Ionic Blank Screen in Browser and on Android

Question: I got the task to check out an Ionic-Application and the Source-Code. I have a compiled .apk File which works perfect on Android. Now I checked out the project. It is written with Typescript and AngularJS, everything seems normal. I went into the Ionic folder and did ionic add platform android and then created a valid apk-File. However it doesn't work i only get a blank screen. The file size of my apk and the one which works is quite the same.
In Webstorm I tried running it in the Browser, by doing run-configuration and then Run Browser. There I also get a blank page. The top URL points to the right starting point. In the Developer Tools everything seems normal. I see all the Script Sources and Console-Messages. The only thing is, that he says he is missing the Keyboard plugin, but I guess, that's not really relevant.
So what are my options? There is no one of the Developers left in our company, so no one we can ask, how they compiled the App. There is a package.json, where there are cordova-plugins defined even the keyboard. There is also a gulp-file which seems to only compile the Sass and do something with Bower.
I can't publish the whole project, also because of legal issues, but what's my best option? I never have done something with Ionic, so it's hard to locate the Error.
Answer: I had a similar issue. My solution was to check out the code in a folder, go to that folder and then run

npm install -g ionic

If I didn't do that - I'd get no end of errors when trying to get it to work.


Best way to read lines from file Java 8 and break in between

Question: The Files.lines().forEach() method doesn't allow the break. What's the optimal way to read lines in Java 8 in chunks and break when needed?
Update 1:  Example for exception.
public class Main {
public static void main(String[] args) {

    try(IntStream s = IntStream.range(0, 5);){
    s.forEach(i -> validate(i));

    }catch(Exception ex){
    System.out.println("Hello World!");
    }
}
static void validate(int s){

    if(s > 1){
        //throw new Exception(); ?
    }
    System.out.println(s);
} }

Comment: if you are using a `Stream`, the only way to break would be to throw an Exception; otherwise a for loop as it used to work for decades
Comment: @Eugene Of course, that is using exception for flow control, which is an [anti-pattern](https://softwareengineering.stackexchange.com/q/189222/202153).
Comment: @Andreas well I am not the good programmers, in such a case. We use it for `reduce`, mainly.
Comment: Yeah, the for loop doesn't leverage any Java 8 features right? and where do I throw the exception?
Comment: What feature are you trying to leverage? Your example is not leveraging anything, that can't be easily done in a `for` loop.
Comment: `Files.lines().filter()` - once the Exception is thrown, catch it - and this will act as the `break`...
Comment: @Eugene doesn't the Files.lines() read all the lines into memory if the filter is applied?
Comment: @Andreas agreed, but how would you break from a Stream otherwise? at my workplace we choose a specific exception with no stack-traces
Comment: @A.Dev no it does not. don't confuse it with `readAllLine` and `lines`
Comment: @Eugene Why would I break from a stream? A stream is for processing all values independent of each other (filtered or not). Rather than trying to use an anti-pattern to force the use of a screwdriver as a hammer, perhaps re-thinking why the code has to use a stream is in order. I'm not saying that exception is not the right choice, *sometimes*, but streams is also not always the right choice. The language has multiple tools (features) that can do the job. A good programmer will use the *right* tool at the right time.
Answer: This is easy by using java-9 takeWhile, So when the condition (s < 1) fails it will drop the remaining part of stream here

when an element is encountered that does not match the predicate, the rest of the stream is discarded.

s.takeWhile(s -> s < 1).forEach(System.out::println);

By using java-8 tried an example but this not every efficient as takeWhile, by combining peek and findFirst() but need to have double check condition which makes no sense rather than this i will prefer standard while loop
IntStream.range(0, 5).peek(i->{
         if(i<3) {
             System.out.println(i);
         }

     }).filter(j->j>=3).findFirst();

do the action in peek and stream will break when ever predicate validated in findFirst
Comment: i found this if it is helpful for you https://stackoverflow.com/questions/20746429/limit-a-stream-by-a-predicate @A.Dev
Comment: Unfortunately these are added in jdk-9 @A.Dev
Comment: @A.Dev there is a back port for it for java-8... just search SO
Comment: Stream.allMatch() is probably the correct way. Any disadvantage with this?
Comment: check the update answer you can try that in java-8 using findFirst @A.Dev
Comment: @Deadpool I can also include my operations in the allMatch() predicate right? as a function
Comment: That is a short-circuiting terminal operation. that is not right place for operations @A.Dev
Comment: Not sure where the quoted part came in from. Yet, how does this relate to *breaking in chunks*?
Comment: If i understand the question he want to terminate the stream based on condition @nullpointer there is link the post of my answer
Comment: And my understanding is he want to teriminate but not breaking into chunks, correct me if i'm wrong sir @nullpointer


Hosting a Node.js app (Cloud9 SDK) and using Apache as reverse proxy (over HTTPS) won't work

Question: I've been pulling my hair out trying to get this to work. I'm trying to host the Cloud9 SDK (Node.js) app on port 8080 (or whatever port higher than 1024) and use Apache as a reverse proxy over HTTPS to that. It shouldn't be relevant, but I'm also using PM2 to ensure the server comes back up in case of a reboot or something like that.
Now, this works when reverse proxying over HTTP in Apache. It also works when reverse proxying over HTTPS in Nginx. The only reason I don't want to use Nginx is because the same server is also hosting Zoneminder, which is a headache to get working with Nginx (already tried). So I know there's no problem with the Node.js app itself.
I was originally following this article. After that, I did some extensive Googling. However, everything I've tried has not worked. At the root directory (/var/www/html/) I just have the default Apache landing page. This is where I'm taken instead of to my Node.js app.
This is what I have in my /etc/apache2/sites-available/000-default.conf file right now:
<VirtualHost *:80>
    #ServerAdmin webmaster@localhost
    ServerAdmin firstname.lastname@example.com
    DocumentRoot /var/www/html

    ServerName example.com
    ServerAlias www.example.com

    Redirect / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    SSLEngine On
    #SSLProxyEngine On
    SSLCertificateFile    /etc/letsencrypt/live/example.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem

    ProxyPreserveHost On
    #ProxyRequests off
    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>

And in case you're curious, this is what I had in my /etc/nginx/sites-available/default file:
server {
    listen 80;
    listen [::]:80 default_server ipv6only=on;
    return 301 https://$host$request_uri;
}

server {
    listen 443;
    server_name example.com;

    ssl on;
    # Use certificate and key provided by Let's Encrypt:
    ssl_certificate      /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_session_timeout  5m;
    ssl_ecdh_curve       secp384r1;
    ssl_session_cache    shared:SSL:10m;
    ssl_session_tickets  off;
    ssl_stapling         on;
    ssl_stapling_verify  on;
    resolver             192.168.1.1 valid=300s;
    resolver_timeout     5s;
    add_header           Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
    add_header           X-Frame-Options DENY;
    add_header           X-Content-Type-Options nosniff;

    root /var/www/html;

    # Pass requests for / to localhost:8080:
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:8080/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

Also, I'm not sure if this is relevant, but this is all on a Raspberry Pi 3b.
Comment: Can you please check the `/var/log/apache2` directory? I suspect it is missing something really basic like enabling `proxy_http`
Comment: These are the 3 log files that exist: access.log, error.log, & other_vhosts_access.log. I just tried `a2enmod proxy_http` and it said the module is already enabled.
Comment: It would be useful to know the exact error you read on the browser and the matching error in apache2 logs.
Comment: There is no error. I'm just taken to the default apache landing page residing at `/var/www/html/index.html` It's just not sending me to the node.js app.
Answer: Ok, I figured out what the issue was. I realized that there were other sites enabled that needed to be removed. I had to a2dissite 000-default-le-ssl.conf and a2dissite default-le-ssl.conf not realizing that apache was looking at those configurations as well. I didn't think about it before because other changes I made to the 000-default.conf file were being reflected. Just not the ProxyPass.


When does c++ right value destruct in this scenario?

Question: Here is the code:
class SomeType {
public:
SomeType() {}
~SomeType() {}

std::string xxx;
}
bool funtion_ab() {
    SomeType(); // This is a right val;
    // The right val destructs here when I test the code. I want to make sure that it would always destructs here.
    int a = 0, b = 10;
    ....// other code
    return true;
}

Please tell me if you know the truth. Thank you!
Comment: @SilvioMayolo You are welcome to have that opinion. It is not a fact.
Comment: Your understanding is correct. Edit: An optimizing compiler could theoretically elide the entire call to `SomeType()` after proving it has no side effects, so you might not see a destructor (or constructor) call at all.
Comment: If you want control of when the destructor is called, you could use `new` and `delete` to create/destroy the object.
Comment: @nielsen Nobody should be using `new` and `delete`. Not in 2022. If you want control of when the destructor is called, you should use explicit scopes and smart pointers. `new` and `delete` are legacy.
Answer: What you have is called a temporary object. From §6.7.7,

Temporary objects are created

when a prvalue is converted to an xvalue

or, more specifically,

[Note 3: Temporary objects are materialized:
...

when a prvalue that has type other than cv void appears as a discarded-value expression ([expr.context]).

— end note]

and, on the lifetime, the same section has this to say

Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.

You can read more about the expression semantics, but in your case "full-expression" is fairly unambiguous.
SomeType();

The "full-expression" containing your constructor call is... the constructor call itself. So the destructor will be called immediately after evaluating the constructor. There are some exceptions to this rule (such as if the temporary object is thrown as an exception or is bound as a reference), but none of those apply here.
As noted in the comments, compilers are free to inline your constructor and destructor calls and then are free to notice that they do nothing and omit them entirely. Optimizers can do fun stuff with your code, provided it doesn't change the semantics. But a strict reading of the standard states that the destructor is called exactly where you suggested.


confusion in output of C program for concatenation of two strings

Question: So this is my code for appending string2 to string 1. Code works fine when I have added the line: s1[null_index]='\0';
but when i omit it adds the word 'road' one more time to the output...why is that? Why do I have to specify that the final value of null_index variabe is '\0'....shouldnt the computer already know this since it does when I declare and assign in the beginning?
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main()
{
char s2[]="a lonely road";
char s1[]="Success is ";
    int l=strlen(s1);
    int null_index=l,i=0;
while(s2[i]!='\0')
{

s1[null_index]=s2[i];
i++;
null_index++;
}
s1[null_index]='\0';
printf("%s",s1);
}

Comment: Sorry. Your program is completely wrong. You are trying to write "off the end" of `s1`  where there is no memory allocated for you. Your actual question? Strings in C have to be 0 terminated.
Comment: You need to lear how to indent your code. Look at the samples in your C text book.
Answer: s1 is allocated only as much memory as Success is requires and when you try to do s1[null_index]=s2[i]; you are inducing an undefined behavior.
Answer: To begin with
char s2[]="a lonely road";
char s1[]="Success is ";

Will declare s2 with size 14  and s1 with size 12. Hence when you write characters more than 12 to s1 you are invoking undefined behavior.
Change it to.
char s1[100]="Success is ";

To answer your question.
In c, strings are null(\0) terminated by definition. Hence printf will look for \0 in the provided string to terminate the printing of string.
If the string does not contain \0 character, it will go on printing the characters until it finds one eventually invoking the undefined behavior.
Answer: The problem is that the arrays you have are of a fixed size. Once initialized, any indexing beyond the null-terminator will be out of bounds and lead to undefined behavior.
If you want to append to s1 then you need to explicitly set a size of the array, a size that fits both the strings (plus the terminator).
And when you append to s1, the very first iteration of your loop you overwrite the terminator. Since you then don't copy the terminator from s2 you have to explicitly set the terminator of s1 at the appropriate place.
Comment: @AnasAziz The terminator will be "automatically" added because on initialization the unused parts of the array will be initialized to zero. But it's a good habit to *always* explicitly add the terminator yourself.
Comment: so if i set a size that fits both strings...say 100...then this means that the '\0' will automatically be added at the end, right? on the other hand if i have not specified the size like this then the computer would not know where '\0' is since it has been overwritten. is my understanding right?


Check whether timestamp to present has been 3 hours - php

Question:
Possible Duplicate:
Check if timestamp is x hours old?

How do I determine whether it has been 3 hours or more from a timestamp (formatted like 2012-08-06 18:22:02) to the current time, in PHP.
Answer: if (time() > (strtotime($timeToCheck) + 10800))

Comment: Could you please also share some code that will format the timestamp to "human regular" formats, for the benefit of this asker? :)
Comment: @L0j1k, you mean you don't understand `2012-08-06 18:22:02` ?


Consistency in bowling stroke

Question: Several years ago, I learned how to bowl by palming (I have two fingers inside, but my thumb and the rest of my hand supports the weight of the ball) the bowling ball.
At first, I could bowl toward the right side of the lane and it will come back and hit most, if not all, of the pins. This was predictable and reliable.
However, as my arm got stronger, the same technique I used before resulted in a straighter path.  If I bowled toward the right side of the lane like I used to, I would throw a gutter ball. If I bowled toward the head pin, it will dive left before it hits a pin. It has been tough to be consistent and to find a predictable, reliable stroke.
What steps do I need to take to (re)gain consistency in my bowling stroke? In addition, how do I adjust my bowling stroke to accomodate for one-pin spares?
Comment: By "palming the ball" do you mean that you have no fingers inserted into the ball?
Comment: @JacobG I tried to further clarify.
Answer: This is the sort of thing much better conveyed in person than online, I think, but I'll give it a whirl.
Here are some steps for you to take to build a consistent, reliable stroke, eventually get a hook/curve back and pick up single pin spares.

Buy your own ball.  It doesn't have to be super fancy or
expensive.  Something like this is a decent entry-level ball.
Get the ball drilled at a local pro-shop.  Get it drilled with a
finger-tip grip (with grips) and make sure to get it drilled with a
thumb hole, because if you want to advance your game, you have to
put your damn thumb in the ball. :-)
Go Bowling.  You're going to be changing your grip and changing your
style, so you are not going to be very good right out of the gate.
Your goal at this stage is to get comfortable with your footwork,
your swing and your release.

Things to keep in mind when you're getting familiar with your new grip / ball:

Squeeze the ball, don't grab the ball.  Your thumb should be
straight when in the hole, rather than slightly bent.  Your index
and pinky fingers should be very close to your middle fingers.
Keep your wrist straight throughout your swing.
Approach the line at a slow, and even pace.  Swing your arm like a
pendulum.  As your arm comes down from the apex, it will build up
some speed.  Your thumb will come out first on your release, you'll
want to lift with your fingers and 'shake hands' with the air.

This should give you a nice hook.  As you get comfortable with this, it's easily tweaked to enhance the hook to a point where you feel most confident.  But, for now, it's baby-steps.
In order to minimize the hook for single pin spares, you will want to spread your index and pinky fingers away from your middle fingers, allow your wrist to bend backwards, follow through 'straight up' (no handshake) and throw directly at your pin.

Consistency in bowling stroke


Implement Random Access Iterators on a linked list

Question: So I have a custom linked list. Every node is a struct which has a next pointer to a the next node and the last->next is null.
struct nodo {
    T value;
    nodo *next;

    nodo() : next(0) {}

    nodo(const T &v, nodo *n=0): value(v), next(n){}
};

I want to implement iterators in my class and since my class supports random access with operator[] then I chose to implement Random Access Iterators.
Now, my problem is on the following operator:
difference_type operator-(const iterator &other) {

}

It returns the number of elements between this iterator and other iterator, but I'm not sure what's the best to implement it.
Comment: You've got it backwards. You don't have random access with operator[] and therefore will implement random access iterators - you need to implement random access iterators and then all the rest falls out naturally. Like @StoryTeller is saying, it is not possible for the data structure you've shown to implement random access iterators. You claim to have implemented operator[], how? Is it constant time as is required by random access iterators?
Comment: I think that's a hint that your iterator isn't really random access
Comment: The point of random access is that the position type, the `iterator`, can be used from any position to get to any other. If that was truly the case, calculating the difference shouldn't be too difficult. You can easily implement a forward iterator. Why isn't that good enough?
Comment: why are you saying that?
Comment: "The point of random access is that the position type, the iterator, can be used from any position to get to any other." This is exactly what I'm looking for
Comment: Then I suggest you think about going from the end of the list to the start. You have no support for it if you rely only on `nodo`. You can provide the illusion of random access with enough overhead, but it's just that, an illusion .
Answer: Linked lists are not random access containers.  You cannot meaningfully implement random access iteration, nor a conventional operator[](size_t) for regular single or double linked lists.
People who use your list class will not expect random access iteration, and will be confused by it.  People who use your "random access" iterators and find out they don't conform to standards and conventions will also be confused.

A RandomAccessIterator is a BidirectionalIterator that can be moved to point to any element in constant time.

Only if your container can access elements by index in constant time should you expose random access interfaces.


Há como desabilitar o "Debugger Exception Notification" do Delphi?

Question: Gostaria de desabilitar a função do qual o debugger me notifica uma Exceção em um trecho de código.
Exemplo:
try
   Text := CurrToStrF('Erro', ffNumber, 2);
except
   Text := '0,00';
end;

Durante a depuração do código acima em algumas ocasiões é lançado a exceção e a depuração pausa exibindo uma mensagem na tela.
Contudo, como eu sei que ele irá lançar a exceção, eu queria que o delphi ignorasse as exceções somente nessa parte.
Tem alguma diretiva (ou outro meio) que avisasse o depurador pra não parar?
Estou utilizando o Delphi 2009
Comment: Qual a versão do `delphi` que estás utilizando?
Comment: A versão usada é o Delphi 2009
Answer: Resposta:
Sim, há como desabilita-lo.
Explicação:
Delphi 7 - No menu superior, clique em Tools-Debugger Options abrirá uma janela, navegue até a aba Language Exceptions e você verá uma checkbox dizendo [ ] Stop on delphi exceptions marque-a, pronto.
Delphi XE5 - No menu superior, clique em Tools-Options abrirá uma janela, navegue na lista que tem na esquerda, lá embaixo no final você vai encontrar Debugger Options clique na flechinha pra abrir ele aí você vai encontrar Language Exceptions, ai você vai ter a checkbox lá embaixo escrito Notify on language exceptions, é só desmarcar e pronto.
Obs: Eu deduzi que você utiliza a versão 7 ou a XE5 do delphi, pois são as mais utilizadas atualmente, se a versão do seu delphi não for a 7 nem a XE5, me avise pois encontrarei a solução para a sua versão editando esta resposta.
Comment: +1. No entanto seria bom mesmo se ele falasse a versão, estou usando o 2006 e na minha IDE o nome é "Notify on language exceptions". Mas só muda isso mesmo, acho que ele não vai ter problemas.
Comment: Na verdade não quero que todas as exceptions sejam ignoradas, nem que seja ignorado todos as exceções ( marcando o checkbox na mensagem lançada pelo depurador ) somente desejo que naquele pedaço de codigo o depurador não pare.
Answer: É possivel sim.
Coloque um Breakpoint no ponto a partir do qual você não quer que o depurador notifique sobre novas exceções.
Clique com o botão direito nele e selecione Breakpoint properties clique em Advanced desmarque Break e marque Ignore subsequent exceptions.
Depois coloque um Breakpoint no ponto que deseja que o depurador volte a notificar as exceções.
Clique com o botão direito nele e selecione Breakpoint properties clique em Advanced desmarque Break e marque Handle subsequent exceptions.
Depois disso quando debugar o depurador não irá notificar sobre qualquer exceção que ocorra nesse trecho.
Porem quando você fechar o projeto os Breakpoints vão ser perdidos, para evitar isso você deve habilitar o auto salvamento da área de trabalho do projeto.
Para fazer isso você deve ir até Tools->Options em Environment options lá procure por Auto save e marque Project desktop ou Project workspace.


How to change the button background color using jQuery selectors and if else statement?

Question: I need to change btn1 background color from transparent to green when someone click on it. If the user clicks on the button again btn1's background color should be change from green to transparent.
Is this following if condition is valid or not?
if(('#btn1').css("background-color")== "green")

function vote(str){

  if(str==1){

        if(('#btn1').css("background-color")== "green"){

                $('#btn1').css("background-color","");

        }else{

                $('#btn1').css("background-color","green");

      }

  }else{

    $('#btn2').css("background-color","red");
  }

}
</script>

<button id="btn1" onclick="vote(1)" >Up Vote</button>
<button id="btn2" onclick="vote(2)" >Down Vote</button>

Comment: No - you have a typo - missing `$` in your first `if`. I.e.; `if(('#btn` is not the same as `if($('#btn`
Comment: Always check the console for errors (F12) `btn1.css is not a function`
Comment: Also, always check what you're comparing, `console.log($('#btn1').css("background-color"))` - as noted above, in Chrome, = `rgb(239, 239, 239)` (initially) and `rgb(0, 128, 0)` when set to `green`.   https://jsfiddle.net/9qgxuL14/
Answer: You can use seperate classes for each color, and then use the toggleClass function to change them as required:

$("button").on("click", (e) => {
  $(e.target).toggleClass("transparent green")
})
.green {
  background-color: green;
}

.transparent {
  background-color: rgba(0, 0, 0, 0);
}

<button class="transparent">hello</button>
Comment: You only need to use one class and make use of the C part of CSS (but otherwise, yes, classes are the way to go here)
Comment: @EmielZuurbier don't need an array if they're strings: `$(e.target).toggleClass("transparent green")`  (array is useful if they're variables)
Comment: jQuery also supports an array of classes to toggle. `$(e.target).toggleClass(["transparent", "green"])`;
Comment: @freedomn-m even better!
Answer: You can try to use css to achieve the effect you want, and use the addClass and toggleClass functions to toggle and add classes.
addClass()

Adds the specified class(es) to each element in the set of matched
elements.

toggleClass()

Add or remove one or more classes from each element in the set of
matched elements, depending on either the class's presence or the
value of the state argument.

Use css file, use jquery to switch css rules

$('#btn1').on('click', function() {
  $(this).toggleClass('background-green');
});

$('#btn2').on('click', function() {
  $(this).addClass('background-red');
});
.background-red {
  background-color: red !important ;
}

.background-green {
  background-color: green !important;
}

.background-transparent {
  background-color: transparent;
}

<button id="btn1" class="background-transparent">Up Vote</button>
<button id="btn2">Down Vote</button>

Instead of using css file, use jquery to create css rules, and switch

$('


Hive UDFs, Java Primitives and null

Question: On page 168 of Programming Hive by E. Capriolo et al it states "...in Java primitives are not objects and cannot be null." So, for the simple Hive UDF:
public class ConvertToCelcius extends UDF {
    public double evaluate(double value) {
        return (value - 32) / 1.8;
      }
}

what happens if a null row value is encountered?
Also, using a Java primitive how can we test whether or not a null is passed to our UDF?
Presumably, we could rewrite the above as:
public class ConvertToCelcius extends UDF {
    public Double evaluate(Double value) {
        if (value == null) {
          return null;
        }
        return (value - 32) / 1.8;
      }
}

Comment: "*what happens if a null row value is encountered?*" => a compile error - it's not possible to do that. Unless you pass a `Double` in which case you will get a NPE.
Comment: Compile error or runtime error? The above code with "double" compiles fine.
Comment: What I mean is you can't call `evaluate(null)` on the first method: compile error. And if you pass a `Double d = null` at runtime, you will get a NullPointerException.
Comment: This is the whole point behind my question. "evaluate(double value)" compiles fine, can be packaged into a jar and used in a script but what happens when a null value is passed? And that's a "double" and NOT a "Double". It is perfectly valid and legal to use type "double".
Answer: We can create UDF with primitives data type only and check null value in sql Case Statement
ie
select
      CASE WHEN columnName = null then null
               else evaluate(columnName) end columnName
 From tabelName

Note : evaluate Is UDF name.
Comment: "...We can create UDF with primitives data type only..." I don't think this is correct. I have several UDFs with lists of doubles (eg List) and they work fine. However, I see your point about having to test for null at the query side so as to not pass a null to a Java primitive.
Comment: @user25029 This ( eg List) thing is workin due to  java  boxing and unboxing feature  more detail.  https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
Comment: I agree but my point was that List is NOT a primitive.

Hive UDFs, Java Primitives and null


System of Equations. Are there any solutions?

Question: Consider the following system of equations
$$
        \begin{bmatrix}
        1 & 1 & 1 \\
        -1 & 0 & 0 \\
        1 & 1 & -1 \\
        \end{bmatrix}
      .
       \begin{bmatrix}
         x\\
        y\\
         z\\
        \end{bmatrix}
=
\begin{bmatrix}
        -1 \\
        -1 \\
        -1 \\
        \end{bmatrix}
$$
Without solving the system, can you tell if there are any solutions? If so, how many?
Comment: What is the determinant?
Comment: If you heard about the Cramer method, you should be able to answer at a glance.
Comment: Cannot you just evaluate the determinant of the coefficient matrix? It is -2$\ne 0$. It has one solution.
Comment: In general: Calculating the determinant of a matrix is at least as expensive as inverting the matrix. Actually one of the least expensive ways the calculate the determinant is - inverting the matrix. So that should not be an option.
Answer: Solution 1. Note that
$$\begin{align}&\qquad a(1,1,1)+b(-1,0,0)+c(1,1,-1)=(0,0,0)\\\\
&\Longrightarrow (a,a,a)+(-b,0,0)+(c,c,-c)=(0,0,0)\\\\
&\Longrightarrow (a-b+c,a+c,a-c)=(0,0,0)\\\\
&\Longrightarrow ((a+c)-b,a+c,a-c)=(0,0,0)\\\\
&\Longrightarrow (-b,a+c,a-c)=(0,0,0)\\\\
&\Longrightarrow (-b,a+c+(a-c),a-c)=(0,0,0)\\\\
&\Longrightarrow (-b,2a,a-c)=(0,0,0)\\\\
&\Longrightarrow a=b=c=0
\end{align}$$
This shows that row vectors of the coefficient matrix are linearly independent. Thus, by the theorem below, the original system has exactly one solution.

Solution 2. The associated homogeneous system
$$\begin{bmatrix}
        1 & 1 & 1 \\
        -1 & 0 & 0 \\
        1 & 1 & -1 \\
        \end{bmatrix}
      .
       \begin{bmatrix}
         x\\
        y\\
         z\\
        \end{bmatrix}
=
\begin{bmatrix}
        0 \\
        0 \\
        0 \\
        \end{bmatrix}$$
which can be written as
$$\left\{\begin{align}x+y+z&=0\\-x&=0\\x+y-z&=0\end{align}\right.$$
has only the trivial solution.  Thus, by the theorem below, the original system has exactly one solution.

Solution 3 (given in other answers and comments). Note that
$$\det\begin{bmatrix}
        1 & 1 & 1 \\
        -1 & 0 & 0 \\
        1 & 1 & -1 \\
        \end{bmatrix}\neq 0
$$
Thus, by the theorem below, the original system has exactly one solution.

Theorem 6.4.5 in Anton & Rorres.
  If $A$ is an $n\times n$ matrix, if $I_n$ is the $n\times n$ identity matrix, and if $T_A:\mathbb R^n\to\mathbb R^n $ is multiplication by $A$, then the following are equivalent.
(a) $A$ is invertible.
(b) $Ax=0$ has only the trivial solution.
  (c) The reduced row-echelon form of $A$ is $I_n$.
  (d) $A$ is expressible as a product of elementary matrices.
  (e) $Ax=b$ is consistent for every $n\times 1$ matrix $b$.
(f) $Ax=b$ has exactly one solution for every $n\times 1$ matrix $b$.
  (g) $\mathbf{\det (A)\neq 0}$.
  (h) The column vectors of $A$ are linearly independent.
(i) The row vectors of $A$ are linearly independent.
  (j) The column vectors of $A$ span $\mathbb R^n$.
  (k) The row vectors of $A$ span $\mathbb R^n$.
  (l) The column vectors of $A$ form a basis for $\mathbb R^n$.
  (m) The row vectors of $A$ form a basis for $\mathbb R^n$.
  (n) $A$ has rank $n$.
  (o) $A$ has nullity $0$.
  (p) The orthogonal complement of the nullspace of $A$ is $\mathbb R^n$.
  (q) The orthogonal complement of the row space of $A$ is $\{0\}$.
  (r) The kernel of $T_A$ is $\{0\}$.
  (s) The range of $T_A$ is $\mathbb R^n$.
  (t) $T_A$ is one-to-one.
  (u) $\lambda=0$ is not an eigenvalue of $A$.
  (v) $A^TA$ is invertible.
Answer: Yes, the determinant of the matrix is $(-1)\times 1\times 1 - (-1)\times1\times(-1) = -2$ so there is one unique solution.
Comment: Not that it really matters but the determinant is -2.
Comment: If the determinant turned out to be zero,  would the answer be infinite solutions or no solution?
Comment: @Ralph Could be both, what you defiinitely can say that there is at least not one unique solution.
Answer: Add the second row, which immediately implies $x=1$, to the other two rows and inspect:
$$
y-z=-2\\
y+z=-2\\
\implies y=-2, z=0
$$
As noted by @skyking, the determinant is nonzero, making the solution unique. Also note, every operation I did to find the solution $(1,-2,0)$ is injective, also implying our solution is unique.
Comment: This answer does not satisfies the OP requirement.
Comment: @Pedro. Indeed, it does not. I read the stipulation late and decided to leave my answer as I think the requirement is silly.
Comment: It is silly for practical purposes because the system is easy to solve. However, exercises like that are very important for beginners.
Comment: @Pedro that's a fair point.
Answer: I assume you don't know the theory of the resolution of linear system of equations at all.
The system is
$$\begin{align}x+y+z&=-1,\\-x&=-1,\\x+y-z&=-1.\end{align}$$
Obviously, $x$ is known and you can move it to the $RHS$ in all equations.
What remains is a system with the values of $y+z$ and $y-z$ known (whatever they are).
Then it is clear that by adding or subtracting these equations memberwise, you will eliminate every other unknown and get a well-defined solution to the system ($2x=\cdots,2y=\cdots$).
Answer: For a system, $\mathbf{Ax}=\mathbf{b}$,  if $\mathbf{A}$ is square and the $\det (\mathbf{A}) \neq 0 $, then there is a unique solution. This means that $\mathbf{A}$ is invertible.
If $\mathbf{A}$ is not invertible, then $\mathbf{Ax}=\mathbf{b}$ will either have infinite solutions or no solutions.
Answer: In order for the $3$ columns to be linearly dependent it is clear column $2$ and $3$ must be dependent. This is not true, so the $3$ columns are linearly independent, the matrix has full rank, and is invertible.


System rake test task doesn't run my tests

Question: I'm sure I'm doing something naive or stupid, I'm just not sure what it is.
I'm writing a simple library for parsing data URIs. Being so simple, I figured I'd go ahead and just give ruby-1.9's minitest a whirl. The tests run great when I run them by hand, but when I try to run them with 'rake test', hoping to invoke the system rake test task, I get no joy. Specifically, with trace and verbose:
Donalds-Decisiv-MacBook-Pro:data_uri dball$ rake test -t -v
(in /Users/dball/src/data_uri)
** Invoke test (first_time, not_needed)

I've got tests in the test folder, they all start with test_ and end in .rb. Any ideas?
The repository of the project is http://github.com/dball/data_uri
Answer: Tests are not invoked because you didn't give rake any information about them.
Put this task in Rakefile:
require 'rake/testtask'
Rake::TestTask.new do |i|
  i.test_files = FileList['test/test_*.rb']
  i.verbose = true
end

Or grab a patch for your project.


Placing a rectangle on a 3D triangle

Question: Background

I have a 3D triangle (let's call the points XYZ) and trying to place a rectangle on it. By that I mean the points of the rectangle should stick to the surface of the triangle in 3D space. The position and size of the rectangle should be defined by some offset vectors relative to X.
My Understanding
My approach would be to calculate two normalized vectors, one which points from X to Y and the other one which is rectangular to the first one and points to the direction of Z. By multiplicating some offset's with the two unit vectors it should be possible to calculate ABCD on the surface of the triangle.
Could that work? How can I calculate this unit vectors?
Answer: The dot product of $\vec{XZ}$ with the unit vector $\vec{XY} / \left| \vec{XY} \right|$ gives you the projection
of $\vec{XZ}$ onto $\vec{XY} $.
That multiplied by the unit vector $\vec{XY} / \left| \vec{XY} \right|$ itself is the component along it of $\vec{XZ}$.
$\vec{XZ}$ minus the last  is the orthogonal component you are looking for.
Make it unitary, ...

Placing a rectangle on a 3D triangle


Asymptotic expansion question

Question: How may I use Watson's Lemma to find the full asymptotic expansion for;
$$ I(\lambda)= \int_0^\infty e^{-\lambda(1+s)}ln(1+s^2)ds $$
as $\lambda \rightarrow \infty$.
Thanks in advance
Comment: What part of Watson's lemma are you having trouble with? The general steps are (1) Expand $\ln(1+s^2)$ in power series about the point $s=0$ and (2) substitute this power series into the integral and integrate term-by-term.
Answer: Consider the function
$$f(t) = \int_0^\infty e^{-s} \ln(1 +t^2s^2) ds,$$
We have $f(0) =0, f'(0)=0$ and
$$f''(0) = 2\int_0^\infty e^{-s} s ds =2$$
hence $f(t) = t^2 + o(t^2)$ when $t\to 0$
By changing variable,
$$I(\lambda) = e^{-\lambda} \lambda^{-1} f(\lambda^{-1}) = \frac1{e^\lambda \lambda^3} + o\left(\frac1{e^\lambda \lambda^3}\right).$$
Comment: may you elaborate on your working out please?

I cant really follow this, sorry for the inconvenience.

Asymptotic expansion question


How do I post a complex object to an MVC 4 controller via Ajax?

Question: I have an object called DrawDie with the following properties:
ID
PlantID : int
QtyOnHand : int
SizeUS : double
SizeMetric : double
CaseSize : string
Style : string

I have an object called DieOrder with the following properties:
ID : int
DrawDie : DrawDie
DrawDieID : int
PlantID : int
PurchaseOrder : string
Qty : int

I would like to post my object to an MVC controller via an Ajax request.  I would prefer not to use a 3rd party library.  I am trying to post it like this:
        var DieOrder = new Object();
        var DrawDie = new Object();

        DieOrder.Qty = $("#Qty").val();
        DieOrder.DrawDieID = $("#DrawDieID").val();

        DrawDie.CaseSize = $("#DrawDie_CaseSize").val();
        DrawDie.Qty = $("#Qty").val();
        DrawDie.ID = dieID;
        DrawDie.QtyOnHand = 0;
        DrawDie.SizeUS = $("#DrawDie_SizeUS");
        DrawDie.SizeMetric = $("#DrawDie_SizeMetric");
        DrawDie.PlantID = $("#PlantID").val();
        DrawDie.IsTransfer = "N";

        DieOrder.PlantID = $("#PlantID").val();
        DieOrder.OrderedBy = $("#OrderedBy").val();
        DieOrder.PurchaseOrder = $("#PurchaseOrder").val();
        DieOrder.DrawDie = DrawDie;

        $.ajax({
            url: "Order/OrdDie",
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(DieOrder),
            success: handleData

        });

    });

I have two questions.  One, is my approach way off or is it okay ?  I am getting an UncaughtType error: Converting circular structure to JSON.  How do I restructure my request so I do not get such an error?  I am unsure of why I am getting this error.
Thanks
Update:
 DrawDie.SizeUS = $("#DrawDie_SizeUS").val();
 DrawDie.SizeMetric = $("#DrawDie_SizeMetric").val();

I was missing the .val()
Comment: Check this out: http://stackoverflow.com/a/5410200/487940
Comment: why you dont use ajax.beginform for this
Comment: Pathachiever11.  I checked out the posting but it really did not clarify things for me.  I do not know why I am getting the circular reference error.
Answer: The problem you're really having is that your controller is interpreting all of the contents of your DieOrder object as arguments to your controller action.
If your controller action looks like this...
[HttpPost]
public void OrdDie(OrderDieViewModel model)
{
    // Some operations
}

...Then the data that your stringifying should look like this:
{
    'model': DieOrder
}

...so, you're really just missing a step prior to making your $.ajax call:
var DrawDie = {
    // Properties...
};

var DieOrder = {
    // Properties...
    'DrawDie': DrawDie
};

var data = {
    'model': DieOrder
};

$.ajax({
    // Spec object here.
});

In short?  Your data object's contents must match the argument list of the action you are calling.  This means that if you pass only a model to your JSON action, your data object must have only one member: the JavaScript representation of that model object.
Comment: Andrew.  Thanks for the info, but I am never getting to the controller.   I am getting an UncaughtType error: Converting circular structure to JSON in my javascript code so the ajax request is never made.
Comment: Aah, my apologies!  I don't see any circular reference, though.  Are you showing us everything (that you can) about the JavaScript data structures that you're trying to send to the server?
Comment: It turns out that when I remove the following line in my javascript the UncaughtType error: Converting circular structure to JSON error goes away.  Any ideas why ?
Comment: I think you may have forgotten to include the line that makes the circular structure error go away...
Answer: Try adding dataType: 'json' to your ajax request:
$.ajax({
    url: "Order/OrdDie",
    type: 'POST',
    cache: false,
    data: JSON.stringify(_data),
    dataType: 'json',
    contentType: 'application/json',
    success: handleData
});

In addition you can initialize JS objects like this:
var DieOrder = {};
var DrawDie = {};

I hope this help!


What actually is the definition of asymptotic normality for an estimator? Some inconsistencies

Question: In most books, the result that the MLE is asymptotically normal is given, and that is used as the definition of asymptotically normal, with no mention of what the actual definition is for a general estimator.
Let $\hat{\theta}_n$ be an estimator for $\theta$. Consider the following definitions.
Defn 1 (Wikipedia): $\hat{\theta}_n$ is asymptotically normal if there exists a sequence of constants $a_n$, $b_n$ such that $\frac{\hat{\theta}_n-a_n}{b_n}\stackrel{d}{\to} N(\mu,\sigma^2)$.
Defn 2: $\hat{\theta}_n$ is asymptotically normal if $\frac{\hat{\theta}_n-\theta}{{se}(\hat{\theta}_n)} \stackrel{d}{\to} N(0,1)$.
Defn 3: $\hat{\theta}_n$ is asymptotically normal if $\frac{\hat{\theta}_n-\theta}{{se}(\hat{\theta}_n)} \stackrel{d}{\to} N(\mu,\sigma^2)$.
Defn 4 (StackExchange/MLE version): $\hat{\theta}_n$ is asymptotically normal if $\sqrt{n}(\hat{\theta}_n -\theta) \stackrel{d}{\to} N(0,\sigma^2)$.
In Defn 1, we can assume without loss of generality that $\mu=0$ and $\sigma^2=1$, but we can't do that for Defn 2 and Defn 3. One of the main questions I have is can an estimator be asymptotically normal where the limiting distribution is normal with a nonzero mean. Does such an estimator exist?
Suppose $\theta$ is a mean and we estimate it using the bad estimator $\hat{\theta}_n = \bar{X}+1$, the sample mean plus 1. Then this is asymptotically normal according to Defn 1 ($a_n = \theta+1$), but not asymptotically normal by Defn 2 ($\frac{\hat{\theta}_n-\theta}{{se}(\hat{\theta}_n)} = \frac{\bar{X}-\theta}{{se}(\hat{\theta}_n)} + \frac{a}{{se}(\hat{\theta}_n)}$, where the first term converges to $N(0,1)$ and the second term diverges), and even Defn 3.
Defn 4 seems too limited and too closely related to MLE. It doesn't appear to account for cases where the rate of convergence is not $\sqrt{n}$.
It seems Defn 1 is the most expansive definition here. It raises the question that if Defn 1 holds with $\mu=0$ and $\sigma^2=1$, how is it related to Defn 2, specifically is it necessary that $\frac{b_n}{se(\hat{\theta}_n)}\stackrel{p}{\to}1$ and $E(\hat{\theta}_n)-a_n\stackrel{p}{\to}0$?
So what is the correct definition? Can the mean of the limiting distribution be nonzero. Is there a reference?
Comment: You might consider the case where $X_i \sim N(\theta,1)$ iid, with $\hat \theta =\bar X$ with probability $1-\frac1n$ and $\hat \theta$ is drawn from a standard Cauchy distribution with probability $\frac1n$, so  the distribution of $\sqrt{n}(\hat \theta -\theta) \to  \mathcal N(0,1)$ pointwise, but $\hat \theta$ has no standard deviation or indeed mean
Comment: @Henry I don't think that example makes sense. Firstly, an estimator must be a deterministic function of the $X_i$s (though you can probably approximate that using an indicator function). Secondly, I don't see how that approaches normality since the CLT would not apply for Cauchy. And lastly, converging pointwise to a distribution is a oxymoron.
Answer: The overarching issue is whether we can center an estimator (by something and not necessarily a mean), and/or scale it (by another something, not necessarily its standard deviation) so that this centered and/or scaled version of it converges in distribution, to some distribution (not necessarily the Normal), preferably having some mean and some variance, which we can derive and compute/estimate
And we want to do that in order to perform inference based on this asymptotic distribution, if we do not have available finite-sample exact distributional result. Note that it may be the case that this asymptotic distribution has no moments, in which case inference could be based on other properties of the distribution, e.g quantiles.
So, we are content if we can determine sequences $\{a_n\}$, $\{b_n\}$, and a distribution $D$ such that
$$\frac{\hat \theta_n - a_n}{b_n} \to_d D({\rm mean},\,{\rm variance}),$$
...and more than content if we can also derive the mean and variance of $D$.
As for the definitions:
Defn 1 (wikipedia) is misunderstood by the OP, because if one reads the article, it does not say that such a general centering and scaling will lead to the standard Normal.
Defn 2 invokes silently a) the Central Limit Theorem, b) that the estimator is consistent, c) that its standard deviation is a decreasing function of the sample size
Defn 3 can be considered wrong, or at least confusing/misleading, if it implies a non-unitary variance, since if you scale something by its standard deviation, the resulting distribution (if all these exist), will necessarily have unitary standard deviation and variance.
Defn 4 indeed assumes that the rate of convergence is $\sqrt{n}$, which is not universally the case.
Comment: +1.  And your post at https://stats.stackexchange.com/a/105749/919 is a good example of the value and generality of your characterization.


Room database Entity initialization

Question: we have following Json and model class. how to initiate Room entity database on this Json.
   {
    "ResultResponse": "Success",
    "OTPValue": "3239",
    "EmployeeInfo": [
        {
            "EmployeeCode": "EMP001",
            "Name": "Natheem",
            "ContactNo": "9952265503",
            "AlternativeContactNo": "9952265502",
            "Age": "22",
            "DOB": "1995-10-08T00:00:00",
            "ImagePath": "C:\\FaceTag\\FaceTag\\Images\\EMP001\\natheem.jpg",
            "Latitude": "1.104492000000000e+001",
            "Longitude": "7.701183000000000e+001",
            "Address1": "45, Bharathiyar Nagar",
            "Address2": "Coimbatore",
            "City": "Coimbatore",
            "State": "Tamilnadu",
            "Country": "India",
            "Zip": "641001",
            "IsSupervisor": false,
            "FormId": 0
        }
    ],
    "AdditionalField": null,
    "FieldControl": null
}

and my entity class is.
  @Entity(tableName = "tbl_device_register")
public class DeviceRegister {

    @PrimaryKey(autoGenerate = true)
    private int id;

    @SerializedName("ResultResponse")
    @Expose
    private String resultResponse;
    @SerializedName("OTPValue")
    @Expose
    private String oTPValue;
    @SerializedName("EmployeeInfo")
    @Expose
    private List<EmployeeInfo> employeeInfo = null;
    @SerializedName("AdditionalField")
    @Expose
    private Object additionalField;
    @SerializedName("FieldControl")
    @Expose
    private Object fieldControl;

How to assign the Foreign key, and what about table relationship. most of the tutorials speaking about the basics. Thanks
Answer:
Adding foreignKeys means we create connection between this entity and
  some other class. In this parameter we declare parentColumns, which is
  name of the id column from User class and childColumns, which is the
  name of the user id column in Repo class.

The ForeignKey Structure is
@Entity(foreignKeys =
    [
        ForeignKey(
                entity = SOURCECLASSNAME::class,
                parentColumns = arrayOf("id"),
                childColumns = arrayOf("id"),
                onDelete = ForeignKey.CASCADE
        )
    ], indices = [Index(value = "id")]
)

Make sure, import below
import static android.arch.persistence.room.ForeignKey.CASCADE;

You can read One-to-many relation.

Room database Entity initialization


PG Search not Returning Exact Matches First - Rails 4

Question: I am using PgSearch on my Rails 4 app. Been stuck trying to figure out how to boost exact matches when returning search results.
Currently, if a user searches for "coke"... "coke zero" will be displayed first... followed by "coke". I would like "coke" to be first.
Here is my code:
include PgSearch
pg_search_scope :search, :against => { :specific => 'A', :title => 'B', :aka => 'C'},
                         :using => { dmetaphone: {}, tsearch: { dictionary: 'english' },
                                     trigram: {:threshold => 0.3} },
                         ignoring: :accents

Any help is much appreciated.
Answer: you can try "normalization: 2" as well: https://github.com/Casecommons/pg_search#normalization
(post here just for some other guys meet the same problem as me but not caused by ordering by updated_at default)
an example:
  pg_search_scope :search_by_name,
                  against: :name,
                  using: { tsearch: { prefix: true }}

[22] pry(main)> Category.search_by_name('Los Angeles').pluck(:name)
   (3.7ms)  SELECT "categories"."name" FROM "categories" INNER JOIN (SELECT "categories"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("categories"."name"::text, ''))), (to_tsquery('simple', ''' ' || 'Los' || ' ''' || ':*') && to_tsquery('simple', ''' ' || 'Angeles' || ' ''' || ':*')), 0)) AS rank FROM "categories" WHERE (((to_tsvector('simple', coalesce("categories"."name"::text, ''))) @@ (to_tsquery('simple', ''' ' || 'Los' || ' ''' || ':*') && to_tsquery('simple', ''' ' || 'Angeles' || ' ''' || ':*'))))) AS pg_search_a6216ea03e578f212dd604 ON "categories"."id" = pg_search_a6216ea03e578f212dd604.pg_search_id ORDER BY pg_search_a6216ea03e578f212dd604.rank DESC, "categories"."id" ASC
=> ["Los Angeles Angels",
 "Los Angeles Lakers",
 "Los Angeles angels",
 "Los Angeles Dodgers",
 "Los Angeles Rams",
 "Los Angeles",
 "Los Angeles Clippers"]

——

  include PgSearch
  pg_search_scope :search_by_name,
                  against: :name,
                  using: { tsearch: { prefix: true, normalization: 2 }}

[20] pry(main)> Category.search_by_name('Los Angeles').pluck(:name)
   (3.4ms)  SELECT "categories"."name" FROM "categories" INNER JOIN (SELECT "categories"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("categories"."name"::text, ''))), (to_tsquery('simple', ''' ' || 'Los' || ' ''' || ':*') && to_tsquery('simple', ''' ' || 'Angeles' || ' ''' || ':*')), 2)) AS rank FROM "categories" WHERE (((to_tsvector('simple', coalesce("categories"."name"::text, ''))) @@ (to_tsquery('simple', ''' ' || 'Los' || ' ''' || ':*') && to_tsquery('simple', ''' ' || 'Angeles' || ' ''' || ':*'))))) AS pg_search_a6216ea03e578f212dd604 ON "categories"."id" = pg_search_a6216ea03e578f212dd604.pg_search_id ORDER BY pg_search_a6216ea03e578f212dd604.rank DESC, "categories"."id" ASC
=> ["Los Angeles",
 "Los Angeles Angels",
 "Los Angeles Lakers",
 "Los Angeles angels",
 "Los Angeles Dodgers",
 "Los Angeles Rams",
 "Los Angeles Clippers"]

Answer: You can try sorting by pg_search_rank:
@beverages = Beverage.search("Coke").with_pg_search_rank
@beverages = @beverages.sort_by {|b| b.pg_search_rank}

Comment: Thanks for the help. Ended up being my default scope that I was stupidly overlooking. @sadaf
Answer: So, I ended up overlooking my default scope - which was ordering by updated_at. After I removed that, it worked perfectly...


Check if "the parameter named by the value of x" is set

Question: I am currently using a piece of code like this:
if (( $( eval "echo \${+$foo}" ) )); then
  ./my-prog
fi

Is there a more elegant or concise way to express this? Originally I tried
if (( ${+${(P)foo}} )); then
  ./my-prog
fi

but that raised the "bad substitution" error.
Answer: There's also the -v operator, which precludes the need for indirect parameter expansion:
if [[ -v $foo ]]; then
  ./my-prog
fi

This is documented in man zshmisc, in the CONDITIONAL EXPRESSIONS section.
Comment: Thanks, this happens to be better for the case I had in mind anyway.
Answer: (P) and + can be used in the same parameter expansion, if you use them in the right order:
if (( ${(P)+foo} )); then
  ./my-prog
fi


Is there a way to disable Quick Find in Visual Studio 2012?

Question: I just upgraded to Visual Studio 2012 from 2010 and cannot stand the fact that Cntrl + F brings up the new Quick Find dialog in the upper right hand corner of the editor. I typically just dock the Find and Replace window and prefer to use that. Is there a way to disable Cntrl + F from bringing up the new Quick Find window and instead have it move focus to the Find and Replace window similar to how VS 2010 did it?
Comment: This annoys me greatly.  But possibly for a different reason.  I do not like the fact that the current document jumps to the text as I'm typing it.  The reason being that I'm looking for a specific function in the current file and if its not there I'll do find in files search.  Well the quick find LOSES MY PLACE in the file while its randomly jumping through the file trying to find the search text!  Then I have the added step of going back to my place before running the find in files search.
Comment: I have a an i7-3930K cpu with 32 gigs of ram. I guess it's not powerful enough for quick find. It takes 1 or 2 seconds to pop up when I hit ctrl-f and about 1 second per keystroke to find text in files with more than a hundred or so lines of code. Nice idea. Bad implementation, I guess. Thanks for the question, I'm switching back to the older find.
Answer: Yes there is. You can assign the keyboard shortcut ctrl+f to edit.findinfiles in tools>options>environment>keyboard. So far it works for me.
Comment: Problem is, you have to manually change "Find what" to current document and change it back again when you really want to find in files.
Comment: Thank you! I was able to finally get it to work by updating the keyboard shortcuts like you said.
Comment: Also, the default button is `Find All`, so the result goes to the "Find Result Window", instead of selecting the text found. For that you'll have to click `Find Next` with the mouse:S There's not even a keyboard shortcut for it :(
Comment: Just made a AutoHotkey script to get around the above issues. Basically makes "Find in Files" dialog behave more like the good ol VS2010 Find dialog. See: http://pastebin.com/M0fVTzLr
Answer: Instead of modifying the default keyboard shortcuts consider using
Ctrl+Shift+F for "Find in files"
Ctrl+Shift+H for "Replace in files"
Sometimes it's not always possible/advisable to change the default shortcuts. Like when working on another persons computer.


Debian KVM and location for vm images different than /var/lib/libvirt/images

Question: I have defined storage pool for VMs  on ZFS:
virsh # pool-dumpxml zfs
<pool type='dir'>
  <name>zfs</name>
  <uuid>b2fba550-467f-8133-dee8-44ada7d0a807</uuid>
  <capacity unit='bytes'>210316853248</capacity>
  <allocation unit='bytes'>32768</allocation>
  <available unit='bytes'>210316820480</available>
  <source>
  </source>
  <target>
    <path>/winvm/win1</path>
    <permissions>
      <mode>0700</mode>
      <owner>4294967295</owner>
      <group>4294967295</group>
    </permissions>
  </target>
</pool>

Created RAW image file for vms:
host /winvm/win1 % l
total 3.5K
drwxrwxr-x. 2 root         root           3 Jan  3 14:03 .
drwxr-xr-x  3 libvirt-qemu libvirt-qemu   3 Dec 30 13:45 ..
-rw-------. 1 libvirt-qemu libvirt-qemu 20G Jan  3 14:03 t1.raw

Defined t1 VM but when I try to start it:
host /winvm/win1 % virsh start t1
error: Failed to start domain t1
error: internal error process exited while connecting to monitor: char device redirected to /dev/pts/13
kvm: -drive file=/winvm/win1/t1.raw,if=none,id=drive-sata0-0-0,format=raw,cache=none: could not open disk image /winvm/win1/t1.raw: Invalid argument

The VM's storage file keeps changing owner to root:root:
host /winvm/win1 % ls -l
total 1
-rw-------. 1 root root 21474836480 Jan  3 14:03 t1.raw

I have SELinux disabled on that machine:
host /winvm/win1 % sestatus
SELinux status:                 disabled

Even changed user and context for it:
host /winvm/win1 % chcon -t virt_image_t -u libvirt-qemu t1.raw

And I still keep getting the error above. Why? And how can SELinux impact file access when it's disabled?
Comment: the pool is actived?
Answer: It's not ZFS, it's virt-manager utility that is causing incorrect configuration - the culprit is if=none added for some reason to disk spec (I've used virt-manager to define raw disk on ZFS volume). I was getting intermittent 'permission denied' errors on the disk image and so I thought it was a question of permissions. That's what happens if you set all the available options on disk image in virt-manager, apparently everyone just leaves the defaults on.
Comment: Thanks for the hint, one need to set : cache-mode=Hypervisor Default


How does this expression simplification make sense? My simplification does not equal what is given.

Question: I attached an image of the expression I'm working with

I have no idea how $A(x)$ is simplified to $\displaystyle 5x - \left(\frac{1+\pi}{2}\right) x^2$.
Every time I work out the equation I get $$A(x) = 5x - x^2 - (\pi x^2/2) + \pi(x/2)^2$$
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: So, step-by-step
\begin{align*}
A(x)&=xy+\pi\left(\frac{x}{2}\right)^{2},\\&=x\left(5-x-\frac{\pi}{2}x\right)+\pi\left(\frac{x}{2}\right)^{2},\\&=5x-x^{2}-\frac{\pi}{2}x^{2}+\frac{\pi}{2^{2}}x^{2},\\&=5x+\left(\frac{\pi}{2^{2}}-\frac{\pi}{2}-1\right)x^{2},\\&=5x+\left(\frac{\pi}{2^2}-\frac{2\pi}{2^{2}}-\frac{2^{2}\cdot 1}{2^{2}\cdot 1}\right)x^{2},\\&=5x+\left(\frac{\pi-2\pi-2^{2}}{2^{2}}\right)x^{2},\\&=5x+\left(\frac{-2^{2}-\pi}{2^{2}}\right)x^{2},\\&=\boxed{5x-\left(\frac{2^{2}+\pi}{2^{2}}\right)x^{2}},\\&\not=5x-\left(\frac{1+\pi}{2}\right)x^{2}
\end{align*}
Hence the answer in your picture is wrong which is clear because in the second sign "$=$" they did not add the term $\pi\left(\frac{x}{2}\right)^{2}$ . You're correct in the simplification.


Indo para um determinado tab

Question: Esse é meu menu:

...

      tenho aqui uma dataTable

Esse é o meu Bean:
private int tabIndex;

public void cadastrar() {
  tabIndex = 0;
}

public void consultar() {
  tabIndex = 1;
}

public int getTabIndex() {
  return tabIndex;
}

Então, ao clicar no Menu consulta, por exemplo, ele não redireciona para o tab de consulta ou cadastro.
Answer: Para funcionar precisarias atualizar o p:tabView, para tal:
1 - Defina um id par ao p:tabView(Exemplo: tabTeste);
2 - Para os items do menu, podes atualizar o p:tabView depois de ele terminar a solicitação assincrona ao servidor (neste caso a mudança do índice):

Recomendação:
Podias fazer isso a nível de JavaScript, para evitar um "interação" com o servidor so para mudar índices bem definidos.
Comment: Eu não sei o que acontece, mas isso deveria funcionar...:/
Parece que o action não funciona, não seta o tabIndex.
Comment: Tente imprimir um texto nalgum dos métodos(cadastrar ou consultar) pra ver se ele exibe. Nota: Se tiveres um errozinho em JavaScript ele já nem passa pra fase seguinte do JSF. Tente abrir a console javascript do browser e ver que se passa.
Comment: Hy Cold, Obrigado pela ajuda..
Ele já está entrando no método e setando os valores.
Porém como o scopo é do tipo View ao redirecionar ele perde todos os dados.
Comment: Então muda o escopo dele, pois desse jeito está tudo a funcionar direito (sendo @ViewScoped)
Comment: É mudei para session consumiu muita memoria pois tenho uma tabela também..rsrs
E acabei achando um tal de FlahsScoped que salva o Objeto ou valor que voce quer na memoria.
Dentro do método vc faz a alteração.

public String redirecionarComFlash() {

FacesContext instance = FacesContext.getCurrentInstance();

ExternalContext externalContext = instance.getExternalContext();
externalContext.getFlash().put("key", valor);
externalContext.getFlash().setKeepMessages(true);
return URL + "?faces-redirect=true";
}
Comment: Se isso der certo vou postar aqui..Mais uma vez Obrigado por disponibilizar a lógica!

Indo para um determinado tab


Is it safe to call a thread safe method through RMI from multiple threads on the local machine?

Question: I have some method which is going to call remote method through RMI as the following:
/**
 * Implementation is supposed to be thread safe
 */
public interface Act extends java.rmi.Remote{
    String doSome() throws RemoteException;
}

public class SomeClass {
    private static final Act stub = (Act) Naming.lookup("/server/stub")

    public static void someMethodAccessedByMultipleThreads(){
        System.out.println(stub.doSome());
    }
}

If the remote method is thread safe is it safe to call someMethodAccessedByMultipleThreads by multiple threads?
Or are there some RMI-threading/networking/something_else issues?
Comment: RMI is just invoking a method on some other machine; from the perspective of that machine, it's not RMI, it's just MI. So, if it's *really* thread safe there, why would calling it in some way - where the call happens to come via an RMI framework - break that thread safety?
Comment: @AndyTurner I dont think so. My question is mostly about rmi and how it guarantees thread safety (if so).
Comment: This feels like a dupe of [What is meant by "thread-safe" code?](http://stackoverflow.com/questions/261683/what-is-meant-by-thread-safe-code); but I'll hold off on the dupe hammer for now.
Comment: @AndyTurner I mean two threads call the same remote method simultaneously and expect to receive some result. Maybe there is some networking issue about that so the result received by these threads is corrupted due to collision.
Comment: If it's thread-safe it's thread-safe. Unclear what you're asking.
Comment: I have to admit: I like your question. It gives food for thought.
Comment: @EJP Two threads simultaneously invoke the same remote method. In order for to do that the threads need to transfer some commands to the remote machine and receive the result. They use the same port, so threads will receive data from the same port and therefore there might a collision.
Comment: Only if they use the same connection, which they don't. If they did the result would be an unimplementable mess. See my answer.
Comment: @EJP - the question is about a thread-safe _remote method_ being called from multiple threads over RMI. Clearly there should be no issue with the remote method itself, but as I understand it the concern is that, for example, the local stub may not be thread-safe, or the remote receiving framework may not be able to handle concurrent calls from the same stub (which is really another way the local stub could be not-thread-safe).
Answer: Hard to discern exactly what you're talking about, but I will make two statements.

Remote stubs are thread-safe. I asked this question many years ago on the [defunct] RMI mailing list, and the answer came forth engraved in stone tablets from Bob Scheifler, Ann Wolrath, Peter Jones, or one of the other authors, not just for RMI but for the entire JDK: it's thread-safe unless the Javadoc says otherwise.
Remote method implementations are not thread-safe. The source for this assertion is the gnomic utterance in the Remote Method Invocation Specification to the effect that RMI makes no guarantees about any association between client-side threads and server-side threads. The occult meaning of this is that you cannot assume RMI is single-threaded at the server.

The conclusion to be drawn is that if your remote method implementation is thread-safe, so is calling it from multiple threads in any client, or multiple clients simultaneously, which amounts to the same thing from RMI's point of view.
Comment: Huh, your point (1) is very interesting. It seems like a wrong approach given that the vast majority of JDK classes are not thread safe, so you have to document nearly every class and if you forget the default is "unsafe" (i.e., based on the guarantee, if you forgot to document a class users may assume it is thread-safe, rather than the other way around). Still, I clicked through a dozen Java docs and indeed every one which I knew not to be thread-safe contained a disclaimer to this effect. So maybe they are actually doing this...
Comment: @BeeOnRope The statement applies to the JDK. What you do with your own classes is up to you.
Answer: Even when RMI tried, it couldn't break things here.
You see, the endpoint, the method that is invoked exists within a single JVM. It is a single method. If you implemented that method in a thread-safe manner, then you are good; otherwise you are not.
And from there: when that JVM invokes that method; does it matter who/what triggers the invocation?
In other words: thread-safety is a local property. No matter what happens on the "client" machine; and how the protocol is implemented that transports the  "invocation" request to the "remote server" machine; in the end; you are dealing with a single JVM, with a single "method endpoint".
If that thing is implemented correctly, things will work; otherwise they will break; no matter whether the n threads calling that method got their orders from "inside the remote server" or from some other thread on some other system.
To make that really clear: it is your responsibility to make sure that  your implementation of that to-be-RMI'ed method is thread safe. If you mess up, then sure, things will go wrong. But the same is true when you have multiple threads calling a non-RMI method that is not thread-safe.
Comment: RMI method implementations are only thread-safe if the implementor makes them so. It isn't inherent in RMI.
Comment: I see. Better now?
Comment: The paragraph that needs fixing is the second one where you blindly assert that the method impllementation is thread-safe..
Comment: Not really. The claim seems to be that everything happens on a single machine (the remote machine?), so it's safe but of course there are all the mechanics of issuing the RMI call in the first place. Certainly it is not some kind of obvious standard that [stubs are threadsafe](http://stackoverflow.com/questions/1950080/are-axis2-generated-stubs-thread-safe) - and making it so involves some implementation effort (whatever state machines, sockets, etc are inside the stub need to handle multiple concurrent calls, etc).
Answer: If I understand the question correctly, you asking if the client's generated RMI stub implementations are thread-safe.
I'm sure they are implemented thread-safe but it doesn't seems documented anywhere. I can't find any explicit mentioning of stubs being or not being thread safe in the RMI spec. It usually is documented if something is not thread-safe.
In this forum question about Thread safety of RMI stubs someone mentions RMI stubs being stateless and therefore thread-safe. The person who asked this also ran some test in Java 6 which confirmed the thread-safety of stubs, but he also reminds that since it's not in the spec it may change in future versions (though this is unlikely in my opinion).
Comment: Your link is about Spring Remoting, not Java RMI. Java RMI stubs are thread-safe, by virtue of the Javadoc not stating otherwise.
Comment: @EJP The linked thread is mostly about Java RMI, there doesn't seem to be many Spring Remoting specific things mentioned (except maybe that it's used to create remote objects).
Comment: The linked thread was posted on a Spring forum, and it is about a remote proxy obtained rom `RmiProxyFactoryBean`, which is a Spring class.
Comment: @EJP yes, as I said Spring is mentioned to be used to get the remote proxy. `RmiProxyFactoryBean` obtains it via the RMI registry though, just like you would do without Spring. Just because it's posted in a Spring forum doesn't make their observations about RMI stubs invalid. I doesn't look like Spring is providing it's own proxy implementation nor does it seem to be interfering with stub methods invocations in any way.


Automatic theorem proving with term rewriting on finitely presented algebraic structures

Question: I am looking for an open source software package that can do automatic theorem proving for finitely presented algebraic structures.  You should be able to program in the axioms of the structure and then give it a theorem, which I think is an equation, though I am not sure, and then it can try to prove this theorem.  Sorry if this is vague, but perhaps two or three examples might help me to see what is out there and what I could possibly use.
Answer: See https://en.wikipedia.org/wiki/Automated_theorem_proving. It's not mentioned on that page but the late Bill McCune's prover9 is a particular favourite of mine and very easy to use - after 30 minutes learning it's syntax, you'll be good to go.


Issue unit testing this function in node with node-fetch

Question: I'm trying to unit test this function.... following the documentation.
Any ideas why i'm getting this error? According to the documentation we can see it being called this way... What am I missing. https://jestjs.io/docs/en/bypassing-module-mocks
Thankx

async function isValid(pair) {
    const path = process.env.PATH;
    const query = '/check';
    const requestOptions = ccyServiceRequestOptions(pair);
    try {
        const response = await fetch(path + query, requestOptions);
        const json = await response.json();
        return json.result.pair === pair;
    } catch (err) {
        if (err instanceof TypeError) {
            return false;
        }
        else {
            log.error(err);
            throw err;
        }
    }
}

------------------------------------------------------------------------------------------
jest.mock('node-fetch');

const fetch = require('node-fetch');
const {Response} = jest.requireActual('node-fetch');

beforeEach(() => {
    jest.clearAllMocks()
})

it('should call with valid url', async () => {
        const pair = 'EURUSD';
        fetch.mockReturnValue(Promise.resolve(new Response({})));

        await ccyPairIsValid(pair);

        expect(fetch).toHaveBeenCalled();
        expect(fetch.mock.calls[0][0]).toHaveBeenCalledWith(process.env.PATH + '/check');
    })

Error: expect(received).toHaveBeenCalledWith(...expected)

Matcher error: received value must be a mock or spy function

Received has type:  string
Received has value: "http://localhost:8000/check"
Answer: You are calling fetch with two arguments, if you don't care about your requestOptions argument then you can use expect.anything()


How to AVAudioPlayer with progress bar show using swift?

Question: I'm playing a song using AVAudioPlayer. I need a progress bar to show the progress of the song.
My issue is that the progress bar's progress isn't working properly. Within 2-3 seconds, it finishes its progress.
func playMusic() {

    do {
        player = try AVAudioPlayer(contentsOf: (currentSong?.mediaURL)!)
        guard let player = player else { return }

        player.prepareToPlay()
        player.play()

        updater = CADisplayLink(target: self, selector: #selector(self.musicProgress))
        updater.frameInterval = 1
        updater.add(to: RunLoop.current, forMode: RunLoop.Mode.common)

        playButton.setImage(UIImage.init(named: "pause"), for: .normal)
    } catch let error as NSError {
        print(error.description)
    }
}

@objc func musicProgress()  {

    let normalizedTime = Float(self.player?.currentTime as! Double * 100.0 / (self.player?.duration as! Double) )
    self.progressMusic.progress = normalizedTime
}

Answer: The issue is here:
let normalizedTime = Float(self.player?.currentTime as! Double * 100.0 / (self.player?.duration as! Double) )

With this you will get a value between 0.0 and 100.0, but according to UIProgressView documentation, progress must be between 0.0 and 1.0. Try
let normalizedTime = Float(self.player?.currentTime as! Double / (self.player?.duration as! Double) )

Comment: I don't think you're using `CADisplayLink` properly. That class should be used to update logic when UI is drawn, not update UI when logic changes. Try to use a regular timer instead, with interval like 0.05 seconds.
Comment: `CADisplayLink` not allow float value.
Comment: I meant you should try a regular `NSTimer`


calling another function from backbone.js fetch success

Question: I am trying to call another function on success of the fetch in the first function but I keep getting an undefined error.  The console.log('success') is working.
In the view:
secondFunction: function() {
  console.log('second function called');
},

someFunction: function() {
  someData.fetch({
    success: function(results) {
      console.log('success');
      this.secondFunction();
    }
  });
 },

When I do it like this it's fine but I need the secondFunction to wait until the success of the first for the data.
secondFunction: function() {
  console.log('second function called');
},

someFunction: function() {
  someData.fetch({
    success: function(results) {
      console.log('success');
    }
  });
  this.secondFunction();
 },

Answer: try:
someFunction: function() {
  var self = this;
  someData.fetch({
    success: function(results) {
      console.log('success');
      self.secondFunction();
    }
  });
 },

Note the use of self. Keep in mind you are in the callback function ;-)
Comment: self didn't seem to work but var that = this; worked.  Thanks for the reply.
Answer: you must bind this
`
someFunction: function() {
  someData.fetch({
    success: function(results) {
      console.log('success');
      this.secondFunction();
    }.bind(this)
  });
 },

`


Exchange 2013 with two wildcard certificates for services

Question: We've an Exchange Server with two different DNS names pointing to the same server, the internal and the external name. Something like this:
exchange.domain.com [External Domain]
exchange1.local.domain.com [Internal Domain]

So there are two wildcard certificates for those domains: *.local.domain.com and *.domain.com.
The problem happens when users come to the Exchange Server through the internal domain name. Since I was only able to use the *.domain.com certificate for IIS, I cannot match the internal certificate from clients coming with the internal DNS name.
The question is basically how to match the DNS domain name with the corresponding certificate? Since we can't reissue those certificates to have different SANs this isn't an option.
Thanks in advance.
Answer: If you have not Imported your certificate into Exchange, then you will need to open up the EMC, click Server Configuration, then on your Server right click and choose "Import Exchange Certificate".
You can upload multiple Certificates using this method, which will allow your server to choose the correct Cert based on whether your traffic is requesting the local or public address.
Then you will need to be sure your Hub transport/Client Access configurations (etc) are set to use the right URLs matching your SSL Certs.
You will see your choice of certificate(s) reflected in the IIS Default Web Site.
But keep in my to change it you cannot use solely IIS to do so, but instead the by using the method above, if you do change it accidentally from within IIS your server will stop responding to connections as it will have mismatched certificates in IIS/EMC.
Comment: Unfortunately it does not work this way. Both certificates are already on ECP, but Exchange fails to match them accordingly. It always deliver the *.example.com certificate. I don't know exactly if I've done something wrong, like you said about the Hub Transport and CAS. But I think they're right.
Answer: You should setup Split-Brain DNS at your internal DNS servers or you should create zone at your internal DNS servers with internal address resolution

exchange.domain.com
Answer: You need to set the IIS virtual directory to the correct domain.
With powershell you can validate the URL that way:

Get-ActiveSyncVirtualDirectory | fl internalurl,externalurl
Get-AutoDiscoverVirtualDirectory | fl internalurl,externalurl
Get-ECPVirtualDirectory | fl internalurl,externalurl
Get-OabVirtualDirectory | fl internalurl,externalurl
Get-WebServicesVirtualDirectory | fl internalurl,externalurl

You can set the new value that way, with a Set- command:

Get-ActiveSyncVirtualDirectory -server EXCHANGE |
  Set-ActiveSyncVirtualDirectory -ExternalUrl
  'https://mail.DOMAIN.ca/Microsoft-Server-ActiveSync' -InternalUrl
  'https://mail.DOMAIN.ca/Microsoft-Server-ActiveSync'
Get-AutodiscoverVirtualDirectory -server EXCHANGE |
  Set-AutodiscoverVirtualDirectory -ExternalUrl
  'https://mail.DOMAIN.ca/Autodiscover/Autodiscover.xml' -InternalUrl
  'https://mail.DOMAIN.ca/Autodiscover/Autodiscover.xml'
Get-ECPVirtualDirectory -server EXCHANGE | Set-ECPVirtualDirectory
  -ExternalUrl 'https://mail.DOMAIN.ca/ECP' -InternalUrl 'https://mail.DOMAIN.ca/ECP'
Get-OabVirtualDirectory -server EXCHANGE | Set-OabVirtualDirectory
  -ExternalUrl 'https://mail.DOMAIN.ca/OAB' -InternalUrl 'https://mail.DOMAIN.ca/OAB'
Get-WebServicesVirtualDirectory -server EXCHANGE |
  Set-WebServicesVirtualDirectory -ExternalUrl
  'https://mail.DOMAIN.ca/EWS/Exchange.asmx' -InternalUrl
  'https://mail.DOMAIN.ca/EWS/Exchange.asmx'

Via the GUI you can look there for a guide
After those change you must issue a iisreset, and restart the outlook client.
Don't forget to create a host record in your local DNS to match the domain name with a local IP, or if you have a firewall that support it you can create a inside NAT rule that when the request is your public exchange IP, it rewrite the destination as the local IP.


Reverse for with no arguments not found for URL

Question: I am attempting to create a view that allows users to delete a build log. On the view that shows the delete button with a link to the delete page I am getting the error
Reverse for 'build-log-delete' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/build\\-log/(?P<pkz>[0-9]+)/delete$']

If I understand this error correctly its because I am not passing paramaters in the url.
Delete

However I do not understand why I need to pass parameters in the URL as I am not passing any new values into the URL and if so what parameters I would pass. Do I have to re pass the previous two?
urls
path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'),

path('post/<int:pk>/build-log/<int:pkz>/delete', views.BuildLogDelete, name='build-log-delete') #error

views
def BuildLogDisplay(request, pk, pkz ):
    post = BuildLog.objects.filter(post_id=pk)
    log = BuildLog.objects.get(pk=pkz)

    context = {
         'post':post, 'log':log
        }

    return render(request, 'blog/buildlog.html', context)

def BuildLogDelete(request):
    context = { }
    return render(request, 'blog/BuildLogDelete.html', context)

full template

                {{ log.title }}

            {% if log.author == user %}
             Update
            Delete
            {% endif %}

{{ log.content | safe}}

Answer: There are multiple errors in you code. You are not passing args in BuildLogDelete view but in url you are using those arguments. So the correct view should look like this.
def BuildLogDelete(request,pk,pkz):
    # delete code
    # write here

Next mistake which i can see is you are assigning queryset rather than object for the post key in BuildLogDisplay view. You should assign object.
post = BuildLog.objects.get(post_id=pk)

Lastly your original error mentioned in the question is because your build-log-delete url expects two arguments i.e pk and pkz but you haven't passed them in template. So it should be like this.
Delete
I would highly suggest you to look for already given generic views like ListView, TemplateView, CreateView, UpdateView and DeleteView. This will prevent you from reinventing the wheel
Ref: Django Class Based Generic Views
Comment: Thanks for the answer! For `post = BuildLog.objects.get(post_id=pk)` when I use that I get the error `MultipleObjectsReturned` thats why i was doing it the other way.


update text format "filtered html" on old nodes

Question: currently i have a content type with multiple nodes, that were created with a text format of plain text. is there any way to update all these nodes to be filtered html?
/admin/config/content/formats
i changed the default format to be filtered html, by making its weight -10 it is now at the top of the list. now when a user creates a new node it will have this format but how do i convert all the old ones?
Answer: Update the database directly using SQL queries. The queries are something like
UPDATE field_data_field_[example] SET field_[example]_format = '[text_format]';
UPDATE field_revision_field_[example] SET field_[example]_format = '[text_format]'

for a field named field_[example] that was created with the Field UI module and a text format with machine name [text_format]. Clear the cache afterwards.


Closure of $\mathbb{Q}\times\mathbb{Q}$ in British Rail metric

Question: I'm wondering what is the closure of $\mathbb{Q}\times\mathbb{Q}$ in $(\mathbb{R}^{2},d)$ where $d$ is British Rail metric:
$$ d(x,y) = \left\{ \begin{array}{lr} ||x-y|| & \text{if} \; \; x,y,0 \; \; \text{are collinear,}\\ || x || + ||y||& \;\;\;\; \text{otherwise.} \end{array} \right. $$
At this moment I'm thinking about set
$$\{(x,y)\in\mathbb{R}^{2}:\exists q\in\mathbb{Q} \quad qx=y\lor x=0\}$$
because I think it is a set of all points that lie on lines passing through $(0,0)$ with rational slope.
Is it correct answer to my question?
Comment: In your solution, the only point with $x=0$ belonging to the closure is $(0,0)$ (I know that's just a technicality).
Comment: That's right, thanks!
Answer: Since this looks like a homework, I will only provide some hints.
Given two points $p, q$ in $R^2$ I will say that the pair $(p,q)$ has type I if $p, q, 0$ are collinear and type II otherwise. Given any point $p\in R^2$ and a sequence $(q_n)$ in $R^2$ I will say that the sequence $(q_n)$ is of type I if all pairs $(p,q_n)$ are of type I. Similarly, for type  II.
Now, fix $p$. Any sequence $q_n$  splits as (at most) two infinite subsequences, each subsequence has either type I or type II. Assuming that $(q_n)$ is of type II, what can you say about
$$
\lim \inf_{n\to\infty} d(p, q_n) ?
$$
For what points $p$ there is a sequence $(q_n)$ of type I consisting entirely of points in ${\mathbb Q}^2$?
Once you have answered these two questions, you will obtain a description of the closure of ${\mathbb Q}^2$ (with respect to the metric $d$) as a union of certain lines in $R^2$.
See also this, for Brian Scott's answer which will help.
Comment: To be honest it's my own extension of homework (homework required to show that $\mathbb{Q}\times\mathbb{Q}$ is not dense in that metric space). And basicly to answer "For what points $p$..." I can repeat my answer from original post. I think that $p$ are points from lines with rational slope that pass through origin. This is based on my conclusion from homework that for point $x=(\sqrt[]{2},4)$ there is no such $q_{n}$ that its limit would be $x$.
Comment: @zinsek OK, if you can prove this guess (and this is not even a calculus problem), you are half-way through the solution.
Comment: Ok, so $x$ is from line with slope $2\sqrt[]{2}$, for for every point $(a,b)\in\mathbb{R}^{2}$ if $a$ is rational then $b$ cannot be. Based on that, any point from $\mathbb{Q}^{2}$ cannot belong to this line apart from $(0,0)$. So every $q_{n}$ is type $II$ with $(x,q_{n})$ so $x$ cannot be limit of $q_{n}$ because every point from $q_{n}$ is at least $d(0,x) = 3\sqrt[]{2}$ away from $x$. That's a bit informal but I think it's clear enough. So now I would need to show that for any point from set mentioned in original post exists $q_{n}$ that converges to that point?
Comment: @zinsek: Very good! The second part is simple calculus since you are using the usual norm on rational lines.


make UIScrollview scroll

Question: I have porblem that my UIScrollView does not scroll I don't think that is a problem with iphone emulator. Here is my way to construct UIScrollView:
[scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES; // default is NO, we want to restrict drawing within our scrollview
scrollView.scrollEnabled = YES;

and I add UILabel to it, to which later I add some info from xml.
labeL = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 1000)];
labeL.numberOfLines = 0;
labeL.text =@"";
[scrollView addSubview:labeL];

this is how I add value to UILabel:
vypisObratString = [[NSMutableString alloc] initWithString:labeL.text];
if (turnOver) {
    turnOver = NO;
    [vypisObratString appendString:@"----------------"];
    [vypisObratString appendString:@"\n"];
    labeL.text = vypisObratString;
}

But when I compile the program it writes the corect values but the last line is like this:
12.1.2010...

and it does not scroll. Why? What I missing?
Answer: I think your issue is with setting the size of the scroll view which needs to be larger than the size of the iphone (i.e. it needs to know that there is some area outside the phone display to scroll to).
Something along these lines:
UIScrollView *tempScrollView=(UIScrollView *)self.view;
tempScrollView.contentSize=CGSizeMake(800,800);

That should be all you need to make it scroll.
Cheers
James
Comment: Thank It start to scroll.Your answer was right but now it does not scroll all of my UILabel which is CGRectMake(0, 0, 320, 1000) has it something with CGSizeMake(600,400)?
Comment: Yes - sorry have updated the code above. You need to set the CGSizeMake parameters to fit the size of the area you want to be scrollable.

make UIScrollview scroll


Increment field value in update query

Question: I am converting some module from d5 to d7, and in old code there is an update query like this:
<?php
db_query("UPDATE {a_table} SET count = count + 1 WHERE field1 = %d", $some_value);

As we see, it is incrementing a field value (AFAIK it is a mysql feature).
But, if I use new style of update it won't work.
<?php
db_update('a_table')
    ->fields(array('count' => 'count + 1',))
    ->condition('field1', $some_value)
    ->execute();

Are there any workaround within new style of db update without running an extra query to get existing field value to increment it?
Answer: You can do it by adding an expression to the query:
db_update('a_table')
  ->expression('count', 'count + 1')
  ->condition('field1', $some_value)
  ->execute();

Comment: Just noting, this also works in Drupal 8

Increment field value in update query


Locally approximate an ellipsoid around two points with a sphere

Question: I am trying to find a way to approximate an ellipsoid around two points using spheres.
Take the following diagram:

As you can see, in my diagram (which is a cross section of the ellipsoid and the appproximating sphere)
The region of the sphere contained in between the points $P_1$ and $P_2$ is somewhat close to the actuall region on the ellipsoid.
I am looking for a method to construct such an approximating sphere that is "Good". By "Good" I mean that the method needs not be perfect, just provide a good enough approximation, even if it's analytically wrong.
EDIT:
By "around the points" I mean that the only part of the ellipsoid I actually care about is the geodesic section in between the two points. I want to approximate said geodesic with a great circle in the sphere (I know that the actual geodesic and the great circle are very different and as such this will invariably deform the surface). The goal is to try to get a good approximation of this geodesic with a sphere,
EDIT2:
The ellipsoid can be represented in any way, which includes the implicit representation and any of the possible parametrizations.
Points are represented in a standard cartesian system with three coordinates $(x,y,z)$
Comment: Could you clarify what do you mean by "around two points"? The figure seems to imply a "circular region" on the ellipsoid surface where the given two points are diametrically opposed. Am I reading your post correctly?
Comment: @LeeDavidChungLin By around two points I mean an epsilon region around the section of the geodesic connecting the 2 points on the ellipsoid. In essence I am not trying to approximate the entire ellipsoid, justa small region around the shortest line connecting both points
Comment: How are you parameterizing your ellipsoid?  Similarly, how are you defining what the two points are?
Comment: Implicit function or any valid parametric representation, it matters little.

The points are 3D vectors
Answer: Here is a possible solution that fits these two additional conditions:

The approximating sphere includes the two points
If your ellipsoid is a sphere the approximation is exact

Let the equation of the ellipsoid be defined as:
$$ \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1 $$
Any point on the surface is defined as:
$$ \vec p_p = ( x_p, y_p, z_p ) $$
The two points in question are where $p=1$ and $p=2$.
A normal vector to the surface at any point is:
$$ \vec n_p = ( \frac{x_p}{a^2}, \frac{y_p}{a^b}, \frac{z_p}{c^2} ) $$
In order for the sphere to contain both points, its center must lay on the plane that is the perpendicular bisector of the two points.  This halfway plane contains the midpoint of the two points and its normal is the difference of the two points.
$$ \vec m = \frac{ \vec p_1 + \vec p_2 }{2} $$
$$ \vec d = \vec p_1 - \vec p_2 $$
Let $ \vec h $ be any point on the plane.
$$ ( \vec h - \vec m ) \cdot \vec d = 0 $$
$$ \vec h \cdot \vec d = \vec m \cdot \vec d $$
Any line normal to the surface at point $p$ can be parameterized as:
$$ \vec g_p(t_p) = t_p \vec n_p + \vec p_p $$
The value of $t_p$ where the line intersects the halfway plane at point $ \vec q_p $ can be found:
$$ \vec q_p \cdot \vec d = ( t_p^* \vec n_p + \vec p_p ) \cdot \vec d = \vec m \cdot \vec d $$
$$ t_p^* = \frac{\vec m \cdot \vec d - \vec p_p \cdot \vec d}{\vec n_p \cdot \vec d } $$
$$ \vec q_p = t_p^* \vec n_p + \vec p_p $$
Each of the normal lines from the two points will intersect the halfway plane.  For simplicity, define the center of the sphere $ \vec s $ at the midpoint of these two points.
$$ \vec s = \frac{ \vec q_1 + \vec q_2 }{2} = ( x_s, y_s, z_s ) $$
The radius is then:
$$ r = \| \vec p_1 - \vec s \|  = \| \vec p_2 - \vec s \| $$
And the equation for the approximating sphere is:
$$ ( x - x_s )^2 + ( y - y_s )^2 + ( z - z_s )^2 = r^2 $$
Notice that this approach does not do any kind of fit function between the ellipsoid surface and the approximating sphere surface.  If such a function were defined, it could be evaluated for spheres with centers on the halfway plane in the neighborhood of $ \vec q_1 $ amd $ \vec q_2 $.  Allowing the center to move off the plane relaxes the constraint the sphere needs to contain both points.
To find your geodesic points, warp the line segment between the points to fit on the surface of the sphere.
$$ \vec v = ( t \vec d + \vec m ) - \vec s $$
$$ \vec w = r \frac{\vec v}{\|\vec v\|} + \vec s $$
Where $t$ goes from -1/2 to 1/2.
A better geodesic can probably be found by shifting the center of the sphere according to $t$, and adjusting the radius correspondingly, along the line segment:
$$ \vec s(t) = t ( \vec q_2 - \vec q_1 )   + ( \vec q_1 + \vec q_2 ) / 2  $$
I'll have to think about that.  Of course, warping the line segment to fit on the ellipsoid surface would be even better.
Hope this helps.
Ced
P.S.  A little post posting searching found these:

Wkipedia: Geodesics on an ellipsoid
How do you find a geodesic on an ellipsoid?
Comment: Lol I am not sure if you noticed but, the SO question is mine : P
Comment: @Makogan, I notice after I went back and read it more carefully.  Are you able to follow my recipe?


X divided by Y, N times until a boundary is reached

Question: not sure how to ask this but here is an example:
X = 31.0
Y = 2.0
Z = 5.0
i want to keep dividing X by Y and the result of that again by Y and so on until i reach Z i will stop.
assuming N is the number of times i had to do this Operation, can N be calculated in a single step without having to divide?
above example solved
<code>31/2   = 15.5
15.5/2 = 7.75
7.75/2 = 3.878 stop as the result got to less than Z=5
</code>
in this case N is 3.
is it possible to write a function F(X,Y,Z)=N=?? which will give me N in one step of calculation?
Comment: hint: it could involve logarithms
Answer: Hint:
$$Y^{-n}\cdot X < Z \implies Y^{-n} <\frac{Z}{X}$$
What happens if you take the natural logarithm of both sides?
Further, recall that
$$\ln(A^B) = B\cdot\ln(A)$$