text:
Q: Determine whether A is diagonalizable using these three steps. Here is the question:
A is the matrix
$$
        \begin{bmatrix}
        3 & 0 & 0 \\
        0 & 2 & 0 \\
        0 & 1 & 2\end{bmatrix}
$$
(a)find eigenvalues of A
(b)For each eigenvalue λ, find the rank of the matrix  λI-A
(c)Is A diagonalizable? Justify your conclusion.
I learned about geometric multiplicities and algebraic multiplicities btw maybe that will help? anyway please keep it simple. thanks!

A: Without getting too technical, recall that you are trying to decompose $A$ so that
$$A = PDP^{-1}$$
where $D$ is the matrix of eigenvalues along the diagonal and $P$ is the matrix of eigenvectors. Note that in writing this, we have assumed that $P^{-1}$ exists, that is, $P$ needs to be comprised of linearly independent eigenvectors.
If you try to find eigenvectors for an eigenvalue with a repeated root, when you try to solve the system
$$(\lambda I-A)\pmb{x} = \pmb{0}$$
you will get one or more row of zeros in its reduced row echelon form. If there are not enough row of zeros (e.g. the dimension of the eigenspace corresponding to $\lambda$ is too small) you will not have enough vectors to put into the columns of $P$ because the parametric form of the solution to $(\lambda I-A)\pmb{x} = \pmb{0}$ will not have enough parameters for you to construct enough linearly independent eigenvectors (Since your eigenvectors are the columns of $P$, they must be linearly independent or $P^{-1}$ will not exist.
Note that by design, if $\lambda$ is a distinct eigenvalue, $(\lambda I -A)\pmb{x} = \pmb{0}$ will always give you a linearly independent eigenvector (why?). So diagonalizability depends on only the repeated eigenvalues.

A: You are diagonalizable if you have say $k$ eigenvalues with corresponding eigenspaces, so that the sum of the dimensions of the $k$ eigen spaces adds up to the dimension of your vector space. The matrix you gave is not diagonalizable. The idea is you are diagonalizable if you have a basis for the vector space consisting of eigenvectors, so you need $n$ eigenvectors.
The rank comes in when you are determining the dimension of the eigenspaces.
Edit: That matrix is not diagonalizable either (I can tell quickly because it is in its Jordan Normal Form which you can look up if interested).
The idea is this. Say you have a diagonal matrix, where all the entries are non-zero. Then your vector space has a basis of eigenvectors, namely the standard vectors $e_{i}$. It's easy to see they are eigenvectors, since if $A$ is your matrix $Ae_{i}=a_{ii}e_{i}$ (just write out a simple example to convince yourself.
Now things like eigenvalues and dimensions of eigenspaces are not changed by similarity. That means, if $A$ is diagonalizable, in any basis it will have a basis consisting of eigenvectors. So, what you do is you first find the eigenvalues. Above, they are 3 and 2, with 2 having multiplicity 2. Now, what is the dimension of the eigenspace? It is the dimension of the kernel of $A-\lambda I$. The dimension of the kernel is the dimension of the vector space minus the rank of the matrix.
So you compute. For $\lambda=3$ you find the rank is $2$ so the eigenspace has dimension 1. But for $\lambda=2$ you have an eigenvalue with multiplicity 2 but computing gives you rank 2, so the eigenspace corresonding to $2$ has dimension 1. So you don't have enough eigenvectors, the sum of dimensions of eigenspaces is 2 instead of 3, so you are not diagonalizable.
At least that is how I think of this.


text:
Q: Expected momentum of ground state hydrogen $$ I am trying to calculate the expected momentum of an electron in the ground state of hydrogen atom. This is the wave function.

So far I have done this:$$\iiint_V \Psi^* (-i\hbar) \frac {d\Psi} {dr} r^2 sin\theta dr d\theta d\phi$$
But the answer I am getting is $$\frac {i\hbar}{a_b}$$ which looks wrong because it is imaginary. What am I doing wrong?

A: You simply miscalculated the action of $\vec p$ on spherically symmetric functions f(r).
In actuality, your answer should transform vectorially,
$$
\vec p f(r)= -i\hbar \nabla f(r)= -i\hbar~  \hat x ~\partial_r f(r),
$$
so, then, as @KevinDeNotariis suggests,
$$
\langle \vec p \rangle= -i\hbar \int d^3x ~\psi^* \partial_r \psi(r) ~\frac{\vec x}{r} ,
$$
trivially vanishing upon integrating over all directions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass data from xaml.cs to .cs I need to pass some data from .xaml.cs to .cs . These data are email and password that user writes in textblocks on xaml page. Like that
xaml
<TextBox x:Name="email" HorizontalAlignment="Left" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="510" Height="72" Foreground="#FFF1BDBD"/>
<TextBox x:Name="password" HorizontalAlignment="Left" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="72" Width="510" Foreground="#FFF1BDBD">

xaml.cs
public string Email;
public string Password;

public authorize()
{
    this.InitializeComponent();
    button.Click += async delegate
    {
        Email = email.Text;
        Password = password.Text;
        ...
    }
}

I need to pass this Email and Password to some class.cs in which I want to write a method for authorize.
I've tried to find any information about how to do this, but I can't.
So, please help me, if you can, or give me a link, where I can find something about this.
Thanx.

A: I would do it like this:
public static class SomeClass
{
    public static string Email;
    public static string Password;
}

Then you can simply say:
SomeClass.Email = "whatever";


text:
Q: Thread or timer to read sensor data out? My Linux C++ application is periodically reading sensor data. Readout is done by simple file I/O operation (OS is writing to file, application is reading from this file).
Some information about my platform:

*

*I have single core processor with hyper-threading

*sensor data update frequency is 1 second

*application GUI runs in main thread and shouldn't be blocked

I considered two approaches for sensor data read out:

*

*timer running in main application thread

*separate thread with infinite loop which does sensor data readout and then sleeps

Which approach makes more sens, are there any other alternatives ? What are the costs of both solution (e.g. blocking of main thread in first or context switching in second approach) ?

A: I don't know anything about your application or the hardware, but here are a few things to consider:

*

*If you use a thread, you will have to create a communication channel of some sort to tell the main thread that data has been updated. Usually this would be a pipe(), as signals are inherently unreliable and condition locks don't work with I/O multiplexing (i.e. select()/poll()).

*Can you get the entire set of data without blocking? If so, then just reading it in the main thread is probably easier. However, if your read can block you'll probably need some more "keep track of my read state to incorporate it into my central select()", whereas a thread can just block until more data is available.

Thus, neither solution is automatically "easier" to do.
I wouldn't worry about "context switching" for a read that only occurs once per second; that's irrelevant.

A: I believe that cost of the context switch once a second is not an issue even for single-core CPU without hyper-threading especially taking to the account that the application is running in user space, thus is not really time-critical. The polling of your sensor in the main thread complicates the logic of the application. So, I would recommend you to start a thread for that purpose.

A: What else does the main thread have to do? Is it ok if it blocks? If so, then you dont need to do the timer, etc in a separate thread.
If the main thread cant block waiting for the periodic timer, then a separate thread must be created. The communication of data between the threads can be via an object that is accessible to both threads and protected via a mutex (look up pthread_mutex_t), which is quite simple to do.
As for which solution would be better and what are the costs, it depends on what else the main  thread is doing. But for something this simple, either way should be about the same, and the context switching shouldnt affect anything. What should affect performance the most is how performance intensive the reads are.

A: A sleep-loop will skew the timing because each iteration is going to take longer than 1sec. Timers don't have that problem, and they are made for this scenario. So choose a timer.
Performance-wise there is no difference because you are only triggering once a second.

A: If the Linux driver is reading a sensor data and writing it to a device file every second, you shouldn't duplicate the timer logic in your application. It may happen that after 1 second sleep your application will still read the same data as 1 second ago. A better approach would be to have a thread that would call a blocking read on a device file. When new sensor data is available, blocking read returns, the thread can process the data and call read again.


text:
Q: Python XBee not able to send two AT commands I've been trying to get the XBee S2 working with the Raspberry Pi through Python. Though, trying to get multiple responses from AT commands is not working.
I have a loop to send the ATID command 10 times, and using the following code I am trying to get a response:
def get_xbee_reply(self):
  reply = b''
  while True:
    print ("hi")
    char = self.serial.read()
    if (char == b'\r'):
      print("ended reply")
      break
    reply += char
  print(reply)
  return (reply.decode('utf-8'))

The reply I am getting:
hi
hi
hi
ended reply
b'OK'
hi
hi
hi
hi
ended reply
b'555'
id = 555
hi
hi
hi
ended reply
b'OK'
hi

It hangs after getting the second OK message from +++ (which I send before the ATID to prevent falling out of AT mode. If I hit Ctrl + C it breaks and does this again, receiving OK, 555 and OK again before hanging.
The XBee is working through my PC and through Minicom with the Raspberry Pi, so it's not an XBee problem.
Why does it stop after the second 'OK'? Doesn't it stop after OK or is the command not coming through? Even with a time.sleep it doesn't work.
EDIT: added code for sending the ATID command
def send_get_at(self, command):
  self.serial.write(
    (command + '\r').encode('utf-8')
  )
  print (str(command) + " = {}".format(
      self.get_xbee_reply()
    )
  )

A: I definitely recommend switching from "AT mode" to "API mode" on the modules, as it's more flexible and you won't have to worry about whether you're in command mode or not.
You would need to configure the XBee module for API mode (ATAP=1) before you could use the API-mode methods/functions in python-xbee.
It might be helpful to monitor the serial connection between the XBee and Raspberry Pi, but that would likely require some hardware hacking (connecting the Tx and Rx pins to the Rx pins of two serial ports, and having software dump the bytes received on both, with timing; or using a logic probe).


text:
Q: Hi can someone tell me what does the following code do Hi all can someone please tell me what does this line of code do
xdata.yarray[3] = *(ptr++);
xdata.yarray[2] = *(ptr++);
xdata.yarray[1] = *(ptr++);
xdata.yarray[0] = *(ptr++);

I am trying to figure out someone Else's code so having problems
would also appreciate if anyone could offer some useful pointers on the best way to decipher someone Else's code.
Thank you
would the meaning of the code be changed if instead of xdata it was just data

A: Setting arr to the initial value of ptr,  the code fills the values arr[0], arr[1], arr[2], arr[3] into the elements xdata.yarray[3], ..., xdata.yarray[0] -- i.e. it copies a range of four elements in reverse order. As a side effect, it modifies the value of ptr so that it is arr + 4 in the end.
Remember that *ptr is the same as ptr[0], and the expression evaluates *(ptr++) the same but leaves ptr incremented.

A: It is basically copying the array pointer to by ptr to the yarray member of xdata just in reverse order.

A: It assigns the data and increments the pointer so the next assignment can use the next value pointed by ptr.
It's simply equivalent to:
xdata.yarray[3] = *ptr;
ptr++;
xdata.yarray[2] = *ptr;
ptr++;
xdata.yarray[1] = *ptr;
ptr++;
xdata.yarray[0] = *ptr;
ptr++;

A: You have plenty of answers as to what this code does. Presumably, coping the contents of some array pointed to by ptr and storing it in reverse order to another array contained within the struct "xdata".
You asked how you could decipher this on your own, which is an excellent question, best way to learn is to do it yourself. Here's my advice: take what you know, create your own little program based on that, and view the output.
For example, without seeing all of the code, I know you have an array "yarray" of 4 elements, and you're storing values from a dereferenced pointer in to it. You could make a little program like below to see how the code reacts:
void main()
{
    int yarray[4] = {0, 0, 0, 0};
    int my_array[4] = {1, 2, 3, 4};
    int *ptr = my_array;
    int cntr;

    for(cntr = 0; cntr < 4; cntr++)
        printf("then: my_array = %d, and yarray = %d\n", my_array[cntr], yarray[cntr]);

    //Add the code that you're not sure what it does here...
    yarray[3] = *(ptr++);
    yarray[2] = *(ptr++);
    yarray[1] = *(ptr++);
    yarray[0] = *(ptr++);

    //Check out the results!
    for(cntr = 0; cntr < 4; cntr++)
        printf("now: my_array = %d, and yarray = %d\n", my_array[cntr], yarray[cntr]);
}

Now you can see that the code is reversing the order of the contents that ptr is pointing to and storing it in the yarray.
then: my_array= 1, and yarray = 0
then: my_array= 2, and yarray = 0
then: my_array= 3, and yarray = 0
then: my_array= 4, and yarray = 0

now:  my_array= 1, and yarray = 4
now:  my_array= 2, and yarray = 3
now:  my_array= 3, and yarray = 2
now:  my_array= 4, and yarray = 1


text:
Q: RxJava: How to repeat an observable chain when original condition is not met anymore? I'd like to re-subscribe to an observable using repeat(), but the condition that triggers the original observable is not met anymore when the first subscription is finished. How would I re-subscribe the observer in this case?
The code looks something like this:
RxInput.onInput(grid)
    .flatMap(Grid::handle)
    .flatMap(Grid::check)
    .delay(300, TimeUnit.MILLISECONDS)
    .flatMap(Grid::clean)
    .repeat() // Does not work
    .subscribe(g -> {System.out.println("Finished");});

The code of RxInput.onInput() is like this:
public static <T> Observable<T> onInput(T t) {
    return Observable.create(subscriber -> {
        if(InputSystem.isInputOn()) { // This is not true anymore when re-subscribing
            subscriber.onNext(t);
        }
    });
}

A: Given that you seem to want to prevent emissions from initial subscription  if isInputOn is false then define the observable like this:
Observable.defer(
  () -> {
     if (!InputSystem.isInputOn())
       return Observable.empty();
     else
       return yourInput
         .flatMap(Grid::handle)
         .flatMap(Grid::check)
         .delay(300, TimeUnit.MILLISECONDS)
         .flatMap(Grid::clean)
         .repeat();
    })
  .subscribe(...);

A quick extra note, do your damndest to avoid using Observable.create like in your example above. If you do emit things like that then you need to combine your observable with .onBackpressureXXX() because you may get a MissingBackpressureException from operators like flatMap downstream.


text:
Q: MIPS Register comparator Given two input registers in MIPS:
$t0, $t1
How would you figure out which one is bigger without using branches?

A: You can use the SLT/SLTU instruction (Set Less Than [Unsigned]):
SLT $t2,$t0,$t1

or
SLTU $t2,$t0,$t1

If $t0 is less than $t1 then $t2 will be 1, otherwise $t2 will be 0.


text:
Q: Error al crear TRIGGER en mariadb Estoy intentando crear un TRIGGER para que cuando se inserte un employee se verifique si esta en nulo el email y si lo esta pues que inserte una row en la tabla advertencias, pero cuando ejecuto la sentencia me da el error:

[Start] Executing MySQL query... Error: ER_PARSE_ERROR: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'DELIMITER $$
CREATE TRIGGER advertaisment  BEFORE INSERT ON employees FOR ...' at
line 1 [Done] Finished MySQL query.

use classicmodels;
DELIMITER $$
CREATE TRIGGER advertaisment
BEFORE INSERT ON employees
FOR EACH STATEMENT
BEGIN
IF(NEW.email = '' OR NEW.email IS NULL) THEN
INSERT INTO advertencias
    SET id = 0,
    codigo = NEW.employeenumber,
    mensaje = 'Email en empleado vacio proveniente de employees',
    accion = 'insert',
    nombre_tabla = 'employees',
    usuario = CURRENT_USER(),
    fecha = NOW();
END IF;
END;
$$
DELIMITER ;


text:
Q: Swift: Cannot assign to immutable expression of type 'AnyObject?!' I searched, but I didn't find a familiar answer, so...
I am about to program a class to handle parse methods like updating, adding, fetching and deleting.
func updateParse(className:String, whereKey:String, equalTo:String, updateData:Dictionary<String, String>) {

    let query = PFQuery(className: className)

    query.whereKey(whereKey, equalTo: equalTo)
    query.findObjectsInBackgroundWithBlock {(objects, error) -> Void in
        if error == nil {
            //this will always have one single object
            for user in objects! {
                //user.count would be always 1
                for (key, value) in updateData {

                    user[key] = value //Cannot assign to immutable expression of type 'AnyObject?!'

                }

                user.saveInBackground()
            }

        } else {
            print("Fehler beim Update der Klasse \(className) where \(whereKey) = \(equalTo)")
        }
    }

}

As I am about to learn swift at the moment, I would love to get an answer with a little declaration, so that I would learn a little bit more.
btw: I later call this method like this:
parseAdd.updateParse("UserProfile", whereKey: "username", equalTo: "Phil", updateData: ["vorname":self.vornameTextField!.text!,"nachname":self.nachnameTextField!.text!,"telefonnummer":self.telefonnummerTextField!.text!])

A: In swift a lot of types are defined as structs, which are immutable by default.
I had the same error doing this :
protocol MyProtocol {
    var anInt: Int {get set}
}

class A {

}

class B: A, MyProtocol {
    var anInt: Int = 0
}

and in another class :
class X {

   var myA: A

   ...
   (self.myA as! MyProtocol).anInt = 1  //compile error here
   //because MyProtocol can be a struct
   //so it is inferred immutable
   //since the protocol declaration is
   protocol MyProtocol {...
   //and not
   protocol MyProtocol: class {...
   ...
}

so be sure to have
protocol MyProtocol: class {

when doing such casting

A: The error message says, you're trying to change an immutable object, which is not possible.
Objects declared as method parameters or return values in closures are immutable by default.
To make the object mutable either add the keyword var in the method declaration or add a line to create a mutable object.
Also index variables in repeat loops are immutable by default.
In this case a line is inserted to create a mutable copy and the index variable is declared as mutable.
Be careful to change objects while being enumerated, this could cause unexpected behavior
...
query.findObjectsInBackgroundWithBlock {(objects, error) -> Void in
    if error == nil {
        //this will always have one single object
        var mutableObjects = objects
        for var user in mutableObjects! {
            //user.count would be always 1
            for (key, value) in updateData {

                user[key] = value
...

A: using AnyObject keyword fixed my issue:
protocol UpgradeActionProtocol: AnyObject {
    var upgradeAction: Selector? { get set }
}


text:
Q: click on a transparent select don't work on firefox I'm trying to get rid of the default select to use something more aligned to the style of my site.
I created a <button> to wrap the select. Gave it opacity: 0 and absolute positioning and sizing to make it fit the button. With some jquery i made it so that the active option appears also as the text of the button, in a <span>. It looks pretty nice.
The problem is that on chrome and safari works perfectly, on firefox instead quite not!
webkit listen to the click on the select even if it's not visible, moz don't (pretty curious about IE and opera). I really don't know how to solve this...
Here a fiddle with a reproduction of the problem:
http://jsfiddle.net/bakaburg1/YyvRf/2/
Any help is welcome.

A: You can use <div> instead of <button>
HTML:
<div class="btn btn-small select-container">
    <select>
        <option>title</option>
        <option>date</option>
        <option>author</option>
    </select>
</div>

CSS:
.btn.btn-small{
  padding-bottom: 2px;
  padding-top: 2px;
  color: #737373;
  font-family: 'Lucida Sans Unicode', 'Lucida Grande', sans-serif;
  font-size: 14px !important;
  font-variant: small-caps;
  font-weight: bold;
}

.btn.select-container {
  position: relative;
  padding-right: 24px;
}

.btn.select-container select {
  position: absolute;
  top: -1px;
  left: 0;
  height: 117%;
  width: 100%;
  opacity: 0;
  filter: alpha(opacity=0);
  z-index: 1000;
}

select.btn {
  width: initial;
  height: 23px;
  padding-right: 20px;
  -webkit-appearance: none;
}

select.btn:focus {
  outline: none;
}

.select-container {
  position: relative;
}

See it here: http://jsfiddle.net/YyvRf/3/


text: Q: smartgwt listgrid population from excel file data i am providing a support to import the excel file data to the smartgwt ListGrid as a ListGridRecord. and im doing it by providing a textarea on my UI. when i paste the excel data to UI texarea. on Tab out,all the record should be populated into my listgrid. any idea how to do it. Thanks


text:
Q: Moving data from shared_ptr to vector constructor I have a library which contains a function that returns the following:
std::shared_ptr<const uint8_t[]>
and
uint32_t size

I need it to pass it to another API that takes:
std::vector<uint8_t> data

The data contained in the shared_ptr is the exact same data that needs to go into the vector, so a move operation would be ideal.
So my question is this: Is there any way to obtain this without just copying the data? I realize the issue hinges on the fact that shared_ptr will delete the data once it goes out of scope, so I'd like to know if there's a way to circumvent this.
(And if copy is necessary, what is the most efficient method to do so? I'm thinking std::copy or good'ol' memcpy.)

A: No, it isn't possible for a vector to take ownership of a separately allocated array.
If you need a vector, and the source isn't a vector, then you have to copy (you could move individual elements, but that's same as copying in case of std::uint8_t).
If you wish to avoid a copy, then you must change one of the premises: Either start with a vector (if library permits), or don't create a vector.

I'm thinking std::copy or good'ol' memcpy.

The only reason to use std::memcpy over std::copy is to reinterpret the data (std::copy could be used for that as well, but the syntax becomes clunky with the casts that are necessary) which you aren't doing here.
std::copy is fine as well as the vector constructor that accepts a pair of iterators.

I realize the issue hinges on the fact that shared_ptr will delete the data once it goes out of scope, so I'd like to know if there's a way to circumvent this.

Your intuition is correct that releasing the pointer from ownership of the shared pointer would have been necessary in order to achieve what you want. However, it isn't sufficient since you cannot make vector take that ownership.
But regarding whether there's a way to prevent a shared pointer from deleting the owned pointer: Yes, it is possible by writing a custom deleter class. But the library that creates the shared pointer would have to let you be in control of the deleter which I suspect isn't the case.
This would also be quite dangerous since you would have to make sure that whatever takes ownership of the pointer would have to keep it alive at least as long as the longest living shared pointer to the "released" data... which is quite difficult unless you're in control of all of the shared owners.


text:
Q: How to see what's using TempDb space in Azure SQL DW? I'm having problems with TempDb being full. Are there any system views I can see to diagnose what's using up TempDb and/or how much space is still available on it?
It would be awesome to also see the TempDb transaction size limit too if possible.

A: So far, I've found the below, using these pages:
https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-file-space-usage-transact-sql?view=sql-server-2017
https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-io-virtual-file-stats-transact-sql?view=sql-server-2017
sys.dm_pdw_nodes_db_file_space_usage doesn't appear to hold any information about tempDb, so therefore we can only use sys.dm_pdw_nodes_io_virtual_file_stats.
The example in Microsoft's documentation doesn't explain what each file_id means, although the example they give filters on it. Until I can find any more information, I'll sum all files in TempDb as this appears to give the most sensible result (but it's a complete guess!).
        select sum(num_of_bytes_written) from sys.dm_pdw_nodes_io_virtual_file_stats
where database_name = 'tempdb'

I cannot find any documentation of transaction size limits for Azure DW Gen2.
This only applies to gen 1 - https://learn.microsoft.com/en-gb/azure/sql-data-warehouse/sql-data-warehouse-develop-transactions#transaction-size
Edit:
after further experimentation, it appears this query doesn't work either, the storage use always increases, so it appears to be more like a write counter. the size_on_disk_bytes never changes, so I'm not sure this would do it either.


text:
Q: Reset user passwd when you don't know it I have a small problem. I have shared keys setup on my domain, so I never type my password to login anymore.
I've forgotten my password now. This is a problem because only my user can sudo. Password authentication for root has been disabled, so without my password, I cannot do maintenance on my web server.
Is there a way to reset my password as my [now only] key-authenticated user?
Specifically, can this be done on CentOS 4?

A: Aside from finding and exploiting a serious security vulnerability in Linux, I can't see how there could be a way to do this without physical access.

A: I have not done this in a long time so I might be wrong. You can reset the password by rebooting into single-user mode.
Here are some links:
http://www.linuxtopia.org/online_books/centos_linux_guides/centos_linux_step_by_step_guide/s1-q-and-a-root-passwd.html
http://www.centos.org/docs/5/html/Installation_Guide-en-US/s1-rescuemode-boot.html


text:
Q: Detecting TAB keypress and making the script execution conditional I have the following script
   $('.formfield:not(.NoHighlight, #P_PH_PHONE, #P120_PH_EMAIL) :input').focus(function(e){

            var currentElementonForm = $(this);
            if(currentElementonForm.is("input[type=submit]")){
                currentElementonForm.parents('form').submit();
            }

    });

Currently, the page submits when a user tabbed (keyborad TAB button) to the submit button. I would like to stop this but only do it when a user clicked not tabbed to the button. Hopefully, the question is clear and happy to give anymore details. I did try detecting e.keyCode == 9 but it logs it as "undefined".

A: enter code hereEdit : Since keyCode is not working we can approach this problem differently ?
$('.formfield input[type=submit]').click( function() {
      $(this).parents('form').submit();
  });

  $('.formfield:not(.NoHighlight, #P_PH_PHONE, #P120_PH_EMAIL) :input').focus(function(e){
            var currentElementonForm = $(this);
            if(currentElementonForm.is("input[type=submit]")){
                var code = e.keyCode || e.which;
                if (code !== 9) {
                    currentElementonForm.parents('form').submit();
                }

            }

    });

A: I had to find an alternative way to deal with this issue. The problem was on "focus" event does not return a keyCode even when using the TAB key. So had to work with a different solution. This was something new to me and hopefully this might benefit someone having the same issue.


text:
Q: Renaming file name with shell script I have lots of file name like below;
KO.ADVT..HHE.D.2017.163.121959.SAC
KO.ADVT..HHN.D.2017.163.121957.SAC
KO.ADVT..HHZ.D.2017.163.121959.SAC
KO.ARMT..HHE.D.2017.163.121957.SAC
KO.ARMT..HHN.D.2017.163.121957.SAC
KO.ARMT..HHZ.D.2017.163.121956.SAC
KO.BGKT..HHE.D.2017.163.121958.SAC
KO.BGKT..HHN.D.2017.163.121959.SAC
KO.BGKT..HHZ.D.2017.163.121954.SAC
KO.BRGA..HNE.D.2017.163.121955.SAC
KO.BRGA..HNN.D.2017.163.121959.SAC
KO.BRGA..HNZ.D.2017.163.121959.SAC
KO.BUYA..HNE.D.2017.163.121954.SAC
KO.BUYA..HNN.D.2017.163.121955.SAC
KO.BUYA..HNZ.D.2017.163.121956.SAC
KO.CAVI..HHE.D.2017.163.121958.SAC
KO.CAVI..HHN.D.2017.163.121958.SAC
KO.CAVI..HHZ.D.2017.163.122001.SAC
KO.CRLT..HHE.D.2017.163.121958.SAC
KO.CRLT..HHN.D.2017.163.121959.SAC
KO.CRLT..HHZ.D.2017.163.121958.SAC
KO.CTYL..HHE.D.2017.163.122000.SAC
KO.CTYL..HHN.D.2017.163.121959.SAC
KO.CTYL..HHZ.D.2017.163.122004.SAC
KO.DST..HNE.D.2017.163.121959.SAC
KO.DST..HNN.D.2017.163.121957.SAC
KO.DST..HNZ.D.2017.163.121956.SAC
KO.EDRB..HHE.D.2017.163.121959.SAC
KO.EDRB..HHN.D.2017.163.121955.SAC
KO.EDRB..HHZ.D.2017.163.121958.SAC

and I want to change their name like this
ADVT.HHE.KO
ADVT.HHN.KO
ADVT.HHZ.KO
ARMT.HHE.KO
ARMT.HHN.KO
ARMT.HHZ.KO
BGKT.HHE.KO
BGKT.HHN.KO
BGKT.HHZ.KO
BRGA.HNE.KO
BRGA.HNN.KO
BRGA.HNZ.KO
BUYA.HNE.KO
BUYA.HNN.KO
BUYA.HNZ.KO
CAVI.HHE.KO
CAVI.HHN.KO
CAVI.HHZ.KO
CRLT.HHE.KO
CRLT.HHN.KO
CRLT.HHZ.KO
CTYL.HHE.KO
CTYL.HHN.KO
CTYL.HHZ.KO
DST.HNE.KO
DST.HNN.KO
DST.HNZ.KO
EDRB.HHE.KO
EDRB.HHN.KO
EDRB.HHZ.KO

I used this code
 for file in *.SAC
    do
        newfilename="${file:3:6}${file:7:9}"
    echo mv $file $newfilename
    done

but the result like this;
ADVT....HHE.D.2
ADVT....HHN.D.2
ADVT....HHZ.D.2
DST..H.HNE.D.20
DST..H.HNN.D.20
DST..H.HNZ.D.20
.... so on.

How can I get new files names with my code ?
Thanks in advance.

A: With perl rename:
rename -n 's/^(.*?)\.(.*?)\.\.(.*?)\..*/$2.$3.$1/' *SAC

Remove -n switch if the output looks good.
.*? is like .* but not greedy

A: Using bash and awk:
for f in *SAC; do
    echo mv "$f" "$(awk -F. -v OFS=. '{print $2, $4, $1}' <<< "$f")"
done

Remove echo statement if the output looks good


text:
Q: Does javamelody work with spring webflux? can anyone point me to a resource, how I can get spring-webflux and javamelody to work together?
Seems, that a servletcontext is neccessary for startup, which I don't have/need.
I'm aware of the coll metrics stuff, that comes with spring-boot 2.x, but I don't have anything to display the metrics with, and am locked to a company environment, where just installing something isn't a valid option.
Thanks,
Henning

A: javamelody is mainly based on monitoring of memory, cpu, http requests, sql requests and spring components among other things. See javamelody-spring-boot-starter for example.
But as far as I know, Spring webflux does not use the servlet api. So what do you want to monitor?
If you just want to have graphs in a browser, then start a http server for javamelody reports like in standalone. And if you also want to monitor sql requests and spring components, then add in your application all methods from this example, except monitoringSessionListener and monitoringFilter.
A new spring-boot-starter for javamelody in webflux could be created if it makes sense.


text:
Q: getfulltext search result for maximum values I have a table with 3 column. "Name","Address","Description".I have 100 records in it.I am writing a code for search and using getfulltext.I want to get result the maximum number search keywords records should be present to top and so on and i want to fetch all column data also.How will i improve my query.
Thanks
I am writing query like below...
mysql_query("SELECT  * from table WHERE MATCH(name,address,description) AGAINST ('".mysql_real_escape_string($search_text)."' IN BOOLEAN MODE)";

A: I have this trick to get a simple count of keyword
select
  *
from your_table
where
  match(name,address,description) against ($search_string IN BOOLEAN MODE)
order by
  length(concat(name,address,description))-
  length(replace(concat(name,address,description), $search_string, ''))
  /length($search_string)
  desc;


text:
Q: On constructing symmetric positive definite kernels as sums of Gaussians Let $\mathcal{X}$ be a non-empty set. We define $k\colon\mathcal{X}\times\mathcal{X}\to\mathbb{R}$ as a symmetric positive definite kernel. For instance, the Gaussian Radial Basis Function (RBF) is given by
$$
k(\mathbf{x}_i, \mathbf{x}_j)=\exp\Big(-\frac{1}{2}(\mathbf{x}_i - \mathbf{x}_j)^T \Sigma^{-1} (\mathbf{x}_i - \mathbf{x}_j)\Big),
$$
where $\Sigma$ is a symmetric positive definite matrix (a covariance matrix). $k$ expresses the similarity between points $\mathbf{x}_i$ and $\mathbf{x}_j$ anisotropically, as well as isotropically if $\Sigma=\sigma^2I_n$. The latter case gives
$$
k(\mathbf{x}_i, \mathbf{x}_j)=\exp\Big(-\gamma\big\lVert \mathbf{x}_i - \mathbf{x}_j \big\rVert^2\Big),
$$
where $\gamma=\frac{1}{2\sigma^2}$. Let's assume now that we have a set of points $\mathbf{x}_i\in\mathbb{R}^n$, $i=1,\ldots,l$, which are the mean vectors of equal number multivariate Gaussian distributions with covariance matrices $\Sigma_i$.
We would like to construct a kernel function which could express the similarity of two points each of which belongs to some of the above Gaussian distributions. To be more clear, let $\mathbf{x} \sim N(\mathbf{x}_i,\Sigma_i)$, and $\mathbf{y} \sim N(\mathbf{x}_j,\Sigma_j)$, $i,j=1,\ldots,l$. A kernel function with the desired property would be hopefully of the form
$$
k(\mathbf{x}, \mathbf{y})=\exp\Big(-\frac{1}{2}(\mathbf{x} - \mathbf{y})^T \Sigma^{-1} (\mathbf{x} - \mathbf{y})\Big).
$$
However: (a) We must somehow determine the relations between $\mathbf{x}, \mathbf{y}$ and the covariance matrices $\Sigma_i,\Sigma_j$, respectively (i.e., that $\mathbf{x}$ corresponds to $\Sigma_i$, while $\mathbf{y}$ corresponds to $\Sigma_j$). Should we construct a generalized kernel (maybe a hyperkernel similar -not the same- to this) as $k( (\mathbf{x},\Sigma_i), (\mathbf{y},\Sigma_j) )$? Is this possible in terms of preserving symmetry and positive-definiteness? If so, (b) what would be a reasonable candidate covariance matrix $\Sigma$? Intuitively, it should be of the form: $\Sigma=\phi(\Sigma_i,\Sigma_j)$, where $\phi$ is a symmetric function on $\mathbb{S}^{n}_{++}\times\mathbb{S}^{n}_{++}$, where $\mathbb{S}^{n}_{++}$ is the space of symmetric positive definite $n\times n$ matrices. For instance, $\Sigma = \Sigma_i+\Sigma_j$. Is this even rational/feasible/possible?
Please keep in mind that I may be mistaken in any of the above stages. Please feel free to correct me and advice me appropriately! Many thanks!

A: I do not quite understand what you are trying to do. You said you want to define a kernel on $\boldsymbol{x} \sim \mathcal{N}(\boldsymbol{x}_i, \Sigma_i)$ and  $\boldsymbol{y} \sim \mathcal{N}(\boldsymbol{x}_j, \Sigma_j)$.
Why does the distribution of your points $\{ \boldsymbol{x}, \boldsymbol{y} \}$ matter ? In general, you do not need any distribution assumption. If you want to define a kernel on the two distributions directly, an obvious way is to define a kernel on the parameters $\boldsymbol{x}_i, \Sigma_i, \boldsymbol{x}_j, \Sigma_j$. The resulting kernel will depend on parametrization. There are also many kernels on distributions which are independent of parametrization. See, say, Probability Product Kernels. The set $\mathcal{X}$ on which you can define a kernel can contain any kinds of objects. In the latter case, it is a set of distributions.
Updated:
Assume that you want to define a kernel on distributions. Then, the previously mentioned paper is relevant. Further, if your distributions are non-parametric, then you want to search works along the direction of "mean embeddings of distributions". See this Wiki on kernel embedding of distributions. For example, the inner product of mean-embedded distributions in RKHS is a valid kernel for your distributions. This may or may not make sense to you. The point is that given two arbitrary distributions, you can define a kernel on them.


text:
Q: A quick doubt on a Calculus problem I am almost sure the following problem, which is in an exercises list I've gotten assigned from college, is somehow mistated, but anyway, here's the statement:

Based on data compiled by the Group Health Association of America, the
  number of people receiving their care in an HMO (Health Maintenance
  Organization) from the beginning of 1984 through 1994 is approximated
  by the function $f(t)=0,0514t^3-0,85t^2+6,8147t+15,6524$, where $f(t)$
  gives the number of people in millions and $t$ is measured in years,
  with $t = 0$ corresponding the beginning of 1984.
a) At what time, in a given time interval, was the number of people
  receiving medical care in HMO growing most rapidly?

The way I went about it was by calculating $f'$, which gives the rate of rage of the number of people etc., and then trying to find its global maximum, which would give the desired value of $t$, right? However, $f'$ is a parabola, so it never attains a global maximum. So, am I missing something out here or is the problem indeed mistated? Thanks very much in advance.

A: To find the maximum of a function over an interval, you check the points where its derivative is zero and the endpoints of the interval.  In your case the maximum comes at $t=0$.


text:
Q: How to install a service on windows 7 without Visual Studio? Install a windows service: there is a util with Visual Studio: InstallUtil.exe.
If I have a service MyService.exe and want to install it on a windows 7 without Visual Studio on it, how can I install it?

A: You can try NSSM (Non-Sucking Service Manager) for the times the "sc" doesn't work quite as expected.  http://nssm.cc
I had an service I built in Go not too long ago that I could not get to run under "sc", nssm worked perfectly.

A: you can find installUtil.exe at "C:\Windows\Microsoft.NET\Framework\v2.0.50727", launch from CMD prompt, and add the path to your service

A: One way is to use sc.exe, which is part of OS. Example:
sc create **ServiceName** start= auto binPath= "c:\mydir\myService.exe"

where binPath is exe file containing your service.
if you don't want start type = automatic then you can use net start and net stop command on command line of windows to start and stop service respectively.

A: Couldn't get NSSM to work on my W7.  It always put its own path as the path to the program I put in the Path box.  Had to go manual with the sc example above.  That worked perfectly.  To get a list of sc parameters, just execute sc.  The two * preceeding the ServiceName will cause the ServiceName to appear at the top of the C:\Windows\System32\compmgmt.msc list.  To remove a service, use sc delete ServiceName.  You will have focus the list and use the Refresh menu item to see the change in compmgmt.msc.


text:
Q: Confused on the approach I should take for a mud/interactive fiction parser One of the first things that got me into wanting to program was to create a multiplayer text game. I was scared away from the notion though when I realized, at least at the time for me, how complicated writing a smart parser would be.
So now I'm back to thinking about it, and I've tried to do lots of research on the subject. It turns out that it seems to be a lot more involved than I think, and I've stumbled across terms such as lexing and tokenizing and parsing, only the latter of which I knew of before. I figured the field of lexical analysis is what I wanted to look for.
So instead of trying to create my own lexer and parser which I've read to be very difficult and error prone, and most people instruct to steer away from, I thought I would find a good lexer and parser generator to use which will supposedly do all the heavy lifting for me and I can just focus on the grammar that I want. I've also heard lots of people say that individuals looking to do such a thing should simply use Inform.
Sure, I guess Inform is cool, but C# is my language of choice and I like the freedom that it allows me over what I perceive Inform to offer. I'm more interested in creating all the components and framework of the multiplayer text game than I am in any one particular final result, and so I like the idea of using a standard programming language best.
I've been trying to find a good lexer/parser generator for C# for a while now, not really satisfied with all that seems to be offered in terms of the comments people give.
antlr for C# seems to be underdeveloped and mostly an afterthought.
I've tried understanding GPLEX and GPPG but as of right now they are far too confusing for me, despite reading a lot of the documentation and trying to read up a lot on lexing in general.
I have a lot of the concepts in my head about the whole process of lexing, but when faced with a lexer and a parser, I guess I don't really know how these are supposed to be meshed into my actual code.
I want to build a simple English like grammar with noun phrases and verb phrases, and be able to have lists of nouns and verbs that can be dynamically added and ready from a database as the game is developed and expanded upon.
I guess I'm feeling like I'm turning up short on the results of the research I've been trying to do with this subject.
To be honest, the idea of creating my own bastardized notion of a lexer and parser based on what I've researched seems far more appealing at this point than using any lexer/parser generator that I've read about.

A: It depends on what you want to get out of the project.
If this is a learning project to do on your spare time, rolling your own tokenizer and interpreter is a good solution.  While it is hard to do this perfectly, it is fairly easy to make a sufficient parsing layer.  I'd recommend making the most minimal parsing layer you can to start with, and incrementally improving it as you add richness to the game.  This is a good type of problem to practice TDD and design patterns with, if that interests you.  Using those practices will make it easier to incrementally make improvements.
On the other hand, if you will not get a lot of value from that exercise (you're on a tight timeline, this is for real work, you just don't care about the parsing layer, etc), then I suggest making do with an existing parser.  If you encapsulate a third party parser behind an abstraction, you can change your mind later about writing your own, or about what parser to use.
You probably already saw it, but this SO question looks to have a nice list of parsers for c#.

A: First, some meta-advice. This is maybe not a great question for StackOverflow since it is not about a specific technical problem. You might consider asking questions like this on Programmers.StackExchange.com instead.
To address your question: I agree with tallseth; it depends on what skill you want to improve here. People occasionally ask me why I don't build a boat, since I am fairly handy and like sailing. Because you should only build a boat if you like having an unfinished boat in your garage for two years. If you want to sail, sail. If you want to build a boat, build a boat. But don't build a boat because you want to sail. If you want to write a text adventure, learn Inform7; it is the most incredibly awesome tool for making text adventures the world has ever seen. If you want to learn how to make a lexer and parser, then don't mess around with parser generators. Make a lexer and parser.
Parser generators are great if you are prototyping up a new programming language and you want to get going quickly. But programming language grammars can have really nice properties that make them amenable to automatic parser generation in a way that natural languages do not. You're likely to spend as much time fighting with the parser generator as you spend building the grammar if you go with a parser generator approach.
Since you're a beginner at this, I suggest that you recapitulate the history of text adventures. Start by writing a lexer and parser that can parse two-word commands: "go north", "get sword", "drop brick", and so on. That will give you enough flexibility that you can then start solving other problems in text adventure design: how to represent objects and locations. Start small; if you can make a two-room game where the player can pick up and put down objects, you are well on your way.
In short, I strongly encourage you to follow your instinct; writing your own lexer and parser is super fun and actually not that hard if you start small and work your way up.


text:
Q: Should an application be designed without prototyping first? I've just begun using a popular, well-documented graphics engine, and was given a month to create some small programs and get familiar with it.
The library is huge, and there are sections I haven't explored.
Due to a time-crunch, my tech-lead has asked me to start designing my software (sequence and class diagrams) even for the parts I haven't explored, just by looking at the documentation and figuring out the capabilities of those classes.
It's my understanding that designing software requires good knowledge of how something works. Does it make sense to create a design with only a vague understanding of how a class works, just by looking at the class's documentation? Shouldn't I be prototyping it with a small program, tweaking it here and there and understand how it behaves and THEN do the design for it?

A: Your own sequence and class diagrams probably do not depend that much on how the graphics engine behaves. During implementation, you will probably run into little quirks like 'I must call initFoo() before setupBar()' but those details most likely do not affect the design of your classes. Your tech-lead needs your design now, probably because other people depend on it, so I propose you create it.

A: There is a risk: just because the engine is popular and well documented, that might not reflect reality. I did use one game engine recently that used a wiki to documentation how the engine worked. What you found was a mixture of old pages that didn't reflect the most recent version, current pages, and ones that were talking about not yet implemented parts.
If I had been asked to design the application, based on the documentation alone, we would have been promising things that would not be available for years.

A: It is important that you provide a design because some preliminary work needs to go into creating a project.  I like ammoQ's answer as he puts it best.
I would just like to add however that in an ideal world we will have all the time to become experts in an unknown framework or library before we commit to designing a software around something that isn't yet 100% understood.  We do not live in a perfect world however.
Every design document should have an Assumptions section that details every remaining unknown that we still have about aspects of the design.  If for example the documentation for the library claims to have functionality A, but you were not able to figure that out yet in your prototype, then claim it as an Assumption and design accounting for it being true.
You may from time to time find that not all of your assumptions were correct, or that perhaps you missed a few.  At this point you will need to revise your design and cite the failed assumption as a reason, as well as revise estimates going forward.

A:
Shouldn't I be prototyping it with a small program, tweaking it here and there and understand how it behaves and THEN do the designing for it?

That depends on what you want to do

*

*if you want Big Design Up Front, then yes - you do need a detailed understanding of how things work

*if you want some sort of agile iterative and incremental development, then no you do not need a detailed understanding of how the framework works in details. In this case, you should create your design to be flexible and expect the changes to it in the future

The answer is in how your company do things. I personally would choose the second (agile) approach.
By the way, your design shouldn't depend so much on a library's implementation.

A: The answer really depends...
If you want to design a highly maintainable software, in which you can yank out the graphics engine and put in a new one, then you can do a high-level design without getting into too much detail on how to use the graphics engine.
If you want to base your design on that of the graphics engine (high coupling), then you need to know its specifics up front.


text:
Q: c# charting - access from other thread exception Today I was trying to chart data from project where I recieve it by transmitting from my uC via UART.
The program is just to recieve data in interrupt, process it and display.
When program goes to my ChartData method I'm getting an exception:

An unhandled exception of type 'System.InvalidOperationException'
  occurred in System.Windows.Forms.dll
Additional information: Cross-thread operation not valid: Control
  'chart1' accessed from a thread other than the thread it was created
  on.
  It is strange for me - I think that I've got one thread in my program.

I have tried charting with pure project where I create data in Form_Load event - everything works fine.
My source code is here - any idea?
public partial class Form1 : Form
{
    private List<float> freqList = new List<float>();
    private List<float> magList = new List<float>();
    private float[] fFrequency = new float[numberOfSamples];
    private float[] fMagnitude = new float[numberOfSamples];

    public static int counterOfRecBytes = 0;
    public static int numberOfSamples = 512;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        GetAvailablePorts();

        tb_Rx.Text = "Wprowadź parametry transmisji";

        // Default transmission parameters for testing
        cb_BaudRate.Text = "9600";
        cb_Ports.Text = "COM5";
    }

    /// <summary>
    /// Checks avaiable serialports - for linking my device to other computers
    /// </summary>
    void GetAvailablePorts()
    {
        string[] ports = SerialPort.GetPortNames();
        cb_Ports.Items.AddRange(ports);
        //cb_Ports.SelectedIndex = 0;
    }

    private void bt_connect_Click(object sender, EventArgs e)
    {
        if (bt_connect.Text == "Connect")
        {
            if (cb_Ports.Text == "" || cb_BaudRate.Text == "" || cb_Ports.Text == "")
                tb_Rx.Text = "Nie wybrano jednego z parametrów";
            else
            {
                bt_connect.Text = "Disconnect";

                SerialP.PortName = cb_Ports.Text;
                SerialP.BaudRate = Convert.ToInt32(cb_BaudRate.Text);
                SerialP.StopBits = StopBits.One;
                SerialP.DataBits = 8;
                SerialP.Parity = Parity.None;
                SerialP.Handshake = Handshake.None;
                SerialP.ReadBufferSize = 8 * numberOfSamples + 4;

                SerialP.Open();

                pb_connect.Value = 100;
                tb_Rx.Clear();

                cb_Ports.Enabled = false;
                cb_BaudRate.Enabled = false;
            }
        }
        else
        {
            SerialP.Close();

            bt_connect.Text = "Connect";

            pb_connect.Value = 0;

            bt_connect.Enabled = true;
            cb_BaudRate.Enabled = true;
            cb_Ports.Enabled = true;

            freqList.Clear();
            magList.Clear();

            pb_connect.Value = 0;
            tb_Rx.AppendText(Environment.NewLine + "----Zamknięto połączenie----");
        }
    }

    private void SerialP_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        byte[] bArray = new byte[8 * numberOfSamples+4]; // frequencies (512 samples) and magnitudes (512 values) - each is a single precision float so 4 bytes
        float[] fArray = new float[2*numberOfSamples];
        //bool dataStart = false;

        int previouse = counterOfRecBytes;

        counterOfRecBytes += sp.BytesToRead;

        sp.Read(bArray, previouse, (counterOfRecBytes - previouse));

            if (counterOfRecBytes == 8*numberOfSamples+4)
            {
                for(uint i = 1; i < 2*numberOfSamples+1; i++)
                {

                   // if (freqList.Count == numberOfSamples) freqList.Clear();
                   // if (magList.Count == numberOfSamples) magList.Clear();

                    fArray[i-1] = ByteToFloat(bArray, i);
                    if (i < numberOfSamples+1)    freqList.Add(fArray[i]);
                    else    magList.Add(fArray[i-1]);
                }

            //ListToArray();
            ChartData();

               // if (counterOfRecBytes >= 8 * numberOfSamples + 4) sp.DiscardInBuffer();
                counterOfRecBytes = 0;
            }

    }

    /// <summary>
    /// Changes my recieved bArray to single precision floats
    /// </summary>
    private float ByteToFloat(byte[] input, UInt32 i)
    {
        byte[] array = new[] { input[4 * i], input[4 * i + 1], input[4 * i + 2], input[4 * i + 3] };
        return BitConverter.ToSingle(array, 0);
    }

    /// <summary>
    /// Setting chart data
    /// </summary>
    private void ChartData()
    {
        for (int i = 0; i < numberOfSamples; i++)
        {
            chart1.Series["Widmo"].Points.AddXY(freqList[i], magList[i]);
        }

    }

}

Problem solved - what I had to do was putting code below in place of just calling ChartData method:
if (InvokeRequired)
            {
                Invoke(new MethodInvoker(ChartData));
            }
            else
            {
                ChartData();
            }


text:
Q: Security, recovery etc of Letsencrypt certificates I'm looking for a description how to property secure, backup, restore etc Letsencrypt certificates, and how to recover if a server containing such certificates was hacked. Does such a description exist?
Here are some of the questions I'm puzzled about:
It appears that letsencrypt has the notion of an "account" with private keys, but appears there is no problem if some other account wishes to obtain a cert for an already-existing hostname. (Then there are two different keys/certs in the wild for the same hostname at the same time.) Just what is that account for?
Then, just who exactly can revoke a certificate, and what information is needed to do so? (I have not tried to do this.) If the account private key is needed, this would mean I can't revoke a cert if my server was taken over and I have not created an off-site backup of my account credentials (does anybody ever backup Letsencrypt data?) If it isn't needed, anybody can revoke anything, which hopefully is not true. Or is the revocation security also driven by DNS resolution verification?

A: The account is associated with the email address you specify when you create the account. This email address gets notifications when certificates are about to expire.
You can keep the private key on the server using the certificates, or on another machine that doesn't allow incoming connections.
There is nothing wrong with having different certificates for the same hostname.
Let's Encrypt Certificate revocation is possible

*

*From the account that issued the certificate

*Using the certificate private key

*Using a different authorized account

I found that page just by typing "letsencrypt revoke certificate" into Google. It explains the requirements for revocation in detail.


text:
Q: Kick an user from telegram chat with nodejs I'm using that node-telegram-bot-api library and I need to handle users in my group.
When the subscription is expired, I need to kick the user. At the moment I use https://core.telegram.org/bots/api#kickchatmember. In that Way, I ban that user, and for re-add to my group I need to unbanChat and invite with Chat link, I can't re-add without that link.
Is it possible to kick the user without Ban?
I see that I can use exportChatInviteLink method to generate link, but I can Revoked that link after click?


text:
Q: Overriding a resource contained in a jar file I am running a tool (a virtual globe) through code from a jar file. The code reads a resource (an XML file) to provide some configuration options, using syntax like this, in a method of class Config:
URL localURL = Config.class.getResource("Config.xml");

I would like to provide my own Config.xml file with settings that override those in the file contained in the jar file.
I am not clear about how I can do this. I understand that the getResource() method explores the classpath to find the resource. So I thought of this:
- putting a copy of the file with my own settings in a specific directory
- putting this directory in front of the classpath
But to no avail: the getResource() still always loads the resource from the jar file.
I must be missing something ...
I tried removing the Config.xml file from the application jar. That fails: the application fails because getResource() returns null. It seems to me like
Config.class.getResource("Config.xml")

only looks for resources inside the jar file that contains class Config, whereas I thought it was looking in the classpath.

A: OK, got it. The issue is this: my Config class is really in a package, i.e. vis.globe.Config.java, so getResource("Config.Xxml") really looks for a file called vis.globe.Config.xml.
Therefore, with a classpath such as "../config:../jar/appl.jar", it will look for file Config.xml, not in ../config, but in ../config/vis/globe.
So the solution was to create a sub-directory structure in ../config that reflects the fully qualified name of class Config.java, i.e.
../config/vis/globe/Config.xml

A: You could always look to do something programmatically. So for example you would first search for a file named UserConfig.xml and if it was not found fall back on the file named Config.xml which would be found in the jar file.


text:
Q: remove empty tags and the parent if empty as well from xml using python I am new to python and trying to use lxml to remove the empty tags from XML. I want to get rid of all empty elements and if by doing that parent is empty as well, I want to remove it as well.
Actual XML
<magento_api>
  <data_item>
    400
    <message>Attribute weight is not applicable for product type Configurable Product</message>
  </data_item>
  <data_item>

    <message>Resource data pre-validation error.</message>
  </data_item>
  <data_item>
    1
    <message></message>
  </data_item>
  <data_item>

    <message></message>
  </data_item>
</magento_api>

Modified XML
<magento_api>
  <data_item>
    400
    <message>Attribute weight is not applicable for product type Configurable Product</message>
  </data_item>
  <data_item>
    <message>Resource data pre-validation error.</message>
  </data_item>
  <data_item>
    1
  </data_item>
</magento_api>

I have used something like below but it ain't working
from lxml import etree

def recursively_empty(xml_element):
   if xml_element.text:
       return False
   return all((recursively_empty(xe) for xe in xml_element.iterchildren()))

data = """
<magento_api>
<data_item>
 400
<message>Attribute weight is not applicable for product type Configurable Product</message>
</data_item>
<data_item>
400
<message></message>
</data_item>
<data_item>

<message>abc</message>
</data_item>
<data_item>

<message></message>
</data_item>
</magento_api>
"""

xml_root = etree.fromstring(data)

for action, xml_element in xml_root:
    parent = xml_element.getparent()
    if recursively_empty(xml_element):
        parent.remove(xml_element)

print (etree.tostring(xml_root))

A: One thing you could do is use the normalize-space() xpath function on each element to get the string value. If it's empty, remove the element.
Example...
Python (Note: I used your "Actual XML" example; not the XML you had in your Python.)
from lxml import etree

data = """
<magento_api>
  <data_item>
    400
    <message>Attribute weight is not applicable for product type Configurable Product</message>
  </data_item>
  <data_item>

    <message>Resource data pre-validation error.</message>
  </data_item>
  <data_item>
    1
    <message></message>
  </data_item>
  <data_item>

    <message></message>
  </data_item>
</magento_api>
"""

parser = etree.XMLParser(remove_blank_text=True)
xml_root = etree.fromstring(data, parser=parser)

for xml_element in xml_root.iter():
    content = xml_element.xpath('normalize-space()')
    if not content:
        xml_element.getparent().remove(xml_element)

print(etree.tostring(xml_root, pretty_print=True).decode())

Output
<magento_api>
  <data_item>
    400
    <message>Attribute weight is not applicable for product type Configurable Product</message>
  </data_item>
  <data_item>
    <message>Resource data pre-validation error.</message>
  </data_item>
  <data_item>
    1
  </data_item>
</magento_api>


text:
Q: How can I Consume a Soap message with Namespace from salesforce in PHP I am new to salesforce.  Proficient in php but I haven't done any xml parsing.  I have this file which I can consume.  It is created when a salesforce object changes:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
 <notifications xmlns="http://soap.sforce.com/2005/09/outbound">
  <OrganizationId>00D30000000opwSEAQ</OrganizationId>
  <ActionId>04k30000000L6QPAA0</ActionId>
  <SessionId xsi:nil="true"/>
  <EnterpriseUrl>https://na1-api.salesforce.com/services/Soap/c/22.0/00D30000000opwS</EnterpriseUrl>
  <PartnerUrl>https://na1-api.salesforce.com/services/Soap/u/22.0/00D30000000opwS</PartnerUrl>
  <Notification>
   <Id>04l3000000JbKClAAN</Id>
   <sObject xsi:type="sf:Account" xmlns:sf="urn:sobject.enterprise.soap.sforce.com">
    <sf:Id>0013000000ooziWAAQ</sf:Id>
    <sf:BillingCity>New York</sf:BillingCity>
    <sf:BillingCountry>US</sf:BillingCountry>
    <sf:BillingPostalCode>10000</sf:BillingPostalCode>
    <sf:BillingState>New York</sf:BillingState>
    <sf:BillingStreet>302 E xxx St Apt C</sf:BillingStreet>
    <sf:FN__Mapping_Status__c>Not Located Yet</sf:FN__Mapping_Status__c>
    <sf:IsDeleted>false</sf:IsDeleted>
    <sf:Member_Status__c>Active</sf:Member_Status__c>
    <sf:Name>Joel Test</sf:Name>
   </sObject>
  </Notification>
 </notifications>
 </soapenv:Body>
</soapenv:Envelope>

I need to parse it so that I can take the values in the sf namespace and update a database.  I can use SimpleXML to read stuff no in namespace, but I haven't been able to read namespace values.  Can someone point me to example code or tutorial on how to do this?

A: PHP's SimpleXML will not work for reading namespace information. See this - http://www.w3schools.com/php/php_xml_simplexml.asp . Instead try something like this http://www.php.net/manual/en/function.xml-parser-create-ns.php

A: It looks like that is a SOAP message from the Outbound Messaging feature in Salesforce. Instead of treating it as just XML, try using the native PHP SoapServer with the WSDL provided in Salesforce, as it is designed to handle SOAP messages like this. You can get the WSDL at Setup | Create | Workflow & Approvals | Outbound Messages |  | Endpoint WSDL. You might also want to look at the Salesforce PHP Client, which uses the corresponding PHP SoapClient and has a utility for handling the sf: namespace and converting to a SObject object. It shouldn't be too hard to rewire the toolkit to act as a server instead of a client so you can handle the Outbound Messages.

A: PHP's SimpleXML may work for the case. Just need to use children() and use the right syntax.
Therefore, to read the field value BillingCity in Salesforce Outbound Message, you may use following code:
$rcXML->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://soap.sforce.com/2005/09/outbound')->notifications->Notification->sObject->children('urn:sobject.enterprise.soap.sforce.com')->BillingCity

To help you understand how it works, I write a post with sames code and xml which shall be easier to understand.
http://amigotechnotes.wordpress.com/2013/11/16/parse-xml-with-namespace-by-simplexml-in-php/
Once you may read the filed value, you may store it to other database or text file with PHP.


text:
Q: Tangents to a parabola that go through the same point The question is: The two lines tangent to f (x) = $x^2$ + 4x + 2 through the point (2, -12)have equations y = ax + b and y = cx + d, respectively. What is the value of a + b + c + d?
What I did to solve it:
f '(x) = 2x + 4. The point is (2 -12) so I plugged in two to get f '(2) = 8. I used this in point-slope form to get y + 12 = 8(x-2) => y = 8x -28. Since it is two equations, I added them up and multiplied by 2 and got -40, which is the answer. I feel like this is a fluke and it doesn't make sense to me why this worked. Can someone explain either why it works or a way that will always work? Thanks in advance!

A: This is no coincidence, or if it is, it's a happy one.
Let $P_0=(x_0,y_0)$ be the given external point and $x_1$ and $x_2$ the ordinates of the points of tangency. The equations of the two tangent lines are $y=f'(x_1)(x-x_0)+y_0$ and $y=f'(x_2)(x-x_0)+y_0$. On the other hand, the equation of the line that you found is $y=f'(x_0)(x-x_0)+y_0$. So, for the given parabola, we have $$f'(x_1)+y_0-f'(x_1)x_0+f'(x_2)+y_0-f'(x_2)x_0 = 2(f'(x_0)+y_0-f'(x_0)x_0)$$ or $$(1-x_0)(f'(x_1)+f'(x_2))+2y_0 = 2(1-x_0)f'(x_0)+2y_0$$ which reduces to $$f'(x_1)+f'(x_2)=2f'(x_0).\tag{1}$$
As it turns out, this holds for any parabola given by the general formula $f(x)=ax^2+bx+c$. The ordinates of the points of tangency are the solutions to $$f(x)-y_0=f'(x)(x-x_0),$$ which after expanding, rearranging and simplifying becomes $$x^2-2x_0x+{y_0-bx_0-c\over a}=0.\tag{2}$$ On the other hand, substituting the general formula into (1) yields $x_1+x_2=2x_0$, which can be verified by a glance at (2).
Observe that this last equation tells us that $x_0$ is midway between $x_1$ and $x_2$, which means that the chord connecting the two tangent points is parallel to the tangent at $x=x_0$. This follows from general properties of parabolas, but can be verified directly: $$\begin{align} f(x_2)-f(x_1) &= f'(x_2)(x_2-x_0)-f'(x_1)(x_1-x_0) \\ &= (2ax_2+b)(x_2-x_0)-(2ax_1+b)(x_1-x_0) \\ &= (2a(x_1+x_2-x_0)+b)(x_2-x_1) \\ &= (2ax_0+b)(x_2-x_1) \end{align}$$ therefore $${f(x_2)-f(x_1)\over x_2-x_1}=2ax_0+b=f'(x_0).$$ A similar derivation demonstrates that for an arbitrary chord, the tangents at its endpoints intersect at a point with ordinate halfway between the ordinates of those endpoints. Combining this with (1), we find that the slope of a chord is equal to the average of the slopes of the tangents at its endpoints.

A: Look at the figure:

The point $A=(2,-12)$ is not a point of the parabola, so the slopes of the tangents to the parabola from this point cannot be be simply derived starting from  the derivative of the parabola at $x=2$.
If $P=(X,X^2+4X+2)$ is a point of tangency (the points $C$ and $D$ in the figure), than the slope $m=(y_P-y_A)/(x_P-x_A)$ of the line $PA$ must be the same as the slope of the tangent to the parabola in $P$, i.e.: $m=f'(x_P)$ . So, For our $A$ and $P$ we have:
$$
\frac{X^2+4X+2+12}{X-2}=2X+4
$$
Solving this equation we find the coordinates $x_C$, $x_D$ of the two points of tangency, from wich we can find the equations of the two tangent lines.
Another simple solution, without using derivative, is to note that the system:
$$
\begin {cases}
y=x^2+4x+2\\
y+12=m(x-2)
\end{cases}
$$
represents the intersection between the parabola and the lines that passe thorough $A$, and a line is tangent  to the parabola if  the system has only one (double) solution.  This means that the discriminat $\Delta(m)$  of the second degree equation  that solve the system is such that: $\Delta(m)=0$ .
Since $\Delta(m)$ is a second degree polynomial in the parameter $m$, this is a second degree equation in $m$ that gives the two values of $m$ for the slopes for the two tangent lines.


text:
Q: Measure width and height of a layout larger than the screen How do we get the width and height of a layout (Eg. LinearLayout) if its width and height is larger than the screen?
I can only get the size that is as big as the screen using getWidth() and getHeight().
Is this even possible?

A: Try this-
View view = getLayoutInflater().inflate(R.layout.your_activity, null);
LinearLayout linearlayout = (LinearLayout)view.findViewById(R.id.yourlinearlayout);
linearlayout.measure(0,0);
int width = linearlayout.getMeasuredWidth();
int height = linearlayout.getMeasuredHeight();


text:
Q: Convert complex SQL query to LINQ for rest api I have two tables , one with accounts transactions and another one with account codes. I would like to get list of account names and its current account balance. below sql code works fine for me, but now I am moving to rest api in which I need Linq query.
Please help me to convert below SQL Query for Entity Framework LINQ Query
select
    ac.AccountCode,
    COALESCE(SUM(Credit), 0) - COALESCE(SUM(Debit), 0) as Balance
from
    tblTransaction t
inner join
    tblAccountCodes ac on t.accredit = ac.AccountCode
                       or t.AcDebit = ac.AccountCode
where
    Transaction_Type in ('T_', 'P_', 'R_')
    and Creatd_Date >= '1999-01-01'
    and valid = 'valid'
    and Creatd_Date <= '3/10/2021'
    and branch = 'MAIN'
    and ac.Branch = 'MAIN'
group by
    AccountCode ;

Any help will be highly appreciated, I need to convert exact query to LINQ as in my transaction table I'm using two column for credit and debit.
What I have tried, but says Operator '||'cannot be applied to operands of type 'string'and 'string'
var credibalance = from trans in aceMoneyDb.tblTransactions
                   //where t.UID == userId
                   join acs in aceMoneyDb.tblAccountCodes
                            on (trans.AcCredit || trans.AcDebit) equals acs.AccountCode
                   into alldata
                   from data in alldata.DefaultIfEmpty()
                   select new
                          {

                              AccountCode = data.AccountCode == null ? "-" : data.AccountCode,
                              Balance = trans.Credit == null ? 0 : trans.Credit,

                          };

A: This LINQ query should be closer to your SQL. Main idea that such inner join can be defined by SelectMany and Where:
var transactionTypes = new []{"T_", "P_", "R_"};
var startDate = new DateTime(1999, 1, 1);
var endDate = new DateTime(2021, 3, 10);

var credibalance =
    from trans in aceMoneyDb.tblTransactions
    from acs in aceMoneyDb.tblAccountCodes
        .Where(acs => trans.AcCredit == acs.AccountCode || trans.AcDebit == acs.AccountCode)
    where transactionTypes.Contains(trans.Transaction_Type)
        && trans.Creatd_Date >= startDate && trans.Creatd_Date <= endDate
        && trans.valid == "valid"
        && trans.branch == "MAIN"
        && acs.branch == "MAIN"
    group trans by new { acs.AccountCode } into g
    select new
    {
        AccountCode = g.Key.AccountCode ?? "-",
        Balance = ((double?)g.Sum(t => t.Credit) ?? 0) - ((double?)g.Sum(t => t.Debit) ?? 0),
    };


text:
Q: assign a attribute using getattr I try to assign value to attributes of some calss
like the following:
for name in dir(modelType):
      if request.get(name):
            getattr(model, name) = request.get(name)

but get the excption:
"can't assign to function call"
how can I change attributes without knowing them at complie time?

A: setattr(model, name, request.get(name))

but I'd recommend saving request data in a dictionary, dedicated class, or accessing it directly - unless you're doing specific metaprogramming/introspection, setattr is often the wrong tool for the job.

A: You use setattr() to assign values to attributes.
See:  http://docs.python.org/library/functions.html#setattr


text:
Q: Use gperftools' heap profiler to profile libc malloc I am trying to profile an application to compare its performance using different allocation strategies.
I have no trouble profiling it when using tcmalloc but how to profile it using libc's allocation functions ? Indeed, enabling gperftool's heap profiler requires to use -ltcmalloc flag¹ but this results as tcmalloc being used as allocation strategy.

A:
how to profile it using libc's allocation functions?

Note: this requirement is a bit strange: it's not like your application will suddenly start using more or less heap memory, or change its allocation pattern or sites when you switch from tcmalloc to GLIBC malloc.
From https://gperftools.github.io/gperftools/heapprofile.html:

Heap profiling requires the use of libtcmalloc. This requirement may be removed in a future version of the heap profiler, and the heap profiler separated out into its own library.

So you can

*

*wait for Google developers to remove this requirement (this may be a wait of a few days, or a few years -- I have no idea. Actually, it looks like above github.io page hasn't been updated since 2012, so I wouldn't hold my breath here), or

*contribute the code required for separation yourself, or

*find an equivalent way to do this with GLIBC (and possibly contribute that code to GLIBC).

I am not aware of any existing GLIBC equivalents that work today.


text:
Q: Docker ports not mapping from Docker's tutorial I am working through the tutorial on Docker's website and am having trouble getting the ports to map like described.
I am exposing the port in my Dockerfile with EXPOSE 80 and running docker run -p 4000:80 containername to start the application. The code is copied directly from the tutorial, but for completeness sake the flask server starts with:
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

When I go to localhost:4000 in my browser or curl it I get that the site can't be reached.


text:
Q: Loading *.rvc files from TNTmips into QGIS? I have many files obtained for a class I took in 2004. We used TNTmips to work with these files.
The file extensions are ".rvc". They show up as executable files in Mac Finder. I remember seeing somewhere that the TNTmips software used the ".rvc" file format for vector data, raster data, and -- something else.
It has been so long that I do not remember what our class used these files for, or how we used them.
Can files with the ".rvc" extension be loaded into QGIS? If so, how?

A: I have also used TNT Mips and the dreaded RVC format in my faculty.
The RVC is a container object, similar to ESRI's geodatabase format, and as far as I know it is a thoroughly closed format. I think to only way to open it is to get yourself a copy of TNT Mips and export the data from RVC to something more interoperable.


text:
Q: js -- code: 'SELF_SIGNED_CERT_IN_CHAIN' У меня есть простенький запрос API из POSTMAN который выдает ошибку SSL. В PHP это решалось добавлением CURLOPT_SSL_VERIFYPEER => false. Как это сделать в js?
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic YWRtaW478378378273cmdrNiFAIzQ=");
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Cookie", "SoapSession.id=C0F96erererDB11671548137398; JSESSIONID=243FEB15643ererre8E1144D0E73E0C; JSESSIONIDSSO=D546EDererer5A5332EA92A18CFC80");

var raw = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soap=\"http://schemas.cisco.com/ast/soap\">\r\n   <soapenv:Header/>\r\n   <soapenv:Body>\r\n      <soap:selectCmDevice>\r\n         <soap:StateInfo></soap:StateInfo>\r\n         <soap:CmSelectionCriteria>\r\n            <soap:MaxReturnedDevices>1000</soap:MaxReturnedDevices>\r\n            <soap:DeviceClass>Phone</soap:DeviceClass>\r\n            <soap:Model>684</soap:Model>\r\n            <soap:Status>Any</soap:Status>\r\n            <soap:NodeName>uc-ucm-1.domain.com</soap:NodeName>\r\n            <soap:SelectBy>DirNumber</soap:SelectBy>\r\n            <soap:SelectItems>\r\n               <soap:item>\r\n                  <soap:Item></soap:Item>\r\n               </soap:item>\r\n            </soap:SelectItems>\r\n            <soap:Protocol>Any</soap:Protocol>\r\n            <soap:DownloadStatus>Any</soap:DownloadStatus>\r\n         </soap:CmSelectionCriteria>\r\n      </soap:selectCmDevice>\r\n   </soapenv:Body>\r\n</soapenv:Envelope>";

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://uc-ucm-1.domain.com:8443/realtimeservice2/services/RISService70", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

Получаю такую ошибку:
error TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: self-signed certificate in certificate chain
      at TLSSocket.onConnectSecure (node:_tls_wrap:1538:34)
      at TLSSocket.emit (node:events:513:28)
      at TLSSocket._finishInit (node:_tls_wrap:952:8)
      at ssl.onhandshakedone (node:_tls_wrap:733:12) {
    code: 'SELF_SIGNED_CERT_IN_CHAIN'
  }
}


text:
Q: How do I reference images in a specfic folder called "images" two subdirectories in I have tried */./images/ and other variations with no success.
Where does the directory of images start? Anything under the directory the script will read. With Trailing slash
$files_path="/";
//Enter the full server path to where the directory starts.
$full_server="c:/xampp/htdocs/location/video/";


text:
Q: My simulation is not never finishing and it is taking so much time? I am running simple code which involves calculation of two first order differential equations.It is taking so much time and i am unable to get the results as the simulation is never finishing.
Remove["Global`*"]

(* Parameters *)

a = 10^-9;
\[Epsilon]0 = 8.85*10^-12;
k1 = 10;
k2 = 10;
e = 1.6*10^-19;
u = ((1/3)*e) ;     (*jouls *)
h = 6.6*10^-34;
\[Delta] = 6.6*10^-9;
d = 100*10^-9;
r = 1;
m = 9*10^-31;
f = 10000;
v0 = 7.5;
T = 5/f;
v[t] = v0*Sin[2*\[Pi]*1*t];
c0 = (a*\[Epsilon]0*k1)/d;

(* Equations *)

c = c0/(1 + (((\[Delta]*q1[t])/(d*q[t]))));

(*Q1 and Q2 are assumed separetly but q+ and q- are assumed together*)

eQ = (q[t] + q1[t])/(2*a*\[Epsilon]0*k2);
vk = eQ*\[Delta];

qq = NDSolve[{q'[t] == v[t]/r - q[t]/r*(1/c),
    q1'[t] == (((q[t] + q1[t])/(2*a*\[Epsilon]0*k2))*\[Delta]),
    q[0] == 10*10^-9, q1[0] == 10*10^-9}, {q, q1}, {t, 0, 5},
   MaxSteps -> Infinity, AccuracyGoal -> 20];

Plot[Evaluate[q1[t] /. qq], {t, 0, 5}, PlotRange -> All]

Plot[Evaluate[q[t] /. qq], {t, 0, 5}, PlotRange -> All]

Can anyone help me?

A: The reason it's not finishing is that you set MaxSteps -> Infinity with a high AccuracyGoal.
We can actually solve this system analytically, by replacing NDSolve with DSolve:
qq = DSolve[{q'[t] == v[t]/r - q[t]/r*(1/c),
    q1'[t] == (((q[t] + q1[t])/(2*a*ϵ0*k2))*δ),
    q[0] == 10*10^-9, q1[0] == 10*10^-9}, {q, q1}, t];

We can inspect the solution:
Rationalize@ComplexExpand[q[t] /. qq]

Which contains a lot of terms like
1.06621*10^-8 E^(-1.12756*10^12 t)

Huge numbers in the exponent like that make me think that this problem is poorly conditioned.  You may want to double-check the values of your constants.

The "easy" solution to this problem is just to reduce the integration time.  Leaving the entire code unchanged, we replace the time 5 with a more reasonable value, like 5*^-11:
qq = NDSolve[_, {t, 0, 5*^-11}, ___];

Plot[_, {t, 0, 5*^-11}, ___]

This results in the plots:

You may want to consider changing your units.  Some of Mathematica's integration and plotting algorithms can have trouble with a mixture of very large and very small numbers.
Instead of SI units (meters, seconds, etc.) I would use something like atomic units instead.  In this system the relevant constants become a bunch of nice numbers:

*

*$h = 2\pi$

*$m_e = 1$

*$m_p \approx 1836~m_e$

*$e = 1$

*$k_e = 1$

*$c = \alpha^{-1} \approx 137.035999$

*$\ldots$

This will help prevent you from encountering numerical problems later on down the road, but will also give you a more intuitive feel for the size of the numbers involved.  For example, consider the length $10^{-10}~\text{m}$.  I have no idea what that means, I'd have to think about the exponent for a little while.  In atomic units, the same length is represented by $1.89~a_0$, which I now instantly know is about twice the radius of the hydrogen atom.


text:
Q: Position a element to bottom-right corner on any device using Anime.js

function goBottomRight(){

  anime({
    targets: '.btn',
    translateX:  240,
    translateY:  320,
    easing: 'easeInOutQuad'
  }).play;

}
<button class='btn' onclick='goBottomRight()'>Click Me</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.min.js"></script>

I am attempting to create a animation using anime.js where you click an element it will go to the bottom-right corner of the page but at the same time i need it to be responsive for desktop and mobile.
Here is my code so far.
function goBottomRight(){

  anime({
    targets: '.btn',
    translateX:  240,
    translateY:  320,
    easing: 'easeInOutQuad'
  }).play;

}

Well above code works on a fix screen resolution but how can i ensure that its always go to the bottom-right corner of the page?

A: Set your element to be position: fixed;
Position fixed will cause your element to be always visible on that position. Do keep in mind z-index because if it isn't the last element in your document it might vanish under other elements or elements that have a higher z-index.
Then animate it to position: right:0px; bottom: 0px;
This will then give the desired behavior on any screen.

function goBottomRight()
{
  var element = document.querySelector('.btn');
  element.style.position = 'fixed';
  anime({
    targets: element,
    right:  '0px',
    bottom:  '0px',
    easing: 'easeInOutQuad'
  });
}
<button class='btn' onclick='goBottomRight()'>Click Me</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.min.js"></script>


text:
Q: How does one detect a browser's cache settings (on/off) How does one detect a browser's cache settings either client side or server side (ASP.NET).  Basically trying detect if the users browser has caching on or off. If it's off, I'd like to either redirect them to a page with error message to tell them to turn it on.  Is this possible?

A: You can't reliably detect cache settings as this information is not passed on from the browser.
If resources that should be cached are being requested repeatedly from the browser, this may be an indication that caching is turned off, but that might not be the case.
As for wanting to redirect to an error page - some browsers and environments simply do not have caching, do you want to penalize these users?
Caching is a mechanism to reduce load by reducing the number of requests, don't use it for anything else.

A: A browser doesn't send out its cache setting to the server.
Maybe you are trying to make some of your page components (images, scripts, etc.) load / interact smoother? If it is, maybe you could try to optimize your page (e.g. sprite, minimized JavaScript) so you don't have to worry too much whether the browser decides to cache your page.
Also, in general, rather than redirecting to a different page, you might also consider simply showing a message on the same page (i.e. 1 less HTTP request).


text:
Q: WPF ComboBox in DataGrid Doesn't Display Selected Value I have a datagrid with a template column and a combobox inside it. I also have another combobox which is not inside the datagrid:
<DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True"
        ItemsSource="{Binding Source={StaticResource asientoDetallesAsientosViewSource}}"
        Name="detallesAsientosDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" >
<DataGrid.Columns>
    <DataGridTemplateColumn Header="Cuenta">
        <DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
                <ComboBox Grid.Column="1" Grid.Row="0"
                            Name="combo1"
                            ItemsSource="{Binding Source={StaticResource cuentaListaViewSource}}"
                            SelectedValuePath="Numero"
                            DisplayMemberPath="Nombre"
                            SelectedValue="{Binding ElementName=detallesAsientosDataGrid, Path=SelectedItem.Numero}">
                    <ComboBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel />
                        </ItemsPanelTemplate>
                    </ComboBox.ItemsPanel>
                </ComboBox>
            </DataTemplate>
        </DataGridTemplateColumn.CellEditingTemplate>
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Numero}" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<ComboBox Name="combo2"
            ItemsSource="{Binding Source={StaticResource cuentaListaViewSource}}"
            SelectedValuePath="Numero"
            DisplayMemberPath="Nombre"
            SelectedValue="{Binding ElementName=detallesAsientosDataGrid,
                            Path=SelectedItem.Numero}"
            VerticalAlignment="Center" Width="120">
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
</ComboBox>

Now the strange thing and the problem is that in this case the combo1 inside the datagrid, when in edit mode, shows correctly the selected row value BUT if I delete the combo2 the combo1 stops working and doesn't anymore show the selected row value but instead the first value of the combobox list.
Why does it happen? The combo2 is exactly the same combobox as the combo1.

A: They both bind to the same SelectedValue.  If you delete (edit) the SelectedValue then the selected value is no longer in the ItemsSource.   If you select (not edit) a value from the pull down does it work?


text:
Q: Screen Orientation Changing Handler fails in TabActivity I am developing an Android application with a TabHost in it SDK 7.
My problem is the screen orientation changing handler fails to do the job.
This is the scenario:

*

*The screen is updated well when switching between portrait to landscape and vise versa.

*The screen fails to be updated whenever the black screen (screen saver) is ON or I press the lock button.

What I mean by "fail" to update the screen is:

*

*When in landscape mode, I press the lock button. After it, I unlock
it in portrait mode, the portrait screen is perfectly updated. But,
once I rotate to landscape mode, the screen fails to be updated in
landscape mode. The landscape mode will be perfectly updated again
after I rotate to portrait once again then rotate it again to
landscape.  When in portrait mode, I press the lock button, none of
the fail scenario like above is happened.

This is the method that I used:

*

*I apply: android:configChanges="keyboardHidden|orientation" in every sceen (both TabActivity and each child of it)

*I apply: onConfigurationChanged() in every child screen

*I didn't use any landscape res (layout-res and drawable-land). Thus, I only use one xml layout for a screen (landscape and portrait)

Any suggestion or a workaround for my problem? I will appreciate and try every suggestion. Thank you :D

A: Your solution should be to handle configuration changes properly. Using configChanges is only an optimization for very edge case situations, but you still need to be prepared for the case when your Activity state is saved and your Activity destroyed to relieve memory pressure.
In your Activity:
@Override
public void onSaveInstanceState(Bundle outState) {
    // Put any temporary state for this Activity instance
    // into the outState bundle
}

Then in onCreate():
@Override
public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        // Retrieve and reassign any state that you saved
    }
}

Also see Handling Runtime Changes


text:
Q: How to visually position image before heading element Quite often we find ourselves wanting to do this:

A Widget

Here's the description of a great widget

Semantically the above is wrong because I believe the image should come after the heading, rather than before it.  To get round this issue I've always done something like this:

A Widget

Here's the description of a great widget

...and then CSS as follows:
.product {
    position: relative;
    padding-top: 220px;
}

.product img {
    position: absolute;
    top: 0;
    left: 0;
}

This means the HTML markup is in a better order, but visually the image appears before the heading, which is what I want.
The problem is that now I am making responsive websites, the image width (and height) can scale to an unknown size.  This means that it's not possible to know how much padding to apply to the top of the container to accommodate the absolutely positioned image.
Is there another solution, other than to place the image before the heading, which feels dirty, dirty, dirty to me.

A: If you know the ratio of the image you could try to work with percentages.
.product {
    position: relative;
    padding-top: 66%;
    /* The ratio of the image is 3/2 (300x200).
       When 100% wide it's 66% high. So you can add padding of 66%. */
}

.product img {
    position: absolute;
    top: 0;
    left: 0;

    width: 100%;
    height: auto;
}

And remove width="" and height="" in the img tag.

A Widget

Here's the description of a great widget

A: For situations like this, I'd forgo the very minor semantic issue and order the elements in such a way that requires the least amount of trickery to put them where I want them. In your case, I'd let the img come before the h1 and leave it at that.
However, if you were dead set on ordering them "correctly", you could use jQuery to dynamically change the padding-top in your example, based on the height of the img in question.
Here's an example on jsFiddle.