Q:

Is the set $\{AB-BA\colon A,B\text{ are } n\times n\text{ matrices}\}$ a subspace of all square matrices of order $n$?

[${AB-BA }$ ,  where $A_{n\times n}$ and  $B_{n\times n}$ are  square matrices]  is this set   a subspace of the vector space of all square matrices of order $n$.
If yes then can you please make me understand how it is closed under addition.
If not then how traceless matrices become commutators.
I have become confused after reading the comments by Alex Wertheim here
,
Can anyone make me understand?

A:

Let $k$ be an infinite field. Then we have the following fact:
Proposition. Suppose $C\in\operatorname{Mat}_{n}(k)$ is an $n\times n$ matrix with entries in $k$ such that $\operatorname{Tr}(C)=0$. Then $C$ is a commutator, i.e. $C=AB-BA$ for some $A, B\in\operatorname{Mat}_{n}(k)$.
I learnt the following elegant proof from the book Mathematical Bridges by Andreescu, Mortici and Tetiva.
Proof. We first prove the following lemma:
Lemma. If $a_1, a_2, ..., a_n\in k$ are elements such that $a_1+a_2+\cdots + a_n=0$, then there exist distinct elements $b_1, b_2, ..., b_n\in k$ and a permutation $\pi: \{1, 2, ..., n\}\to \{1, 2, ..., n\}$ such that $a_i=b_i-b_{\pi(i)}$ for each $i=1, 2, ..., n$.
Proof of the lemma. We proceed by strong induction on $n$. When $n=1$, this is trivial as $a_1=0$ and so we can take $b_1=1$ and $\pi$ to be the identity permutation. For the inductive step, we have two cases:
Case 1. No proper subset of $\{a_1, ..., a_n\}$ adds up to zero.
Let $b_1$ be arbitrary. Define $b_2=b_1-a_1$. Similarly, define $b_3=b_2-a_2$, and so on. In other words, $b_{i+1} := b_{i}-a_{i}$ for $i=1, 2, ..., n-1$. By construction, $a_{i}=b_{i}-b_{i+1}$ for each $i$, so we can take the permutation $\pi: \{1, 2, ..., n\}\to \{1, 2, ..., n\}$ to be $\pi(i)=i+1$ for $i<n$ and $\pi(n)=1$.  Note the assumption $a_1+a_2+\cdots + a_n=0$ was used to conclude that $a_{n}=b_{n}-b_{1}$, so there is no issue when we "loop back" from $n$ to $1$. All we need to show is that $b_1, b_2, ..., b_n$ are distinct. If $b_i=b_j$ for $1\leq i<j\leq n$, then summing up the equalities $a_{i}=b_{i}-b_{i+1}$, $a_{i+1}=b_{i+1}-b_{i+2}$, ..., $a_{j-1}=b_{j-1}-b_{j}$ and taking advantage of the telescoping, we get $a_{i}+a_{i+1}+...+a_{j-1}=b_{i}-b_{j}=0$ which contradicts the assumption that no proper subset of ${a_1, ..., a_n}$ adds up to zero.
Case 2. Some proper subset of $\{a_1, ..., a_n\}$ adds up to zero.
In this case, we have $\{a_1, ..., a_n\}=\{c_1, c_2, ..., c_k\}\cup \{d_1, d_2, ..., d_{n-k}\}$ such that $c_1+c_2+\cdots + c_k=0$ where $1\leq k<n$. Since $a_1+a_2+\cdots + a_n=0$, this forces $d_1+d_2+\cdots + d_{n-k}=0$ as well. By induction hypothesis, we know that there exist permutations $\sigma: \{1, ..., k\}\to \{1, ..., k\}$, $\tau: \{1, ..., n-k\}\to \{1, ..., n-k\}$, distinct elements $\lambda_1, ..., \lambda_k$, and distinct elements $\mu_1, \mu_2, ..., \mu_{n-k}$ such that $c_i=\lambda_i-\lambda_{\sigma(i)}$ and $d_j=\mu_j-\mu_{\tau(j)}$. We can find some $r$ such that $r+d_j \neq c_i$ for every $i$ and $j$. This is where the assumption $k$ is infinite comes in. Anyways, now it is easy to "stitch" together these permutations. Simply define $b_i=\lambda_i$ for each $i=1,2, ..., k$, and define $b_{k+j} = r+d_{j}$ for each $j=1, ..., n-k$. Finally, define $\pi$ to be the permutation $\pi(i)=\sigma(i)$ for each $I=1,..., k$, and $\pi(k+j)=\tau(j)$ for each $j=1, ..., n-k$. The proof of the lemma is complete.
Proof of the Proposition. Let $C$ be a matrix with trace zero. Set $a_i:=c_{ii}$. Since $\operatorname{Tr}(C)=0$, we get $a_1 + a_2 + ... + a_n=0$. By the lemma above, we can write $a_i=b_{i}-b_{\pi(i)}$ for distinct elements $b_1, ..., b_n$ and some permutation $\pi$. It is straightforward to rewrite our matrix $C$ as a difference of two matrices $C=U-L$ where $U$ is an upper triangular matrix with diagonal entries $b_1, ..., b_n$, and $L$ is a lower triangular matrix with diagonal entries $b_{\pi(1)}, ..., b_{\pi(n)}$. Since $U$ and $L$ have distinct eigenvalues (namely, $b_1$, ..., $b_n$), they are both diagonalizable. In fact, they share the same set of eigenvalues, so if we set $D$ to be the diagonal matrix consisting of $b_1, ..., b_n$, then $U=PDP^{-1}$ and $L=QDQ^{-1}$ for some invertible matrices $P$, and $Q$. Write $D=Q^{-1}LQ$ and substitute this into $U=PDP^{-1}$ to get
$$U=P(Q^{-1}LQ)P^{-1}=(PQ^{-1})L(PQ^{-1})^{-1}=RLR^{-1}$$
where $R=PQ^{-1}$. Thus,
$$
C = U - L = RLR^{-1}-L = RLR^{-1} - (R^{-1}R)L = (RL)R^{-1}-R^{-1}(RL)
$$
So we set $A=RL$ and $B=R^{-1}$ to get $C=AB-BA$.

As I mentioned in the comments, the proposition implies that
$$
\{AB-BA: A, B \in\operatorname{Mat}_{n}(k)\} = \{C: \operatorname{Tr}(C)=0\}
$$
Since the right hand side is clearly a subspace, it follows that the set on the left hand side is actually a subspace! This is kind of surprising! It says that given $AB-BA$ and $CD-DC$, it follows that $(AB-BA) + (CD - DC) = RS-SR$ for some matrices $R, S$.


Q:

Balance returns zero but shows ether with web3.eth.getBalance on testrpc

Issue:
Using an account on testrpc I get 0 as my balance from within a program but I get the correct amount when I query balance at web3 command prompt:
//here I'm calling a function (shown below) from command line

contractInstance.queryBalance("0xf24qf4b3ae667a23f296f48eb92fa619310c95fd")
  { [String: '0'] s: 1, e: 0, c: [ 0 ] }
//here's I'm listing my accounts, just showing the first one to save space
web3.eth.accounts
  [ '0xf24qf4b3ae667a23f296f48eb92fa619310c95fd',
   ...

//here I am querying the balance directly at the command prompt

web3.eth.getBalance('0xf24qf4b3ae667a23f296f48eb92fa619310c95fd')
  { [String: '99999999999984495002'] s: 1, e: 19, c: [ 999999, 99999984495002 ] }

Here is the function call I'm making in my program:
function queryBalance(address addr) public constant returns (uint balance) {
    return balances[addr];
    }

What else I've tried
contractInstance.queryBalance("0xf24qf4b3ae667a23f296f48eb92fa619310c95fd", {from: web3.eth.accounts[0], gas: 4500000})
{ [String: '0'] s: 1, e: 0, c: [ 0 ] }
and
Environment:
web3.js environment on Mac with testrpc running
Thanks

A:

We have that web3.eth.getBalance returns the balance in ethers of your address.
But in your function
function queryBalance(address addr) public constant returns (uint balance) {
    return balances[addr];
}

You are returning the value you have stored in the balances mapping. If you didn't store anything the default value is zero.
To obtain the balance in ether of your address in solidity
function queryBalance(address addr) public constant returns (uint balance) {
    return addr.balance;
}


Q:

Why "would you rather..." not "will you rather..."?

I was writing a paragraph where I had to include two questions. They are (not exactly):

Will you reject the offer? Or would you rather embrace it knowing it is to your advantage?

It is for sure "would" in the second question, but since I have stated the first question with "will", I thought it would be more grammatical for both questions to be in the same tense, so it would be either "would" or "will".
However, the first question doesn't sound very properly with "would", and I think the reason is that it has some determination in it, and because it refers to a doing that may be taken in the near future.
I have searched for a question with "will + rather", but it seems that they can't be combined together; why?
According to the Oxford Dictionary, would rather is used to indicate one's preference in a particular matter.
And rather means to a certain or significant extent or degree.

Which doesn't indicate a low possibility as to attach it with "would".

A:

It needs to be would you for the sense of it, though will isn't incorrect.
"Will you reject the offer?" implies there's an offer, already made or coming soon, and you will have to answer.
Consider

"Will you reject the offer?  Or will you accept it?"  I have no idea which you will do
"Will you reject the offer?  Or will you accept it?  Or would you prefer to sleep on it and give them an answer in the morning?"  Instead of certainty of rejecting the offer, the certainty of accepting it, there is some uncertain additional option which you might prefer.

Your case:
Because the opposite of "reject" is "accept", to "embrace" it is a kind of uncertain possibility, hence it sounds better with the uncertainty of "would".  Other possibilities would be "or would you like to negotiate some changes first."
Note also that "rather" is slippery and can carry the sense of "prefer" or "very" (mainly UK), and sometimes just "instead".  "I'd rather have cake" = "I would prefer to have cake", "I rather like cake" = "I very much like cake", "Do this rather than that" = "Do this instead of that".  In your examples it's faintly ambiguous between "instead" and "prefer".

Will you reject the offer? Or will you rather accept it knowing it is to your advantage? makes a simple choice between the two.  ("rather" = "instead")
Will you reject the offer? Or would you rather embrace it knowing it is to your advantage? makes the embracing sound uncertain, speculative. ("rather" = "prefer to")

If we're suggesting it's a good idea, we might say

Will you reject the offer? Wouldn't you rather embrace it knowing it is to your advantage? makes the suggestion that you would prefer the embracing.
"Wouldn't you rather" is definitely "Wouldn't you prefer to".


Q:

'module' object has no attribute 'unescape'

This code works perfectly on the console but when I implement it in my flask application it says that there's an AttributeError
        clean = html.unescape(tweet.text)

        final = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', clean)

I also tried import html inside the for loop
and from html import unescape

A:

The html module was introduced in Python 3.4. If you're running Python 2.7, you might want to try HTMLParser.HTMLParser().unescape instead.

A:

The flask app is built using Python2:
import HTMLParser
HTMLParser.HTMLParser().unescape('Hello & World')


Q:

Surprising results with std::fstream

I wrote a short program to generate evenly-spaced random digits and save them to a generic text file. If I ask it to generate exactly 786432 digits (spaces every six digits) the output displays as random Chinese and Japanese characters. Why?
I'm using standard-library classes for file I/O and 64-bit Xorshift as my PRNG.
The program (compiled under MSVC):
#include <iostream>
#include <fstream>
#include <algorithm>

// From https://en.wikipedia.org/wiki/Xorshift
uint64_t xorsh64star(uint64_t* state)
{
    uint64_t x = *state;
    x ^= x >> 12;
    x ^= x << 25;
    x ^= x >> 27;
    state[0] = x;
    return x * 0x2545F4914F6CDD1D;
}

int main()
{
    uint64_t nDigits = 0;
    uint64_t wordLen = 1;
    std::cout << "How many digits?\n";
    std::cin >> nDigits;
    std::cout << "How many digits/word?\n";
    std::cin >> wordLen;
    std::fstream* txt = new std::fstream("randTxt.txt", std::ios::out);
    std::cout << "writing...";
    uint64_t charCtr = 0;
    uint64_t xorshState = 1103515245U; // GLIB C init constant, from https://www.shadertoy.com/view/XlXcW4
    for (uint64_t i = 0; i < nDigits; i += 1)
    {
        uint64_t rnd = xorsh64star(&xorshState) % uint64_t(9);
        *txt << rnd;
        charCtr += 1;
        if (!(charCtr % wordLen) && charCtr != 1)
        {
            *txt << ' ';
            charCtr += 1;
        }
    }
    std::cout << "finished! :D";
    return 0;
}

Output with 786431 digits:

Output with 786432 digits:

Output with 786433 digits:

A:

Here is the fix. I'm not sure what causes the original problem, but once the if statement is changed to:
if (!(charCtr % wordLen) && charCtr != 1
{
    txt << ' ';
//  charCtr += 1;    // This makes each word after the first 1 digit shorter.
}

the final .txt file is now shown properly, which fixes your notepad viewing problem and all your words now have 6 digits, not just the first one.

Originally, I reproduced the same problem by compiling your code with MSVS17 on Win 10 64bit:


Q:

New answers message while reading a question

A couple of times now, I've experienced that while reading a somewhat short - yet easy, understandable and valid - question, being answered three or more times before I'm done reading the question.
Now I'm ready to type my answer, but even though I started typing, I don't get any notifications about new answers. I suspect this is because the answers were submitted before I started typing my own.
After submitting my answer, I see three other answers I could have sworn was copied from what I just wrote - and the three others might think the same thing about me.
I'd like to suggest that the 'New answers' notification pops up even though, I haven't started writing an answer.
This would help me not making redundant answers (redundant as in writing exactly what someone else just did) and it could potentially help making a an answered question more clear and transparent.

A:

This feature has been implemented.


Q:

Is my kernel safe to use?

I am running Ubuntu server 12.04 and my fresh installation is using the 3.2.0-60-generic kernel, however when I go to https://www.kernel.org/ it says the latest stable kernel is only 3.14
I don't want to run into problems down the line.

A:

LTS
The kernel released with 12.04 server at its outset was v3.2.
Canonical have committed to supporting v3.2 of the kernel:

The original 12.04 stack in Precise will remain supported for the
usual 5yr life cycle of the LTS release.

source
What this means is that the kernel v3.2 will receive security and other stability fixes throughout the 5 years of the support period.
Newer kernels are available for each point release - these are called enablement stacks and are primarily for newer hardware.  You dont need to install these if kernel 3.2 is just running fine on your hardware.
Obviously, if you need to add newer hardware cards to your server you should first check that the cards work with the kernel 3.2 series.  Likewise, if you image the server to install on newer hardware, then you should similarly check 3.2 compatibility.

Linked Blog:

http://www.jorgecastro.org/2013/02/19/what-the-lts-enablement-stack-means-for-sysadmins/

Linked Wiki:

https://wiki.ubuntu.com/Kernel/LTSEnablementStack

Linked Question:

How to remove Kernel/LTS Enablement Stack?

A:

I think the OP might be (or was) under the mistaken impression that 3.2 is newer than 3.14 because he's viewing 3.2 > 3.14 in a decimal sense instead of thinking about three separate numbers.  He said " the latest stable kernel is only 3.14," which makes me think his concern is that 3.2 is too "bleeding edge." He's obviously good to use 3.2 in either case as was rightly pointed out, but I wanted to make sure he understood the versioning system for future concerns.

A:

Yes, the 3.2.0 kernel is absolutely safe to use.
Linux distributions (Ubuntu 12.04, Ubuntu 13.10, CentOS 6.5, etc.) will typically choose, and stay at, a base kernel version in order to maintain security, stability, and other features that might cause issues if moving to a newer kernel.
The newer kernel versions usually have cool, "bleeding-edge" features (performance improvements, updated drivers, etc.), but with the sacrifice of being less stable and less tested. The 3.2.0 kernel has been tested and vetted by dozens of organizations and individuals that have made absolutely sure that it is stable enough to host "production-ready" applications and environments.
To compare, CentOS 6.5 runs kernel version 2.6.32-431, which multiple enterprise organizations use to host mission-critical applications and devices.


Q:

Mod Security blocking wordpress

I have a wordpress site with Modsecurity and apache. When I try to access wordpress it throws a 403 Forbidden error. Neither the admin panel nor the frontend is accessible. Here are the logs:
[Tue Mar 18 08:17:41 2014] [error] [client 122.170.1.216] ModSecurity: Access denied with code 403 (phase 4). Pattern match "^5\\\\d{2}$" at RESPONSE_STATUS. [file "/etc/httpd/modsecurity.d/activated_rules/modsecurity_crs_50_outbound.conf"] [line "53"] [id "970901"] [rev "2"] [msg "The application is not available"] [data "Matched Data: 500 found within RESPONSE_STATUS: 500"] [severity "ERROR"] [ver "OWASP_CRS/2.2.6"] [maturity "9"] [accuracy "9"] [tag "WASCTC/WASC-13"] [tag "OWASP_TOP_10/A6"] [tag "PCI/6.5.6"] [hostname "www.bullion.ambab.com"] [uri "/research/wp-admin/index.php"] [unique_id "UygBJQoLkgUAABXkL-8AAAAX"]
[Tue Mar 18 08:17:41 2014] [error] [client 122.170.1.216] ModSecurity: Warning. Operator GE matched 4 at TX:outbound_anomaly_score. [file "/etc/httpd/modsecurity.d/activated_rules/modsecurity_crs_60_correlation.conf"] [line "40"] [id "981205"] [msg "Outbound Anomaly Score Exceeded (score 4): The application is not available"] [hostname "www.bullion.ambab.com"] [uri "/research/wp-admin/index.php"] [unique_id "UygBJQoLkgUAABXkL-8AAAAX"]

This can be solved by disabling RuleByID 981205. But I do not want those rules to be bypassed because it might open a door for an attack.
Is there a way to solve this problem by modifying wordpress source?

A:

Modifying the WordPress sources is highly not recommended, because after update the modified files will be overwritten again.
Better approach is to refine your mod_security rules by allowing some more requests to be sent to the WordPress system.
ModSecurity (also known as “modsec”) has proven itself useful in a variety of situations, and again this is true in assisting with WordPress brute force attempts resulting in a Denial of Service (DoS) attack. While a number of WordPress plugins exist to prevent such attacks, custom modsec rules can prevent such attacks for all WordPress installations on a server. Modsec immediately filters incoming HTTP requests, which assists against taxing server resources.
These rules will block access for the offending IP address for 5 minutes upon 10 failed login attempts over a 3 minute duration. These rules have been automatically updated in the custom rules for Liquid Web’s ServerSecure service. For customers without ServerSecure, these rules can be added to their custom modsec rules. To accomplish this, edit your custom modsec user rules and append the file with the rules provided below. For CPanel servers, this file is likely located at /usr/local/apache/conf/
Below are the examples:
SecAction phase:1,nolog,pass,initcol:ip=%{REMOTE_ADDR},initcol:user=%{REMOTE_ADDR},id:5000134
 <Locationmatch "/wp-login.php">
 # Setup brute force detection.
 # React if block flag has been set.
 SecRule user:bf_block "@gt 0" "deny,status:401,log,id:5000135,msg:'ip address blocked for 5 minutes, more than 10 login attempts in 3 minutes.'"
 # Setup Tracking. On a successful login, a 302 redirect is performed, a 200 indicates login failed.
 SecRule RESPONSE_STATUS "^302" "phase:5,t:none,nolog,pass,setvar:ip.bf_counter=0,id:5000136"
 SecRule RESPONSE_STATUS "^200" "phase:5,chain,t:none,nolog,pass,setvar:ip.bf_counter=+1,deprecatevar:ip.bf_counter=1/180,id:5000137"
 SecRule ip:bf_counter "@gt 10" "t:none,setvar:user.bf_block=1,expirevar:user.bf_block=300,setvar:ip.bf_counter=0"
 </Locationmatch>


Q:

Alphabetical array sort - lowercase first

Given the array :
var myArray = ['d','a','k','v','z','A','t','G']

If I were to use :
myArray.sort()

The result would be :
myArray = ['A','G','a','d','k','t','v','z']

Is there a way of modifying the sort function or the output to put the uppercase letters at the end of the array like this :
myArray = ['a','d','k','t','v','z','A','G']

Either pure Javascript or jQuery would be OK.

A:

Test the first character and apply compare:

var myArray = ['d', 'a', 'k', 'v', 'z', 'A', 't', 'G', 'V'];

myArray.sort(function (a, b) {
    if (a[0] === a[0].toLocaleLowerCase() && b[0] === b[0].toLocaleLowerCase() ||
        a[0] === a[0].toLocaleUpperCase() && b[0] === b[0].toLocaleUpperCase()) {
        return a.localeCompare(b);
    }
    if (a[0] === a[0].toLocaleLowerCase()) {
        return -1;
    }
    return 1;
});

document.write('<pre>' + JSON.stringify(myArray, 0, 4) + '</pre>');


Q:

¿Cómo hacer un onclick de un elemento append? JQuery

Me explico. quiero crear varios elemento
$("#restriction").click(function(){
      efect = false; //No tiene nada que ver
      redraw(); //Tampoco tiene algo que ver
      v = $('#inputRess').val();
      if (v <= 1) {
        $("#Nanswer").html("
¡Ups!  Al menos dos restricciónes.<button type='button' class='close' data-dismiss='alert' aria-label='Close' onclick='inputRess.disabled=false;'>×</button>
");
      }else{
        $(".boxAcount").hide();
        //NgenerarM();
        mat = "";
        for(var k = 0; k < 2; k++) {
            mat += "";
            mat += "
";
            mat += "
Objeto "+(k+1)+"
";
            mat += "<input type='text' class='form-control' id='ob"+k+"'>";
            mat += "
";
        }
        mat += "<button type='button' class='btn btn-default btn-block' id='afterObj'>Block level button</button>";
        $("#Nmatriz").append(mat); //Acá creo todos los elementos
      }
});
$("#afterObj").click(function(){ //Acá quiero usar el button creado en el último mat llamado afterObj
    $("#Nmatriz").append('hola');
});

Pero a la vez quiero usarlos. No sé si se puede, pero al intentarlo el boton ni siquiera envía a consola

A:

Los elementos que se vayan agregando después de la carga inicial del DOM no son reconocidos pero si son existentes, por lo cual debes usar delegate para asignar los eventos a hijos dada una selección particular y no un elemento especifico.
Para usar delegate debes seleccionar un contenedor padre y asignar la acción en los hijos.
Ejemplo:
$( "body" ).delegate( "p", "click", function() {
  alert( $( this ).text() );
});

Otro ejemplo:
$( "body" ).delegate( "p", "click", function() {
  $( this ).after( "
Another paragraph!
" );
});

También puedes delegar un evento en el evento de la siguiente manera:
$( "#dataTable tbody" ).on( "click", "tr", function() {
  console.log( $( this ).text() );
});

A:

El problema que tienes es que no enlazas el evento click con los nuevos elementos, es decir creas elementos y creastes el evento click pero nunca lo enlazas es decir cada uno anda por su lado; hice un ejemplo resumido de lo que tu estas haciendo y el otro como deberias de hacerlo:
Como tu lo tienes:

$("#agregar").click(function(){

  let htmlE = "<button type='button' class='btn btn-default btn-block' id='afterObj'>Block level button</button>";

  $("#nuevos-elementos").append(htmlE);

});

$("#afterObj").click(function(){
  alert("Si, me distes click!!!")
});
#nuevos-elementos{
  border:1px solid red;
  padding:5px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<button id="agregar">Agregar nuevo elementos</button>

Como veras es un ejemplo similar al tuyo donde vas creando nuevos elementos y creas el evento click pero nunca se entienden, ahora te colocare como debe de ser:

$("#agregar").click(function(){

  let htmlE = "<button type='button' class='btn btn-default btn-block afterObj'>Block level button</button>";

  $("#nuevos-elementos").append(htmlE);
  $(".afterObj:last").on("click",function(){
    alert("Si, me distes click!!!, soy el botón "+($(this).index()+1)+" creado")
  });

});
#nuevos-elementos{
  border:1px solid red;
  padding:5px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<button id="agregar">Agregar nuevo elementos</button>

Aquí movi el evento click inmediatamente luego del append() ya que estoy creando el elemento e inmdiatamente le asigno el evento click, tambien le hice referencia a dicho objeto por la clase y no por un id porque si lo haces solo por el id solo te hara el vento click el primero y los demas no. En resumen el problema era el momento en el cual debes asignar el evento. Espero que sea lo que andas buscando.


Q:

NSOperationQueue: Can't add UIBarButtonItem in the Toolbar on Main Thread

In my UIViewController I want to add a UIBarButtonItem in the Toolbar, but the new Button doesn't appear. What am I doing wrong?
- (void)doLogin:(NSString *)name password:(NSString *)password {
 // 1.: start the Thread:
 NSInvocationOperation *invOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(backgroundTaskLogin:) object:request];
 [self.opQueue addOperation:invOperation];
}

- (void)backgroundTaskLogin:(NSString *)request2 {
 // 2.: jump back in the Main Thread in show a cancel button in den toolbar:
 [self performSelectorOnMainThread:@selector(showCancelButton) withObject:nil waitUntilDone:NO];
}

- (void)showCancelButton {
 // 3.: add a new Cancel-Button in the Toolbar:
 UIBarButtonItem *tempButtonCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelLogin)];
 NSMutableArray *myButtons = (NSMutableArray *)self.toolbarItems;
 NSLog(@"Count buttons: %d", [self.toolbarItems count]); // DEBUGGER: 2

 [myButtons addObject:tempButtonCancel];
 [tempButtonCancel release];

 NSLog(@"Count buttons: %d", [self.toolbarItems count]); // DEBUGGER: 3

 // PROBLEM: I don't see the new Toolbar-Button :-(
}

A:

You can't rely on self.toolbarItems being a mutable array. It may be one in your case if you assigned a mutable array to that property before but you can't expect the view controller to notice a change in a property if you don't use the documented interface.
Create a new array and use the setter to assign it to toolbarItems:
NSMutableArray *newToolbarItems = [NSMutableArray arrayWithArray:self.toolbarItems];
[newToolbarItems addObject:tempButtonCancel];
self.toolbarItems = newToolbarItems;


Q:

Error on compiling Android App in Eclippse ?

I have freshly installed Ubuntu OS , installed Eclipse and then added Android sdk as well as running ABD fine.But while compiling on Simulator or Device I am getting the following error on console
    [2011-11-04 22:28:25 - dealkart] ERROR: Unknown option '--no-crunch'
    [2011-11-04 22:28:25 - dealkart] Android Asset Packaging Tool
    [2011-11-04 22:28:25 - dealkart]
    [2011-11-04 22:28:25 - dealkart] Usage:
    [2011-11-04 22:28:25 - dealkart]  aapt l[ist] [-v] [-a] file.{zip,jar,apk}
    [2011-11-04 22:28:25 - dealkart]    List contents of Zip-compatible archive.
    [2011-11-04 22:28:25 - dealkart]
    [2011-11-04 22:28:25 - dealkart]  aapt d[ump] [--values] WHAT file.{apk} [asset [asset ...]]
    [2011-11-04 22:28:25 - dealkart]    badging          Print the label and icon for the app declared in APK.
    [2011-11-04 22:28:25 - dealkart]    permissions      Print the permissions from the APK.
    [2011-11-04 22:28:25 - dealkart]    resources        Print the resource table from the APK.
    [2011-11-04 22:28:25 - dealkart]    configurations   Print the configurations in the APK.
    [2011-11-04 22:28:25 - dealkart]    xmltree          Print the compiled xmls in the given assets.
    [2011-11-04 22:28:25 - dealkart]    xmlstrings       Print the strings of the given compiled xml assets.
    [2011-11-04 22:28:25 - dealkart]
    [2011-11-04 22:28:25 - dealkart]  aapt p[ackage] [-d][-f][-m][-u][-v][-x][-z][-M AndroidManifest.xml] \
    [2011-11-04 22:28:25 - dealkart]         [-0 extension [-0 extension ...]] [-g tolerance] [-j jarfile] \
    [2011-11-04 22:28:25 - dealkart]         [--debug-mode] [--min-sdk-version VAL] [--target-sdk-version VAL] \
    [2011-11-04 22:28:25 - dealkart]         [--app-version VAL] [--app-version-name TEXT] [--custom-package VAL] \
    [2011-11-04 22:28:25 - dealkart]         [--rename-manifest-package PACKAGE] \
    [2011-11-04 22:28:25 - dealkart]         [--rename-instrumentation-target-package PACKAGE] \
    [2011-11-04 22:28:25 - dealkart]         [--utf16] [--auto-add-overlay] \
    [2011-11-04 22:28:25 - dealkart]         [--max-res-version VAL] \
    [2011-11-04 22:28:25 - dealkart]         [-I base-package [-I base-package ...]] \
    [2011-11-04 22:28:25 - dealkart]         [-A asset-source-dir]  [-G class-list-file] [-P public-definitions-file] \
    [2011-11-04 22:28:25 - dealkart]         [-S resource-sources [-S resource-sources ...]]         [-F apk-file] [-J R-file-dir] \
    [2011-11-04 22:28:25 - dealkart]         [--product product1,product2,...] \
    [2011-11-04 22:28:25 - dealkart]         [raw-files-dir [raw-files-dir] ...]
    [2011-11-04 22:28:25 - dealkart]
    [2011-11-04 22:28:25 - dealkart]    Package the android resources.  It will read assets and resources that are
    [2011-11-04 22:28:25 - dealkart]    supplied with the -M -A -S or raw-files-dir arguments.  The -J -P -F and -R
    [2011-11-04 22:28:25 - dealkart]    options control which files are output.
    [2011-11-04 22:28:25 - dealkart]
    [2011-11-04 22:28:25 - dealkart]  aapt r[emove] [-v] file.{zip,jar,apk} file1 [file2 ...]
    [2011-11-04 22:28:25 - dealkart]    Delete specified files from Zip-compatible archive.
    [2011-11-04 22:28:25 - dealkart]
    [2011-11-04 22:28:25 - dealkart]  aapt a[dd] [-v] file.{zip,jar,apk} file1 [file2 ...]
    [2011-11-04 22:28:25 - dealkart]    Add specified files to Zip-compatible archive.
    [2011-11-04 22:28:25 - dealkart]
    [2011-11-04 22:28:25 - dealkart]  aapt v[ersion]
    [2011-11-04 22:28:25 - dealkart]    Print program version.
    [2011-11-04 22:28:25 - dealkart]
    [2011-11-04 22:28:25 - dealkart]  Modifiers:
    [2011-11-04 22:28:25 - dealkart]    -a  print Android-specific data (resources, manifest) when listing
    [2011-11-04 22:28:25 - dealkart]    -c  specify which configurations to include.  The default is all
    [2011-11-04 22:28:25 - dealkart]        configurations.  The value of the parameter should be a comma
    [2011-11-04 22:28:25 - dealkart]        separated list of configuration values.  Locales should be specified
    [2011-11-04 22:28:25 - dealkart]        as either a language or language-region pair.  Some examples:
    [2011-11-04 22:28:25 - dealkart]             en
    [2011-11-04 22:28:25 - dealkart]             port,en
    [2011-11-04 22:28:25 - dealkart]             port,land,en_US
    [2011-11-04 22:28:25 - dealkart]        If you put the special locale, zz_ZZ on the list, it will perform
    [2011-11-04 22:28:25 - dealkart]        pseudolocalization on the default locale, modifying all of the
    [2011-11-04 22:28:25 - dealkart]        strings so you can look for strings that missed the
    [2011-11-04 22:28:25 - dealkart]        internationalization process.  For example:
    [2011-11-04 22:28:25 - dealkart]             port,land,zz_ZZ
    [2011-11-04 22:28:25 - dealkart]    -d  one or more device assets to include, separated by commas
    [2011-11-04 22:28:25 - dealkart]    -f  force overwrite of existing files
    [2011-11-04 22:28:25 - dealkart]    -g  specify a pixel tolerance to force images to grayscale, default 0
    [2011-11-04 22:28:25 - dealkart]    -j  specify a jar or zip file containing classes to include
    [2011-11-04 22:28:25 - dealkart]    -k  junk path of file(s) added
    [2011-11-04 22:28:25 - dealkart]    -m  make package directories under location specified by -J
    [2011-11-04 22:28:25 - dealkart]    -u  update existing packages (add new, replace older, remove deleted files)
    [2011-11-04 22:28:25 - dealkart]    -v  verbose output
    [2011-11-04 22:28:25 - dealkart]    -x  create extending (non-application) resource IDs
    [2011-11-04 22:28:25 - dealkart]    -z  require localization of resource attributes marked with
    [2011-11-04 22:28:25 - dealkart]        localization="suggested"
    [2011-11-04 22:28:25 - dealkart]    -A  additional directory in which to find raw asset files
    [2011-11-04 22:28:25 - dealkart]    -G  A file to output proguard options into.
    [2011-11-04 22:28:25 - dealkart]    -F  specify the apk file to output
    [2011-11-04 22:28:25 - dealkart]    -I  add an existing package to base include set
    [2011-11-04 22:28:25 - dealkart]    -J  specify where to output R.java resource constant definitions
    [2011-11-04 22:28:25 - dealkart]    -M  specify full path to AndroidManifest.xml to include in zip
    [2011-11-04 22:28:25 - dealkart]    -P  specify where to output public resource definitions
    [2011-11-04 22:28:25 - dealkart]    -S  directory in which to find resources.  Multiple directories will be scanned
    [2011-11-04 22:28:25 - dealkart]        and the first match found (left to right) will take precedence.
    [2011-11-04 22:28:25 - dealkart]    -0  specifies an additional extension for which such files will not
    [2011-11-04 22:28:25 - dealkart]        be stored compressed in the .apk.  An empty string means to not
    [2011-11-04 22:28:25 - dealkart]        compress any files at all.
    [2011-11-04 22:28:25 - dealkart]    --debug-mode
    [2011-11-04 22:28:25 - dealkart]        inserts android:debuggable="true" in to the application node of the
    [2011-11-04 22:28:25 - dealkart]        manifest, making the application debuggable even on production devices.
    [2011-11-04 22:28:25 - dealkart]    --min-sdk-version
    [2011-11-04 22:28:25 - dealkart]        inserts android:minSdkVersion in to manifest.  If the version is 7 or
    [2011-11-04 22:28:25 - dealkart]        higher, the default encoding for resources will be in UTF-8.
    [2011-11-04 22:28:25 - dealkart]    --target-sdk-version
    [2011-11-04 22:28:25 - dealkart]        inserts android:targetSdkVersion in to manifest.
    [2011-11-04 22:28:25 - dealkart]    --max-res-version
    [2011-11-04 22:28:25 - dealkart]        ignores versioned resource directories above the given value.
    [2011-11-04 22:28:25 - dealkart]    --values
    [2011-11-04 22:28:25 - dealkart]        when used with "dump resources" also includes resource values.
    [2011-11-04 22:28:25 - dealkart]    --version-code
    [2011-11-04 22:28:25 - dealkart]        inserts android:versionCode in to manifest.
    [2011-11-04 22:28:25 - dealkart]    --version-name
    [2011-11-04 22:28:25 - dealkart]        inserts android:versionName in to manifest.
    [2011-11-04 22:28:25 - dealkart]    --custom-package
    [2011-11-04 22:28:25 - dealkart]        generates R.java into a different package.
    [2011-11-04 22:28:25 - dealkart]    --auto-add-overlay
    [2011-11-04 22:28:25 - dealkart]        Automatically add resources that are only in overlays.
    [2011-11-04 22:28:25 - dealkart]    --rename-manifest-package
    [2011-11-04 22:28:25 - dealkart]        Rewrite the manifest so that its package name is the package name
    [2011-11-04 22:28:25 - dealkart]        given here.  Relative class names (for example .Foo) will be
    [2011-11-04 22:28:25 - dealkart]        changed to absolute names with the old package so that the code
    [2011-11-04 22:28:25 - dealkart]        does not need to change.
    [2011-11-04 22:28:25 - dealkart]    --rename-instrumentation-target-package
    [2011-11-04 22:28:25 - dealkart]        Rewrite the manifest so that all of its instrumentation
    [2011-11-04 22:28:25 - dealkart]        components target the given package.  Useful when used in
    [2011-11-04 22:28:25 - dealkart]        conjunction with --rename-manifest-package to fix tests against
    [2011-11-04 22:28:25 - dealkart]        a package that has been renamed.
    [2011-11-04 22:28:25 - dealkart]    --product
    [2011-11-04 22:28:25 - dealkart]        Specifies which variant to choose for strings that have
    [2011-11-04 22:28:25 - dealkart]        product variants
    [2011-11-04 22:28:25 - dealkart]    --utf16
    [2011-11-04 22:28:25 - dealkart]        changes default encoding for resources to UTF-16.  Only useful when API
    [2011-11-04 22:28:25 - dealkart]        level is set to 7 or higher where the default encoding is UTF-8.
    [2011-11-04 22:28:25 - dealkart]    --non-constant-id
    [2011-11-04 22:28:25 - dealkart]        Make the resources ID non constant. This is required to make an R java class
    [2011-11-04 22:28:25 - dealkart]        that does not contain the final value but is used to make reusable compiled
    [2011-11-04 22:28:25 - dealkart]        libraries that need to access resources.

Tried with many other alternate questions posted over internet but unable to find the solution for it.Tried several other duplicate looking questions over stackoverflow like After update ADV getting error "Unknown option '--no-crunch'" when try to run or Error while creating new project in Android or Android - ERROR: Unknown option '--no-crunch' or . Any other way i could approach its solution ?? Updated SDK, ADB and Developer Tools. Everything is up to date as it is a fresh install.

A:

This happens when you have a version mismatch between your Android Eclipse Plugin and the platform-tools on your system. The --nocrunch option was added in the most recent release. I know you said everything is up to date, but it doesn't look like that's the case. Run the SDK manager and check the Available Packages. Make sure you have both the Android SDK Tools, Revision 15 and the Android SDK Platform-tools, revision 9


Q:

how to run python script from php on xamp?

Following is the php code that I was using. I am trying to run this script(residing in the same directory as the php file is in) and want to display the output of the script on webpage. Script is working fine through command prompt, but not working thru php script.

<title>py script</title>

hey there!

<?
$pyscript = 'C:\\xampp_new\\htdocs\\projectx\\USR.py';
$python = 'C:\\Python27\\python.exe';
exec("$python $pyscript ", $output, $return );
echo $return;
?>

A:

<title>py script</title>

hey there!

<?
$pyscript = 'C:/xampp_new/htdocs/projectx/USR.py';
$python = 'C:/Python27/python.exe';
$command=escapeshellcmd('C:/xampp_new/htdocs/projects/USR.py');
$output=shell_exec($command);
echo $output;
?>


Q:

Cannot use registerReceiver in BroadcastReceiver

I cannot use registerReceiver in BroadcastReceiver. I read that I cannot do that then how should I confirm that my SMS has been sent?
BroadCastReceiver
public class MyReceiver extends BroadcastReceiver {
    String SENT="sent";
    String DELIVERED="delivered";
    public final String tag="com.example.pritesh.smstimer";
    public MyReceiver() {

    }

    //@Override
    public void onReceive(Context context, Intent intent) {

            Log.i(tag,"Sending");
            final NotificationManager notificationManager=  (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);

            Intent intent1=new Intent(context,Time_Picker.class);

            PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent1,0);
        //Notification for sent msg
        final Notification.Builder notification_sent=new Notification.Builder(context)
                    .setContentTitle("SMS SENT")
                    .setContentText("Your SMS has Been Sent")
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.drawable.favicon);
        //Notification for msg not sent
        final Notification.Builder notification_notsent=new Notification.Builder(context)
                .setContentTitle("SMS SENT")
                .setContentText("Your SMS was not sent due to no network service")
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.favicon);
        //Intent for sending confirmation

        Intent sent=new Intent(SENT);
        //PendingIntent for sending confirmation

        PendingIntent sentIntent=PendingIntent.getBroadcast(context,0,sent,PendingIntent.FLAG_UPDATE_CURRENT);
        //Receiver for sent confirmation

        Intent deliveryIntent = new Intent(DELIVERED);

        PendingIntent deliverPI = PendingIntent.getBroadcast(
                context, 0, deliveryIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String result = "";

                switch (getResultCode()) {

                    case Activity.RESULT_OK:
                        result = "Transmission successful";
                        notificationManager.notify(0,notification_sent.build());
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        result = "No service";
                        notificationManager.notify(0,notification_notsent.build());
                        break;
                }
            }
        },new IntentFilter(SENT));

        context.registerReceiver(new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "Deliverd",
                        Toast.LENGTH_LONG).show();
            }

        }, new IntentFilter(DELIVERED));

            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(Time_Picker.Phone,null, Time_Picker.Message, sentIntent
                    ,deliverPI);

            Toast.makeText(context, "Sms Sent", Toast.LENGTH_LONG).show();

    }
}

How should I send the sentIntent   to confirm whether sms sent or not
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pritesh.smstimer" >

    <uses-permission android:name="android.permission.SEND_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/favicon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Time_Picker"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:excludeFromRecents="true"
            android:exported="true"
            android:launchMode="singleTask"
            android:taskAffinity="" />
        <receiver
            android:name=".NotificationReciever"
            android:enabled="true"
            android:exported="true" >
        </receiver>
    </application>

</manifest>

A:

You cannot register dynamic BroadcastReceivers inside of another BroadcastReceiver. This is because the system enforces that a BroadcastReceiver finishes it's work within a short period of time (I think it's either 5 or 10 seconds).
You can create another BroadcastReceiver that is registered in your AndroidManifest. The <intent-filter> should include <action> elements that match the custom action strings you use in your code.


Q:

How to add a button with Tooltip, Transparent background and Glyph from code?

In XAML, you can add a button like this:
<Button Height="Auto" Width="Auto" Background="Transparent" ToolTipServie.ToolTip="Tooltip here" ToolTipService.Placement="Bottom" />

However I cannot achieve similar approach with C#. Assume I have a Stackpanel named "toolbar":
toolbar.Children.Add(new Button {
    Name = "undo",
    FontFamily = new FontFamily("Segoe MDL2 Assets"),
    Content = "&#xE10E",
    Opacity = 100,
});

When I debug the code, it adds a button with squares, gray background. Also  I don't know how to add a tooltip to the button.
I tried searching for help, nothing helped. :(
Any help is much appreciated. Thanks.

A:

The tooltip isn't a normal DP, it's an attached property via the ToolTipService class, so you need to add it as such:
var button = new Button
        {
            Name = "undo",
            FontFamily = new FontFamily("Segoe MDL2 Assets"),
            Content = "&#xE10E",
            Opacity = 100,
        };

ToolTipService.SetToolTip(button, "Tooltip here");
ToolTipService.SetPlacement(button, PlacementMode.Bottom);
toolbar.Children.Add(button);


Q:

Will the page lock be released on committing nested transaction?

It is well known that the database locks taken inside the transaction are released on the end of that transaction. So, in this code..
public static TransactionScope CreateTransactionScope()
{
    return new TransactionScope(TransactionScopeOption.Required,
     new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted });
}

Actually, in this one...
using (DataContext dataContext = new DataContext())
using (TransactionScope rootScope = CreateTransactionScope())
{
    using (TransactionScope nested = CreateTransactionScope())
    {
        Ticket ticket = dataContext.ExecuteQuery<Ticket>(
          "SELECT * FROM Tickets WITH (UPDLOCK) WHERE id={0}", ticketId).First();
        nested.Complete();
    }

    // Will the lock be still ON here? Because I don't need him to be!
}

When exactly the row/page lock (UPDLOCK) will be released - after the disposing the nested transaction or the root one?

A:

It will be released only after the root scope will exit the using block and will dispose.
The best way to learn this kind of stuff is by getting your hands dirty.
Create a simple database with table A and table B, each contains single column, name it "TimeStamp" and create simple console application that inserting timestamp (or any kind of value) and you can play with the transaction options and learn the behaviour.


Q:

Knowing the current Revision of a file or the project/solution for AnkhSVN

How can I view the current revision number of a particular file from Visual Studio or directly from Explorer under SVN Source control? I am using AnkhSVN as the client.
Also, is it possible to know the revision number when the project/solution was last updated from server and changes to some of its files have been made thereafter?

A:

use the string $Rev$ in your source file, e.g.
string revision = "$Rev$".Replace("$", "");

in solution explorer right click on that source file and select Subversion/Subversion properties
Add Property svn:keywords and enable "Rev".

Voilà: on every commit "$Rev$" is replaced with the new svn revision.

A:

You should install TortoiseSVN to have the integration of SVN in Explorer (File explorer i assume?).


Q:

Why do I suddenly need to declare a variable as "final" when adding an ActionListener to a button?

Possible Duplicate:
Why are only final variables accessible in anonymous class?

This is the code I have for a "random math game" I'm creating for class:
package RandomMathGame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class RandomMathGame {

    public static void main(String[] args) {
        RandomProblemGenerator randomProblems = new RandomProblemGenerator(10);
        final int numberProblems = 10;
        int correctScore = 0;
        JPanel panel = new JPanel();
       int answer;
        int correctAnswer;
        JLabel[] mathProblems = new JLabel[numberProblems];
        final JTextField[] mathAnswers = new JTextField[numberProblems];
        JLabel[] correctYesNo = new JLabel[numberProblems];
        final JLabel score = new JLabel(correctScore + "/10");
        JButton submit = new JButton("Submit");
        for (int i = 1; i <= numberProblems; i++)
        {
            final int X = randomProblems.createNumberX();
            final int Y = randomProblems.createNumberY();

            mathProblems[i] = new JLabel("" + X + " * " + Y + " = ");
            mathAnswers[i] = new JTextField();

             answer = Integer.parseInt(mathAnswers[i].getText());
             correctAnswer = X * Y;

            if (answer == correctAnswer)
            {
                correctYesNo[i] = new JLabel("Correct answer; good job!");
                correctScore = correctScore + 1;
            }
            else
            {
               correctYesNo[i] = new JLabel("Incorrect answer; try again!");

            }
             panel.add(mathProblems[i]);
             panel.add(mathAnswers[i]);
             panel.add(correctYesNo[i]);
            }
      submit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                score.setText("Score: " + correctScore + "/10");
            }
        });

        panel.add(submit);
        panel.add(score);

        JFrame gameFrame = new JFrame();
        gameFrame.setTitle("Random Math Game");
        gameFrame.setSize(150, 150);
        gameFrame.setVisible(true);
        gameFrame.setContentPane(panel);

        }
  }

I'm getting an error that the correctScore variable has to be declared as final before it can be used by the ActionListener. But when I set correctScore as a final, it causes all kinds of other errors. Can anybody think of a way to resolve this?

A:

To pass a local variable to an anonymous class, it has to be final - that is part of the Java language. Now when a primitive variable is final, you can't modify it, hence the issues you get when making correctScore final.
A workaround is to use a temporary variable right before the addActionListener call:
final int temp = correctScore;

and use that temp variable in your actionPerformed method.
Note that when you do that, any future changes to correctScore will not be reflected in the value of temp.


Q:

Why can't a 9 vertex graph whose complement is in 3 components be planar?

Let $G$ be a graph with 9 vertices whose complement, $\overline{G}$, has three components.
I've read that it can't be planar, but am having trouble completing a proof.
Most ways of distributing the 9 vertices among the 3 components of $\overline{G}$ would force $G$ to be non-planar, it is clear to me. For example, if 6 vertices were in one component, 2 in another and 1 in the last, then in $G$ any 3 vertices from that 6-vertex component would be completely connected to the vertices from the other 2 components, i.e. $K_{3,3}$ would be a subgraph of $G$, so $G$ would be non-planar.
This argument works when the largest component has 5 vertices, 4 vertices, or even 3 vertices.
That leaves one case: when 7 vertices are connected into a component in $\overline{G}$ and the other 2 vertices are isolated points. Why must $G$ be non-planar in this case?

A:

In fact, the statement is wrong: $G$ can be planar.
Assume that the component of size 7 in $\overline{G}$ is the clique; then $G$ is the tripartite graph $K_{1,1,7}$, which is planar:


Q:

Dev SP 2013 server is filled with 6481 and 6398 errors

The dev server is filled with errors 6398:

The Execute method of job definition
  Microsoft.Office.Server.Search.Administration.CustomDictionaryDeploymentJobDefinition
  (ID 339e26fd-56be-4f9e-b9bc-50c32d42b9ee) threw an exception. More
  information is included below.
Retrieving the COM class factory for component with CLSID
  {0FF1CE15-0005-0000-0000-000000000000} failed due to the following
  error: 80070422 The service cannot be started, either because it is
  disabled or because it has no enabled devices associated with it.
  (Exception from HRESULT: 0x80070422).

And 6481 :

Application Server job failed for service instance
  Microsoft.Office.Server.Search.Administration.SearchServiceInstance
  (f9677bce-935a-4d4f-97b4-8c7c32672676).
Reason: Retrieving the COM class factory for component with CLSID
  {0FF1CE15-0005-0000-0000-000000000000} failed due to the following
  error: 80070422 The service cannot be started, either because it is
  disabled or because it has no enabled devices associated with it.
  (Exception from HRESULT: 0x80070422).
Technical Support Details: System.Runtime.InteropServices.COMException
  (0x80070422): Retrieving the COM class factory for component with
  CLSID {0FF1CE15-0005-0000-0000-000000000000} failed due to the
  following error: 80070422 The service cannot be started, either
  because it is disabled or because it has no enabled devices associated
  with it. (Exception from HRESULT: 0x80070422).    at
  Microsoft.Office.Server.Search.Administration.Gatherer.get_AdminObject()
  at
  Microsoft.Office.Server.Search.Administration.Gatherer.ProvisionGlobalProperties()
  at
  Microsoft.Office.Server.Search.Administration.SearchServiceInstance.Synchronize()
  at
  Microsoft.Office.Server.Administration.ApplicationServerJob.ProvisionLocalSharedServiceInstances(Boolean
  isAdministrationServiceJob)

Could anyone point me to the correct direction. We don't care for search services(yet)

A:

Looks like it is permission problem on the Osearch in DCOM.

Open Start Menu > Administrative Tools > Component Services Tool
Drill Down and Expand DCOM Config
Navigate to the OSearch15,Right Click Properties
Select the Security Tab
Add the Network Service Account to Local and Activation Permissions
Add the Network Service Account to Access Permissions
Restart the Office SharePoint Server Search Service

I hope this will fix the problem.


Q:

Can we ask postgres to use caching for specific tables?

Can we ask postgres to use caching for specific tables and don't use it for few tables at all?

A:

No, you cannot control what is going to be cached.
But if that is a frequently accessed table, it will be cached anyway. If it's not accessed frequently it will not be cached.
So I don't see a reason for trying to control this.

A:

In order to read data and operate on it, PostgreSQL has to bring it into its cache.  And doing that will also put it temporarily in the operating system cache, too.  You can find an exact description of how that data will eventually be evicted from the database's cache once processes stop using it in my Inside the PostgreSQL Buffer Cache talk.
You can get faster eviction from cache by reducing the size of the shared_buffers parameter, which may have performance downsides.  PostgreSQL always reads using the OS cache, and you can't keep that from being polluted when you access large amounts of data.
There is an optimization for sequential scans that keeps the database's own shared_buffers cache from being taken over by that data.  Tables that are larger than (shared_buffers / 4) are limited to only using a small amount of memory on the database's side.  Those will still hammer the operating system cache though, but those tend to hold onto infrequently used data for less time than the database will.


Q:

Data loss after repair

Our repair jobs failed for a long period (> 14 days).
Today i manually started an repair job with nodetool repair -pr. Afterwards it looks like we lost some data from a table.
Question:
Is it theoretically possible to lose data after a repair job?
If yes what can be done to avoid this?

A:

You should not lose data with repair. If anything, you could gain back records that were deleted (resurrected zombie records).
One scenario where data might appear to be "lost" is if you have a missing tombstone cell copied from an alternate node during repair. That would be a correct value, not a lost value. If your client CL was something small, say, 1, and you're on the node with the data (but missing the tombstone), you might think that all-of-the-sudden you lost the cell, but again, that's the correct value.
Another scenario where things might appear to be "lost" is if the nodes time/clocks ever got out of sync and on your cluster where certain cells have incorrect time/date values causing things to get potentially messed up when repair tries to sync things up.
That's all I can think of off the top of my head.
-Jim


Q:

angular code is not working properly

This div tag i have written in my index.html file from there so can display details.

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="true">
                                Toggle navigation

                            </button>

Venue Details

Batch Details

Student Details

Trainer Details

This is my dashboard.html file which is coming when ui-view is called in index.html page but I want to display different html pages when click on link as shown in this code. Html detail should come in the place where I have commented the div tag with ui-view.

angular.module("activeCubs", ["signUp","login","dashboard","venueGet", "editVenue", "myListApp", "studentApp", "batchApp", "trainerDet", "ui.router", "xeditable", "ngDialog"])
       .config(function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise("/login");
        $stateProvider

            .state("signUp",{
            url:"/register",
            templateUrl: "forms/signup.html",
            controller:"myCtrl"
            })
            .state("login",{
                   url:"/login",
                   templateUrl:"forms/login.html",
                   controller:"loginCtrl"
                   })
            .state("dashboard", {
            url:"/dashboard/:token",
            templateUrl:"dashboard.html",
            controller:"dashboard"
        })

            .state("venueList", {
                url: "/venueList",
                templateUrl: "venue/venueDetailsListView.html",
                controller: "venueGetCtrl"
            })
            .state("venueDetails", {
                url: "/venueDetails",
                templateUrl: "venue/venueDetails.html",
                controller: "venueDetailCtrl"
            })
            .state("editVenueDetails", {
                url: "/editVenueDetails",
                templateUrl: "venue/venueDetailsEdit.html",
                controller: "editCtrl"
            })
            .state("batchList", {
                url: "/batchList",
                templateUrl: "batch/batchlist.html",
                controller: "myListCtrl"
            })
            .state("batchDetails", {
                url: "/batchDetails",
                templateUrl: "batch/batchdetails.html",
                controller: "batchCtrl"
            })
            .state("studentDetails", {
                url: "/studentDetails",
                templateUrl: "student/stdtwo.html",
                controller: ""
            })
            .state("studentData", {
                url: "/studentData",
                templateUrl: "student/stdone.html",
                controller: ""
            })
            .state("trainerDetails", {
                url: "/trainerDetails",
                templateUrl: "trainer/trainerDetails.html",
                controller: "trainerCtrl"
            })
            .state("index", {
                url: "/index",
                templateUrl: "index.html",
                controller: ""
            })
            .state("editTrainer", {
                url: "/editTrainer",
                templateUrl: "trainer/traineredit.html",
                controller: "trainerCtrl"
            })
    });

This my app.js file .

A:

I think you have one div extra which is not opened..Please check you have 5 open div But 6 close div.Hope this help.


Q:

Set Specific Bit in Byte Array

I want to know how to set a specific bit in a 16 byte array (128 bits).
For example ... if I wanted to set the 9th bit in the the array I would expect:
{00, 80, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00}
If I wanted to set the 125th bit ...
{00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 08}
I have looked into using bit shifting but got confused on how to bit shift with an array consisting of 128 bits. Is there a way to break down an array this size and evaluate in smaller chunks of bytes? Any help would be appreciated.

A:

The process of selecting a specific bit consists of two steps:

Picking the byte, and then
Picking the bit.

Picking the byte is simple: all you need to do is dividing the bit index by the number of bits in a byte - i.e. dividing by eight:
int byteIndex = bitIndex / 8;

Now that you know what byte to use, calculate which bit you want to access. For that you need to compute a remainder of a division by eight, like this:
int bitInByteIndex = bitIndex % 8;

With these two indexes in hand, it is easy to access the bit: use 1 << bitInByteIndex as a mask, like this:
byte mask = (byte)(1 << bitInByteIndex);
bool isSet = (bytes[byteIndex] & mask) != 0;
// set to 1
bytes[byteIndex] |= mask;
// Set to zero
bytes[byteIndex] &= ~mask;
// Toggle
bytes[byteIndex] ^= mask;

A:

You could use a BitArray:
byte[] bytearray = new byte[16];

var bitArray = new BitArray(bytearray);

bitArray.Set(8, true);

bitArray.CopyTo(bytearray, 0);

A:

Directly from a Byte Array, your quickest solution is probably using a BitArray.
 - http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx
E.g. This would go something like:
public void BitManimulation()
{
    //Ill just use 2 bytes here for demonstration, get your 16 bytes here.
    byte[] bytes = new[] { (byte)250, (byte)250 };

    //Convert your bytes to a BitArray.
    BitArray array = new BitArray(bytes);
    array[3] = !array[3]; // Flip
    array[4] = false; // 0
    array[5] = true; // 1

    //Convert back to bytes.
    byte[] bytes2 = new byte[2];
    array.CopyTo(bytes2,0);

    Console.WriteLine(bytes2[0]);
    Console.WriteLine(bytes2[1]);
}

Now this comes with a performance penalty.
So as an alternative you have the BitVector32 that will require you to convert blocks of 4 bytes to an integer...
 - http://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32.aspx
Finally you can do bit shifting, XOR's etc to produce the desired results. Since @dasblinkenlight already left a nice answer for that ill just leave you with that for explaining things.^
Here is some quick helper methods based on his post though:
public static class ByteArrayExt
{
    public static byte[] SetBit(this byte[] self, int index, bool value)
    {
        int byteIndex = index / 8;
        int bitIndex = index % 8;
        byte mask = (byte)(1 << bitIndex);

        self[byteIndex] = (byte)(value ? (self[byteIndex] | mask) : (self[byteIndex] & ~mask));
        return self;
    }

    public static byte[] ToggleBit(this byte[] self, int index)
    {
        int byteIndex = index / 8;
        int bitIndex = index % 8;
        byte mask = (byte)(1 << bitIndex);

        self[byteIndex] ^= mask;
        return self;
    }

    public static bool GetBit(this byte[] self, int index)
    {
        int byteIndex = index / 8;
        int bitIndex = index % 8;
        byte mask = (byte)(1 << bitIndex);

        return (self[byteIndex] & mask) != 0;
    }
}


Q:

Перегрузка "=" для контейнера STL

Нужно перегрузить оператор "="  (присваивания для следующих типов данных)
enum Suit { clubs, diamonds, hearts, spades };

vector< Suit > CardSuit[];

Suit su = Suit(1);
CardSuit[0] = su; <-  чтобы работало так????

A:

vector<Suit> CardSuit[];

Это что-то странное - вы объявляете CardSuit как массив векторов, так что CardSuit[0] - это вектор, а вы присваиваете ему отдельный элемент.
Чтобы работало так, как вы хотите - нужно сделать CardSuit вектором с уже выделенным как минимум нулевым элементом, типа
vector<Suit> CardSuit(1);

Или, что разумнее -
vector<Suit> CardSuit;

и добавлять
CardSuit.push_back(su);


Q:

What is a deleted function, and why only my functions that I pass files into are considered deleted?

#include <bits/stdc++.h>
using namespace std;

class contact {
private:
    vector< pair<string, int> > contact_info;
public:
    void add_contact(string contact_name, int contact_number) {
        contact_info.push_back(make_pair(contact_name, contact_number));
        sort(contact_info.begin(),contact_info.end());
    }
    void edit_contact(string contact_name) {
        int found_at;
        for (unsigned int i =0; i < contact_info.size(); i++) {
            if (contact_info[i].first == contact_name) {
                found_at = i;
            }
    }
    if (contact_info[found_at +1].first == contact_name) {
        int choice;
        int counter = found_at;
        int index = 1;
        while (contact_info[counter].first == contact_name) {
            cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
            counter++;
            index++;
        }
        cout << "Choose any please: ";
        cin >> choice;
        found_at = found_at - (choice - 1);
    }
    cout << "Enter the new number: ";
    cin >> contact_info[found_at].second;
}
void show_all() {
    for (unsigned int i =0; i < contact_info.size(); i++) {
        cout << contact_info[i].first << " " << contact_info[i].second << endl;
    }
}
void delete_contact(string contact_name) {
    int found_at;
    for (unsigned int i =0; i < contact_info.size(); i++) {
        if (contact_info[i].first == contact_name) {
            found_at = i;
        }
    }
    if (contact_info[found_at +1].first == contact_name) {
        int choice;
        int counter = found_at;
        int index = 1;
        while (contact_info[counter].first == contact_name) {
            cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
            counter++;
            index++;
        }
        cout << "Choose any please: ";
        cin >> choice;
        found_at = found_at - (choice - 1);
    }
    contact_info.erase(contact_info.begin()+found_at);
}
void writeFile(ofstream contact_file) {
    for (unsigned int i =0; i < contact_info.size(); i++) {
        contact_file << contact_info[i].first << " " << contact_info[i].second << endl;
    }

}
void readFile(ifstream contact_file) {
    string input;
    while (!contact_file.eof()) {
    contact_file >> input;
    size_t pos = input.find(" ");
    string name = input.substr(0,pos);
    string number_str = input.substr(pos);
    int number = stoi(number_str) ;
    contact_info.push_back(make_pair(name,number));
    }
}

};

int main()
{
    int choice;
    ifstream contacts_file_read;
    contacts_file_read.open("contacts.txt");
    ofstream contacts_file_write;
    contacts_file_write.open("contacts.txt");
    bool in_prog = true;
    contact contacts;
    string name;
    int number;
    while (in_prog) {
    cout << "1. Add contacts" << endl
        << "2. Edit contact" << endl
        << "3. Delete contact" << endl
        << "4. Show all" << endl
        << "5. exit" << endl;
   cout << "Your choice: ";
    cin >> choice;
    contacts.readFile(contacts_file_read);
    if (choice == 1) {
        cout << "Enter name & number separated by a space: ";
        cin >> name >> number;
        contacts.add_contact(name, number);
    } else if (choice == 2) {
       cout << "Enter name of contacts to be edited: ";
       cin >> name;
       contacts.edit_contact(name);
   }  else if (choice == 3) {
    cout << "Enter name of contact to be deleted: ";
    cin >> name;
    contacts.delete_contact(name);
} else if (choice == 4) {
    contacts.show_all();
} else if(choice == 5) {
    contacts.writeFile(contacts_file_write);
} else {
    cout << "Wrong choice" << endl;
}
}

return 0;
}

So, I was asked in my programming class to make a phone book application in C++ using only objects, so this is my attempt at it.
All functions are good, I did recompile the program after finishing each function at it gave me 0 errors, however whenever I try to call writeFile or readFile function that were previously working fine, now the compiler gave me an error of "error: use of deleted functions... "
I don't know what are deleted functions and why only functions that take file objects as an argument are treated as such.
Can anyone please help?
Thanks.

A:

Objects of type std::ifstream are not copyable -- indeed, the object represents the unique handle of an open file, and it would be difficult to conceptualize what it would mean to copy such unique responsibility.
Indeed, this inability to copy an object is encoded by making the copy constructor deleted, which causes the error that you see when you do attempt to copy it.
Your code should pass the original ifstream, not a copy (by taking a reference parameter):
void readFile(ifstream & contact_file)
//            ^^^^^^^^^^


Q:

Alamofire 4 multipart request upload progress

How should I track progress of my multipart upload request using Alamofire 4?
My encodingCompletion handler:
encodingCompletion: {
        encodingResult in
        switch encodingResult {
        case .success(let uploadRequest, _, _):
            uploadRequest.uploadProgress {
                p in
                print(p.completedUnitCount, p.totalUnitCount)
            }
            break
        case .failure( _):
            print("Failed to encode upload")
        }
}

The error I get says:

Cannot call value of not-function type 'Progress'

A:

Try this:
Alamofire.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(URL(string: "http://example.com/url1")!, withName: "one")
            multipartFormData.append(URL(string: "http://example.com/url2")!, withName: "two")
        },
        to: "http://example.com/to",
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                }
                upload.uploadProgress { progress in

                    print(progress.fractionCompleted)
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    )


Q:

DevExpress CustomRowFilter - how to trigger?

I'm very new to C# programming, so am hoping this is something simple that I'm overlooking.
I have a XtraGrid.GridControl on my form which I want to apply a CustomRowFilter against.
I am not explicitly defining any views for the grid, so I thought I'd be adding my CustomRowFilter method to an event handler against the MainView on my GridControl - however I can't find how to access the event I'm after?
Is this the right approach or am going about this the wrong way?
    private void gridControl1_CustomRowFilter(object sender, RowFilterEventArgs e)
    {
        GridView view = sender as GridView;
        DataView dv = view.DataSource as DataView;

        if (1==1) //Temp - this should hide everything
        {
            e.Visible = false;
            e.Handled = true;
        }
    }

private void Form1_Load(object sender, EventArgs e)
    {
        //Bind the datasource etc...

        gridControl1.MainView.CustomRowFilter += gridControl1_CustomRowFilter //"Base view does not contain a definition for "CustomRowFilter"
    }

A:

The CustomRowFilter event belongs to the GridView and not to GridControl, You can access the event with :
private void Form1_Load(object sender, EventArgs e)
{
    (gridControl1.MainView as GridView).CustomRowFilter += gridControl1_CustomRowFilter;
}


Q:

Proving $\sum^k_{n=0}\frac{(k-n)^k(-1)^n}{(k-n)!n!}=1$

Please look at the following relation.
$$\forall k \in \mathbb{N}, \ \ \ \ \ \sum^k_{n=0}\frac{(k-n)^k(-1)^n}{(k-n)!n!}=1$$
I don't know a proof of this relation.
I tried mathematical induction. But it didn't work.

A:

We will prove something stronger. Namely, that
$$f_k(x)=\sum_{n=0}^k\frac{(k+x-n)^k(-1)^n}{(k-n)!n!}=1$$
for any $x\in\mathbb{R}$. However, first we will provide a lemma that will be used later in the proof. That is that identity
$$\sum_{n=0}^k\binom{k}{n}n^j(-1)^n=0\text{ for }0\leq j<k$$
From here, an explicit formula for Stirling Numbers of the Second Kind is
$$S2(j,k)=\frac{1}{k!}\sum_{n=0}^k(-1)^{k-n}\binom{k}{n}n^j$$
Then
$$\sum_{n=0}^k\binom{k}{n}n^j(-1)^n=k!(-1)^kS2(j,k)$$
However, $S2(j,k)$ is defined as the number of ways to arrange $j$ elements into $k$ non-empty sets. The key here being non-empty. That is, if $j<k$ then it is impossible to arrange the $j$ elements into $k$ non-empty sets so $S2(j,k)=0$. That is, if $j<k$ then
$$\sum_{n=0}^k\binom{k}{n}n^j(-1)^n=0$$
Having proved our lemma, we continue onto the main proof. Now, consider the form of $f_k(x)$. Obviously, $f_k(x)$ is a polynomial. That is, it is an entire function. We are justified then in taking its Maclaurin Series. To this end, we need to calculate $f_k^{(m)}(0)$ for $m\geq 1$. Now, since $f_k(x)$ is of degree at most $k$, $f_k^{(m)}(0)=0$ for $m\geq k+1$. Consider the derivatives of $f_k(x)$:
$$f_k^{(0)}(x)=\sum_{n=0}^k\frac{(-1)^n (k-n+x)^k}{n! (k-n)!}$$
$$f_k^{(1)}(x)=\sum_{n=0}^k\frac{k (-1)^n (k-n+x)^{k-1}}{n! (k-n)!}$$
$$f_k^{(2)}(x)=\sum_{n=0}^k\frac{(k-1) k (-1)^n (k-n+x)^{k-2}}{n! (k-n)!}$$
$$\vdots$$
$$f_k^{(m)}(x)=\sum_{n=0}^k\frac{k! (-1)^n (k-n+x)^{k-m}}{n! (k-n)!(k-m)!}$$
for $0\leq m\leq k$. Thus,
$$f_k^{(m)}(0)=\sum_{n=0}^k\frac{k! (-1)^n (k-n)^{k-m}}{n! (k-n)!(k-m)!}$$
$$=\frac{1}{(k-m)!}\sum_{n=0}^k\frac{k! (-1)^n (k-n)^{k-m}}{n! (k-n)!}$$
Expanding $(k-n)^{k-m}$ in its Binomial Series gives us
$$=\frac{1}{(k-m)!}\sum_{n=0}^k\left[\binom{k}{n} \sum_{j=0}^{k-m}\binom{k-m}{j}k^{k-m-j}n^j(-1)^{n+j}\right]$$
Since these are finite sums, we can switch the order of summation to get
$$=\frac{1}{(k-m)!}\sum_{j=0}^{k-m}\left[ \binom{k-m}{j}k^{k-m-j}(-1)^n\sum_{n=0}^{k}\binom{k}{n}n^j(-1)^{j}\right]$$
But for $m\geq 1$, $j$ will always be less than $k$. This is precisely the lemma we proved above. Thus, for $m\geq 1$
$$=\frac{1}{(k-m)!}\sum_{j=0}^{k-m}\left[ \binom{k-m}{j}k^{k-m-j}(-1)^n\cdot 0\right]=0$$
and hence
$$f_k^{m}(0)=0$$
Since every coefficient in the Maclaurin Series except for the $m=0$ is zero, we conclude $f_k(x)$ is a constant function. That is
$$f_k(x)=a_k$$
where $a_k$ could change depending on $k$. We seek to show that $a_k=1$ for all $k$. In fact, this is easily done as we can simply calculate $f_k(0)$:
$$f_k(0)=\sum_{n=0}^k\frac{(k-n)^k(-1)^n}{(k-n)!n!}=a_k$$
(this is your original question). In fact, these terms can be rearrange to
$$a_k=\sum_{n=0}^k\frac{(k-n)^k(-1)^n}{(k-n)!n!}=\frac{1}{k!}\sum_{n=0}^k\frac{k!(k-n)^k(-1)^n}{(k-n)!n!}$$
$$k!a_k=\sum_{n=0}^k\binom{k}{n}(k-n)^k(-1)^n$$
However, as was pointed out by user @Angela_Richardson, this exact problem can be found here already. In the link provided, simply swap $n$ and $k$, and set $l=k$ to get
$$k!a_k=\sum_{n=0}^k\binom{k}{n}(k-n)^k(-1)^n=k!$$
$$a_k=1$$
Thus, your original question is answered in the affirmative as well as
$$f_k(x)=\sum_{n=0}^k\frac{(k+x-n)^k(-1)^n}{(k-n)!n!}=1$$
for all $x\in\mathbb{R}$.


Q:

Fredholm Integral Equations - Sturm-Lioville & Green Function Theory?

In an ODE's book one is given a 2nd order ode boundary value problem like
$$y'' + A(x)y' + B(x)y = f(x), y(a) = y_a, y(b) = y_b$$
and might be told to analyze it with a Green function or via Sturm-Liouville theory, and invoke all this orthogonal function theory. For example randomly converting an ode to S-L form.
It looks to me that GF & S-L theory very naturally arise when you convert the ode to a Fredholm integral equation, as in it looks so obvious these methods are the only thing to use. Further there are some Fredholm theorems that apparently justify what you're doing.
My question, is it 'correct' to view S-L (homogeneous) & GF (inhomogeneous) theory as actually being part of the theory of integral equations, not differential equations, and to view the Fredholm theorems as the real source of justification for things like Fourier, Legendre polynomials being orthogonal and complete, the spectral theorem being an integral equation theorem?
Thanks

A:

If you compare two operation: differentiation and integration, then the clear winner is the integration, you can integrate way more functions than differentiate (moreover, integration is a numerically stable operation, whereas numerical differentiation is an ill posed problem). On the other hand, what is easier to do in Calc, differentiate or integrate? Clearly, find derivatives requires no imagination if you know the rules. A similar thing happens when one talks about S-L problems and the theory behind it. It is easier to find actual eigenfunctions from the ODE, but way better to prove theorems for the integrals.
Here are some more details.
Sturm-Liouville operator $L$ is symmetric, but unbounded (because it involves differentiation). This means it is quite difficult to prove a lot of things directly for the Sturm-Liouville operator.
On the other hand, we know that if an operator on a separable Hilbert space is compact and self-adjoint, then the whole lot of nice things can be proved, most importantly the completeness of the list of eigenfunctions.
So, assume that zero is not an eigenvalue of $L$. Then there exists an inverse operator
$$
L^{-1}(f)(y)=\int_a^b f(y)g(x,y)dy,
$$
where $g$ is exactly the Green function, which can be explicitly constructed from the given S-L problem. It is not difficult to prove that, if $g$ is nice enough, the integral above is self-adjoint and compact operator. Hence, using the nice properties of integrals we can infer tons of useful stuff about S-L problems, which appear in applied problems in a natural way.


Q:

"Unexpected end of declaration" Android AIDE

I'm following this spinner_guide to add a spinner to my app. I have added the following to MainActivity.java:
Spinner key_spinner = (Spinner) findViewById(R.id.key_spinner);
ArrayAdapter<CharSequence> key_adapter =ArrayAdapter.createFromResource(this,R.array.spinner_keys,android.R.layout.simple_spinner_item);
key_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
key_spinner.setAdapter(key_adapter);

with spinner_keys a string array defined in strings.xml and key_spinner is a spinner in main.xml. I get an unexpected end of declaration error at the brackets of the last two functions (the brackets are underlined with a red squiggly line in AIDE). I have had this error in another app I am working on but cannot see the cause. I have searched for the error term but have not found it. I suspect it may be due to the argument to the function not being recognised(?), but I don't really know - this (and the other mentioned app) are my first attempt at Android (and Java) programming.
Any suggestions would be appreciated.

A:

Code like this should be in a method body such as onCreate() and not in class body. In a class body the first two lines are valid since they define and initialize member variables, while the latter two lines are not valid in such context.
So, wrap the code in
@Override
public void onCreate(Bundle b) {
    super.onCreate(b);

    setContentView(R.layout.your_layout_name);

    // that code here

 }


Q:

TLS client certificates : which attribute for authorization?

I am trying to setup a web service which uses x509 client certificates sent during the TLS handshake for authentication as well as to check whether the user has the auhorization to access the requested ressource.
The idea is that each user is givenan access level, and some ressources are only available to the higher levels. The certificate is then used to match the user to its level.
I have had no problem configuring Apache to verify the certificate against the root CA and to forward the certificate to the back-end application ( a python-based XML-RPC server).
However I am struggling to choose which attribute(s) of the certificate I should use to map the user to his level :

The Common Name field seems like a natural choice, but I am wondering how secure this solution would be as nothing prevents multiple intermediary CAs from providing certificates with the same CN
The Public Key itself is clearly more secure, but how practical is it to use ? Will it stay the same if the client has to renew his certificate after its expiry ? There is also the problem of storage and speed of comparison of a much larger string
The whole certificate itself or its thumprint thumbprint could be an alternative to the public key, but the client will not be able to connect if his certificate is renewed

I am currently leaning towards the public key, but is it the best choice in this situation ? Or is there a better option ?
Thanks in avance

A:

Typically authentication with client certificates is done by having some private CA which issuing the client certificates and only trusting the CA when validating the client certificates. In this case the trusted CA and only this CA has full control over the subject of the certificate which means that mapping the CN to users is perfectly fine and also commonly used.
If you instead for whatever reason want to allow certificates issued by arbitrary CA's then such simple mapping can not be done as you've realized yourself. In this case a mapping between certificate pubkey or certificate fingerprint might be done, which of course requires that it is known up-front which exact certificate to expect for a specific user. And, this mapping need to be somehow renewed whenever the client certificate needs to change because it was expired.


Q:

How to set user account password without knowing the old password in C?

I'm writing a C++ program to manage user accounts on Windows 7.
I would like to set the password for an existing user account.
I cannot use NetUserChangePassword (Netapi32.dll) since I don't record previous password that I set when creating the user.
So, the program must be able to just set a new password (without knowing the old password).
Is there a way to do that programmatically in c++?
Thank you for your help.

A:

Call NetUserSetInfo with the level parameter set to 1003.


Q:

How to implement the edge button pointer event?

I have seen this kind of button styling only in edge button and would like to know how to implement it. So there are two different effects into play(as far as I know). First that when buttons are pressed the content inside them shrinks (unlike default effect provided by Windows) and then second a dark non-discrete border appears inside the button when clicked to almost give a feel of depth in it.

A:

This question was a challenge!
My first idea was to use the UWP Community Toolkit DropShadowPanel to create a shadow and clip it to the button's rectangle. Unfortunately this didn't work well, as I would have to set the shadow on a Rectangle that would need to have a visible border, which is not really good for our purpose of having a nicely blended borderless button. In addition, the DropShadowPanel shadow just didn't give a strong enough shadow effect that would be enough for the button to look like in Edge.
I have used Visual Studio and attached it's debugger to the Edge browser to see which control does the browser actually use. The Live Tree Visualizer revealed this:

SpartanXAML.InnerShadowControl? Okay, we don't have that. Let's work around this.
I fired up Photoshop instead. Created a 64x64 square image, put a transparent rectangle layer on the surface and set its Inner Glow as shown in this screenshot:

After export, I got the following PNG:

That looks quite like the inner shadow on the Edge button!
Now let's create a custom button style that uses this image!
<Style TargetType="Button" x:Key="EdgeButtonStyle">
    <Setter Property="Background" Value="#f5f5f5" />
    <Setter Property="Foreground" Value="{ThemeResource ButtonForeground}" />
    <Setter Property="BorderBrush" Value="{ThemeResource ButtonBorderBrush}" />
    <Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}" />
    <Setter Property="Padding" Value="8" />
    <Setter Property="HorizontalAlignment" Value="Left" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" />
    <Setter Property="FontWeight" Value="Normal" />
    <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}" />
    <Setter Property="UseSystemFocusVisuals" Value="True" />
    <Setter Property="FocusVisualMargin" Value="-3" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid x:Name="RootGrid" Width="64" Height="64" Background="{TemplateBinding Background}">

                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">

                                <Storyboard>
                                    <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                                </Storyboard>
                            </VisualState>

                            <VisualState x:Name="PointerOver">

                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="#c1c1c0" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPointerOver}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>

                            <VisualState x:Name="Pressed">

                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="#c1c1c0" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPressed}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Scale" Storyboard.TargetProperty="ScaleX">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="0.8" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Scale" Storyboard.TargetProperty="ScaleY">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="0.8" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="InnerShadow" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="Visible" />
                                    </ObjectAnimationUsingKeyFrames>

                                </Storyboard>
                            </VisualState>

                            <VisualState x:Name="Disabled">

                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundDisabled}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundDisabled}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>

                    </VisualStateManager.VisualStateGroups>

                    <ContentPresenter x:Name="ContentPresenter"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}"
            Content="{TemplateBinding Content}"
            ContentTransitions="{TemplateBinding ContentTransitions}"
            ContentTemplate="{TemplateBinding ContentTemplate}"
            Padding="{TemplateBinding Padding}"
            HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
            VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
            AutomationProperties.AccessibilityView="Raw">
                        <interactivity:Interaction.Behaviors>
                            <behaviors:Scale x:Name="Scale"
                                    ScaleX="1"
                                    ScaleY="1"
                                    CenterX="32"
                                    CenterY="32"
                                    Duration="100"
                                    Delay="0"
                                    EasingType="Default"
                                    AutomaticallyStart="True"/>
                        </interactivity:Interaction.Behaviors>
                    </ContentPresenter>

                    <Image Source="/Assets/InnerShadowGray.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Visibility="Collapsed" x:Name="InnerShadow" />

                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

This is a lengthy listing so I will just point out the most interesting things:

Removed all borders from the button
Set background to #f5f5f5 and hover background to #c1c1c0 to match Edge
Set the width and height to 64
Added an Image as the last control in the RootGrid, this is the shadow image, is Collapsed by default and appears only when pointer is pressed
Used UWP Community Toolkit's (Microsoft.Toolkit.Uwp.UI.Controls NuGet package) Scale behavior to create a simple, easy to control animation. This required adding xmlns:interactivity="using:Microsoft.Xaml.Interactivity" and xmlns:behaviors="using:Microsoft.Toolkit.Uwp.UI.Animations.Behaviors" XML namespaces to the root element of the file
Replaced the default PointerDownThemeAnimation with a custom animation utilizing Scale behavior, to make the animation more significant and scale uniformly, without skewing the content

Now let's just take our new button for a test ride!
<Button Style="{StaticResource EdgeButtonStyle}" HorizontalAlignment="Center">
    <Image Source="Assets/Windows.png" />
</Button>

And the result:


Q:

Create View using Linked Server db in SQL Server

How can I create View on Linked Server db. For Example I have a linked server [1.2.3.4] on [5.6.7.8]. Both db servers are SQL Sserver 2005. I want to create View on [5.6.7.8] using table on linked server.
EDIT:
On creating using full name, [1.2.3.4].db.dbo.table, I am getting this error.
SQL Execution Error.
Executed SQL statement: SELECT * FROM  1.2.3.4.db.dbo.table (YOu can see brackets are not there.)
Error Source: .Net SqlClient Data Provider
Error Message: Incorrect syntax near '0.0'. ---> part of IP address.
I am just creating this in ManagementStudio, not using it because it is not created yet. I Have changed IP. In image you can see there are not brackets around IP but I given it and on error these brackets are removed.
Thanks.

A:

You need to use the four part qualified name: linkedserver.database.schema.table
SELECT * FROM [1.2.3.4].Northwind.dbo.Customers

Here is an MSDN article about accessing object names.
You might want to try manually creating the view, rather than using the SQL Management tools:
CREATE VIEW [dbo].[sywx]
AS
    SELECT  *
    FROM    [1.2.3.4].Atia.dbo.IpPbxDCR
GO

I also recommend that you use a name, if possible, for the linked server rather than using the IP address.

A:

Its a SQL Management Studio Issue.
If you try to create the view using management studio NEW VIEW then you get that error incorrect syntax.
But if you use SQL Query:
CREATE VIEW [dbo].[viewname]
AS
    SELECT  *
    FROM    [0.0.0.0].database.dbo.table
GO

then it will work.
To test you will see the view created when you refresh views.
If you just do a select query from the view you will see the view return results.
But if you try to go into design mode for that view and try executing the design query the error will pop up again even though the view was successfully created.


Q:

How to slice an image in gee into multiple images

I want to slice a big image into images with shape 256x256xchannels, one of my channels show the class of a pixel, which can be 0, 1 or 2. My goal with this slice is to throw out the images that only have pixels with the class 0, so that when I export those images I would spend less space in memory. How can I do that in the google earth engine?

A:

First, use image.updateMask(image.select('class').neq(0)) to mask off the pixels that have the class you don't want.
Then, use one of the two tiled export options:

Export.image with fileDimensions: 256 to ask for tiles rather than a single image, or
Export.map.toCloudStorage (which exports standard 256×256 web map tiles)

and specify the option skipEmptyTiles: true. This will result in not exporting any tiles which are fully masked off.


Q:

TreeView Drag & Drop help - _Invalid FORMATETC structure_ exception

I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:
Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))
The ItemDrag handler (where the exception takes place), looks like:
private void treeView_ItemDrag(object sender,
        System.Windows.Forms.ItemDragEventArgs e)
{

        this.DoDragDrop(e.Item, DragDropEffects.Move);
}

Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2)

A:

In case it helps anyone else - I encountered this problem with the WPF TreeView (not Windows Forms as listed in the question) and the solution was simply to make sure to mark the event as handled in the drop event handler.
    private void OnDrop(object sender, DragEventArgs e)
    {
        // Other logic...

        e.Handled = true;
    }