How to prevent concurrent call in Spring MVC

Question: Deal all, i am facing one problem in spring mvc. From one of our external system say payment gateway will call us [/getRespFromExternal] after their transaction completed, unfortunately they are calling us more than one time at time.
In the method getRespFromExternal, we are calling internal webservice to process payment acknowledgement, before WS call completed itself i get another duplicate call from external system. So i get payInd is null in payResponse method in controller. after first call [WS call] finished then /payResponse from controller is not even calling . Sorry for my english. Please advice me.
Service Method called by External System:
<code>@RequestMapping(value="/getRespFromExternal",method=RequestMethod.POST)
public String getRespFromExternal(HttpServletRequest httpRequest,HttpServletResponse httpResponse,HttpSession session){
    if (httpRequest != null && session.getAttribute("extRespId") == null) {
        session.setAttribute("extRespId", httpRequest.getParameter("tranID"));
        // internal web service call
        callInternalWS(); // to process payment
        before processing above WS method i get another call from external[/getRespFromExternal] for second time;
        session.setAttribute("payInd", "Y");

        return "redirect:/payResponse/";
    }
    return "redirect:/payResponse/";
}
</code>
Controller Method :
<code>@RequestMapping(value = "/payResponse/", method = RequestMethod.GET)
public ModelAndView payResponse(HttpServletRequest request, HttpSession session) {

    String payInd = (String) session.getAttribute("payInd");
    System.out.println("payInd --> "+payInd);
    if (payInd != null && payInd.trim().equalsIgnoreCase("Y") ) {

    }
}
</code>
Comment: Does it provide some sort of transaction ID?
Comment: Yes they are providing transaction is
Comment: @Chrylis any ideo or solution..
Comment: How can you detect the duplicate call in `/getRespFromExternal `? By `tranID`?
Comment: @zico.. yes getting 3 calls for same tran id..
Comment: @DEADEND you can use [ConcurrentHashMap](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html) to store `tran id` before process WS and remove the id whenever you completed the process. So that whenever same `tran id` comes between WS call + processing you can easily check if the `tran id` already send to WS or not.
Comment: Thank you @Zico.. If i use ConcurrentHashMap as instance variable then if i get multiple call at method /getRespFromExternal for same tran id, tran id is exist in that map during second because its instance variable right & another problem is second call ie duplicate call is not waiting for first call completion, it will redirect to response jsp before first call job completion. i used synchronization but all different tran is is waiting in queue.
Answer: If you are getting multiple calls to your service with the same transaction if, that should be treated as an error.
I assume that you are using a transactional database to record the payments.
If so, then you could make the transaction id a unique key in the database.  If the SQL insert or update to record the transaction fails due to a duplicate key, redirect to a different URL to report the error.


Optimization algorithms for sparse data

Question: For couple of weeks now I've been dealing with a classification problem involving a sparse dataset. To be more specific, for each input $x^{(i)}$, knowing that I have 1000 features, I've only 5 to 10 values of $k$ such as $x^{(i)}_{k} \not= 0$.
Up until now, I've tried stochastic gradient descent (SGD), momentum SGD, adagrad and adadelta. Adadelta seems to be performing the most; I think it's more down to the fact that there's no learning rate. For the previous optimizations algorithms, I struggled with the choice of $\alpha$ and I couldn't find one value that was giving good enough results for various training sets.
Anyway, this pushed me to wonder if there are specific optimization algorithms that are known to have good results with sparse data? What would you suggest? Also, I have to add that my data is unbalanced (positive class represents 8% of the dataset).
Comment: Optimization algorithms optimize *functions*, they are not directly applied to the data, so you need to tell us more about the actual function you are optimizing.
Comment: You need to specify that you're using concrete algorithm - there is no such mention in post.
Comment: I'm voting to close because the question is under-specified: optimization tasks are characterized by what **function** you're optimizing. Data sparsity may play a role in that **function**, but it is at best ancillary to the main task of optimization.
Comment: Naive Bayes, perhaps? It's known to work well with sparse data (the sklearn versions take sparse matrices, even), and is suitable for unbalanced datasets. YMMV.
Comment: Naive Bayes would be a learning model / classifier.
In my case, I've already chosen Factorization Machines as the model to work with and I'm more worried about the optimization algorithm to learn its parameters.
Answer: I'd suggest Lightning, because

inner loops in cython, fast for big sparse arrays
an AdaGrad
more like AdaM than
standard AdaGrad .

(By the way, it doesn't add a column of ones for intercepts;
do that yourself with
from sklearn.preprocessing.data import add_dummy_feature .)

Optimization algorithms for sparse data


Excluir pasta com permissão CHMOD777

Question: Crio uma pasta com o PHP assim
mkdir('/public_html/buscauiva/public_html/'.$_POST['Nome'].'', 0777);

Para excluir estou usando o rmdir() do PHP
dir='/var/www/casamentowagnerecamila.com.br/public_html/buscauiva/public_html/'.$row['nome'].'';

if(rmdir($dir))
{
echo 'Pasta deletada com sucesso.';
}
else
{
echo 'A pasta não pode ser deletada.';
}

Mais o PHP não consegue excluir a pasta retornando o erro:
 A pasta não pode ser deletada.
Como faço para excluir a pasta com o php ( contém arquivos dentro)?
Comment: quando cria a pasta você não precisa do caminho completo (`/var/www/casamentowagnerecamila.com.br`). Não pode remover isso na hora de excluir também?
Comment: sim eu fiz isso, mais retorna o erro A pasta não pode ser deletada
Comment: no `else`, imprime `error_get_last();` pra ver qual o erro real e coloca na pergunta, pode ser que ajude.
Comment: não retornou nenhum erro com o error_get_last();
Answer: Para apagar uma pasta, é necessário primeiro apagar os arquivos dentro dela. Você pode tentar dessa forma:
$dir='/var/www/casamentowagnerecamila.com.br/public_html/buscauiva/public_html/'.$row['nome'].'';

// Se a pasta não existir
if (!file_exists($dir)) {
    echo "Pasta não existe";
}

// Se não for uma pasta, exclui o arquivo
if (!is_dir($dir)) {
    unlink($dir);
}

// Verifica os arquivos dentro da pasta
foreach (scandir($dir) as $item) {
    unlink($item);
}

// Por fim, apaga a pasta
rmdir($dir);

De forma mais simplificada, você pode usar comandos do SO pra apagar a pasta, mas essa solução só funciona em LINUX (eu acho)
// chama o comando do SO
system('rm -rf ' . escapeshellarg($dir), $retorno);
// esse comando linux retorna 0 quando sucesso
if( $retorno == 0) echo "Excluido com sucesso";

Answer: Fui dar uma olhada no manual do PHP e vi que para deletar a pasta, "o diretório tem que estar vazio e as permissões relevantes autorizarem a esta operação".
No próprio manual tem um exemplo de como proceder; você precisa limpar o diretório e depois deletá-lo, você usaria assim:
public static function MeuMetodo()
{
  // ...
  dir='/var/www/casamentowagnerecamila.com.br/public_html/buscauiva/public_html/'.$row['nome'].'';

  if(DelTree($dir))
  {
    echo 'Pasta deletada com sucesso.';
  }
  else
  {
    echo 'A pasta não pode ser deletada.';
  }
}

public static function DelTree($dir) {
  files = array_diff(scandir($dir), array('.','..'));
  foreach ($files as $file) {
    (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
  }
  return rmdir($dir);
}

Comment: com esse código não abre a página, está faltando alguma coisa

Excluir pasta com permissão CHMOD777


Hierarchical logistic regression package in R

Question: I'm working on a logistic regression model; the purpose of the analysis is to identify factors that influence use of an app - the DV being use/no use, and IVs being a couple of numerical and categorical variables.
I want to do a hierarchical regression and add variables step-wise, and compare how much each variable improves the model.
At the moment I define multiple models, add a variable for each model, compare the models using an ANOVA and save and compare the (adjusted) R squares in a table:
<code>model1 <- glm(mh_use ~ Q7, data = results_mod, family = "binomial")
model2 <- glm(mh_use ~ Q7 + Q6_4_TEXT, data = results_mod, family = "binomial")
model3 <- glm(mh_use ~ Q7 + Q6_4_TEXT + Q66, data = results_mod, family = "binomial")
anova(model1, model2, model3, test= "Chisq")

rtbl <- matrix(nrow = 3, ncol = 2, byrow = TRUE)
rtbl[1,] <- c(rsq(model1), rsq(model1,adj=TRUE))
rtbl[2,] <- c(rsq(model2), rsq(model2,adj=TRUE))
rtbl[3,] <- c(rsq(model3), rsq(model3,adj=TRUE))
</code>
Rather than doing this manually, I was wondering if there is a package/function in R that does this for you and gives the relevant results? And is R squared the best comparison for logistic regression or should I include other measures?
Answer: OK, so:

I don't think this is hierarchical logistic regression.  The word "hierarchical" is sometimes used to refer to random/mixed effects models (because parameters sit in a hierarchichy).  This is just logistic regression.

R square is not a good way to compare logistic regression models.  It depends on what you're interested in studying, but a generalized r squared (like Nagelkerke's R squared) are better.

Is your goal here to infer some effect or are you trying to predict something?
Comment: thanks! the goal is inference, not predict.
Comment: OK, goal is inference.  What about the model is trying to be "improved"?  I'm assuming the generalized R squared?  More generally, I think something like AIC might be a good tool here (though I'm personally not a fan of AIC but that is another story).
Comment: The improvement is to evaluate how much additional variance is explained by adding each variable, so yes something like generalized R squared (or another suitable measure).
Comment: If this starts looking like stepwise regression beware.  And the data are seldom capable of telling you how important each predictor is.  That takes an enormous dataset.


Elixir Mocking: Assign a module to a module attribute

Question: For testing I want to make a mock, as described by José Valim here
But I keep getting a "CaseClauseError" error. I made a simple project here if interested.
When using Application.get_env to to bind a module to a module attribute, e.g.
defmodule Att do
  @file Application.get_env(:att, :file_module)

  def hello do
    file = Application.get_env(:att, :file_module)
    file.hello()
    # @file.hello
  end
end

It results in the following compile error:
mix compile
    == Compilation error in file lib/att.ex ==
** (CaseClauseError) no case clause matching: [{:file, Att.Real, false, 2}]
    lib/att.ex:5: (module)
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

If I comment out @file Application.get_env(:att, :file_module) there is no problem and the use of file = Application.get_env(:att, :file_module) in the hello function is fine.
The problem is not Application.get_env specific as if do the following
defmodule Att do
  # @file Application.get_env(:att, :file_module)
  @file_mock Att.Mock

  def hello do
    file = Application.get_env(:att, :file_module)
    file.hello()
    Att.Mock.hello()
    # @file.hello
  end
end

Then @file_mock Att.Mock results in the same CaseClauseError. The problem seems to be assigning a module to a module attribute.
Comment: Which line exactly throws that error? The problem is not assigning a module to a module attribute. You can definitely do that. The error message says line 17 but your code is only 8 lines.
Comment: Sorry, that might have been before deleting some lines, edited with new error msg. As you can see it is complaining of line 5 `def hello do`, but if I comment out line 2 `@file Application.get_env(:att, :file_module)` all is fine.
Answer: @file is a special module attribute which stores file name to use in stacktraces. If you instead assign it to another name, it should work fine.

@file
Changes the filename used in stacktraces for the function or macro
  that follows the attribute, such as:
defmodule MyModule do
  @doc "Hello world"
  @file "hello.ex"
  def hello do
    "world"
  end
end

Source
Comment: Good catch. I will improve the error message in this case. :)
Comment: Awesome that my baffle caught José attention, thanks Dogbert and José.
Comment: Docs for GenServer list reserved attributes, [here](https://hexdocs.pm/elixir/Module.html)
Comment: José, nice error messaging might include if you name a attribute wrong, such as using a  leading capital letter for the attribute name. I don't recall seeing naming rules for attributes in the docs.


How do you style an individual webform?

Question: How to style individual webforms with  different css class and html elements?I have a few webforms and I need different html elements like divs, spans etc and css class for each webforms
Comment: you could try using [Theme key](http://drupal.org/project/themekey) module.
Answer: If you just need to apply CSS styling, then if you view the source of the webforms you will see they have container divs with classes that contain an ID number. This ID will allow you to directly target a specific webform.
If you mean you want to add your own divs etc. and template different webforms, then the best way to do this is by creating a specific template file for it.
In your theme folder you can add a template file such as:
webform-form-[nid].tpl.php you can get the ID by viewing the source of your form, it displays in one of the forms parent divs.
As your base you can use the default template from the webforms module. Goto (or other location where you have installed the webforms module):
/sites/all/modules/webform/templates/webform-form.tpl.php

and make a copy of this.
I have themed webforms that appear in blocks in the following way too:
block--webform--client-block-112.tpl.php

Comment: That should be /sites/all/modules/webform/templates/webform-form.tpl.php I think
Answer: For few changes drupal provide a class wrapper for each page node for example :

this is the class for the node 109 so in css you could use :
.page-node-109 input{}

and then for each web form you will use the .pane-node-(node id) to theme it separatly
But for big changes you must use the hook_form_alter
Answer: To modify each Webform separately you should use the forms css ID.  The ID should always be unique.
For example, when you look at the source of your webform, you will notice in the <form> element, there will be an ID. For example <form id='the_unique_id'>.
I believe the ID should be something like webform-client-form-<NODEID>
You can then use your themes CSS file to modify the form.
Note that ID selectors start with # and not .
#the_unique_id {
   background-color: red;
}

How do you style an individual webform?


MySQL error when trying to read from database in PHP/Ajax

Question: In my application I am getting the following error when trying to get data from MySQL. I'm not sure if it is a misconfiguration of MySQL, if someone could check my code for me and tell me how MySQL should look it will be greatly appreciated.
The error that I am receiving is Could not query: Unknown column 'id' in 'where clause'. This only displays once I select an item from the drop down box.
Here is the code for the main page which has the drop down box on it
<!DOCTYPE html>

    <title>Cable Management</title>
    <link href="style.css" rel="stylesheet">

<?php include("Header.php"); ?>

Cable Management

Bournemouth Office

Enter how many cables you want to remove or add from the Bournemouth office

<form>
<INPUT TYPE = "TEXT" NAME='amount' VALUE ="">
<select name="cables" onchange="showcables(this.value)">
<option value="">Select a cable type</option>
<option value="0.25 Metre Orange">0.25 Metre Orange</option>
<option value="0.3 Metre Orange">0.3 Metre Orange</option>
<option value="0.5 Metre Orange">0.5 Metre Orange</option>
<option value="1 Metre Orange">1 Metre Orange</option>
<option value="2 Metre Orange">2 Metre Orange</option>
<option value="3 Metre Orange">3 Metre Orange</option>
<option value="5 Metre Orange">5 Metre Orange</option>
<option value="10 Metre Orange">10 Metre Orange</option>
<option value="2 Metre Black">2 Metre Black</option>
<option value="3 Metre Black">3 Metre Black</option>
<option value="5 Metre Black">5 Metre Black</option>
<option value="10 Metre Black">10 Metre Black</option>
<option value="RJ 11">RJ11</option>
<option value="RJ 11 to BT">RJ11 to BT</option>
</select>
<INPUT TYPE = "button" Name = "Remove" VALUE = "Remove">
<INPUT TYPE = "button" Name = "Add" VALUE = "Add">
</form>

The amount of cables left will be listed here

        </select>

<?php include("Footer.php"); ?>

Here is the getcable.php page which actually has the MySQL commands in it
<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','','cables');
if (!$con)
  {
  die("Could not connect: " . mysqli_connect_error());
  }

$sql="SELECT * FROM bmouthoff WHERE id = '".$q."'";

$result = mysqli_query($con,$sql) or die ("Could not query: " . mysqli_error($con));

echo "
";
while($row = mysqli_fetch_array($result))
  {
  echo "
";
  echo "" . $row['Amount'] . "	";
  echo "
";
  }
echo "
";

mysqli_close($con);
?>

Comment: may be id column is not there.
Comment: check the table again, sure the column isnt actually named ld (LD) ?
Comment: could you show a script of your data table? do you have a column named id? are your id values the strings like '0.25 Metre Orange'?
Comment: Sorry, MySQL is not my strong point at all. I am using PHPmyadmin and I have created a database called cables. A table called bmouthoff and a Column called ID. My column wasn't called ID I am not getting this error anymore. Do I not need to add each column as the full name as in the drop down box? How can I get some dummy data to test?

Thanks again
Answer: Your table seems not to have a column called id, therefore your query fails.
SELECT * FROM `bmouthoff` WHERE `id` = 'youridexample';

The error message...

Unknown column 'id' in 'where clause'.

...says it all.
Check out the table definition and replace id with the actual column name you want there, or rename the column in your table to id.
Answer: R u kidding ?
value="RJ 11 to BT" This value isn't integer at all. Cannot be converted to int also with the intval funct.
Unfortunetely
I can not see if there is a null controll for the id ?
$q = isset($_REQUEST["id"]) ? $_REQUEST["id"] : null ;
if($q != null)
{
}

work better .
What is the type of ID column ? Is int ? So the escaper of ' ' is useless.
Comment: Sorry I think there may be a problem with the way my application is working then. The idea is that when a certain cable from the drop down box is selected, it connects to MySQL and gets a number of cables that are set for that selected cable type. Make sense?
Answer: In query
SELECT * FROM bmouthoff WHERE id = '".$q."'"

you send value of cables select, wich is not integer.


How to show that a set does not contain a specific string

Question: If I have a set $S$ defined as the smallest set $S$ over an alphabet $A=\left\{ \star, \urcorner,(,), a_0,a_1, \dots \right\}$ ( $S\subseteq \cup_{k \in \mathbb{N}} A^k$) satisfying:
$\bullet \ a_0, a_1, \ldots$  $\in S$
$\bullet $ if $\alpha \in S$ then $ ( \urcorner \alpha) \in S$,
how can I then show for example that $( \alpha \urcorner )$ or $\alpha ()$ is not in the recursively defined set $S$, where $\alpha$ is some element of $S$ (or even  $S\subseteq \cup_{k \in \mathbb{N}} A^k$, for greater generality). Of course I can "see" that this is the case, but how can I prove it ?
Maybe because it seems so easy to see that strings like the above can't be in $S$ I can't up with a proof. (Of course, if $\star \alpha$  were in $S$, intuitively it would be clear, that $S$ woulsn't be the smallest set anymore, but how would I then prove this ?)
Comment: Are you sure that propositional calculus and logic fit here? It sounds like an exercise in formal languages.
Comment: Maybe. But there isn't a "formal languages" tag and I came up with the question while browsing a chapter on propositional calculus...but feel free to edit the tags, if you want to.
Answer: Added Remark: This is a solution to the previous incarnation of the question, which was quite different (it asked one to show that no word of shape $\star\alpha$ is in the set).  This is not a solution of the altered question!
It is obvious, and does not require proof (unless, weirdly, it is demanded that you prove it).
What do we mean by "smallest set $S$"?  In the context of this kind of definition, it means the intersection of all the sets satisfying your two bulleted conditions.
Now let $W$ be the set of all words over the alphabet that contains everything except the $\star$,  Then $W$ obviously satisfies the bulleted conditions.  It follows by the definition of $S$ that $S \subset W$, since $W$ is one of the sets that was intersected to make $S$.  And it is clear that no word of the form $\star\alpha$ is in $W$.
Remark about changed question The strategy of a proof does not change much for the altered questions. (But if the question changes again, the strategy might have to change).  For example, look at the set $Z$ of words that do not end with  $()$ or with $($.  It is clear that if $\alpha$ is in $Z$, then the string produced by the second bulleted condition is in $Z$.  So $Z$ is one of the sets intersected to produce $S$.  This implies that $S$ does not contain any string of shape $\alpha()$.


How to remove the title from a youtube video when using D7 + media module?

Question: When I add an youtube video to a "blog post" content type I automatically get youtube's title/url placed above the video (see screenshot below).

I have Drupal 7.7 + Media 7.x-2.x-dev + Media Youtube 7x-1.x-dev installed.
I have added to the "blog post" content type a new "video" field with type "multimedia asset" and widget "media file selector".

I would really appreciate any advice on how to remove or change this title.
Comment: I have the same setup. It does look like the field label. I have my label set to hidden, but it still shows, I'm thinking it's a bug. I just hid mine with css until I could either try to fix the bug or update the module.
Comment: Yes. I also believe it is a bug. I have been searching online and other people seem to have the same problem. One possible solution is to insert the video into the WYSIWYG editor (I have tried with CK Editor and it works fine). Nonetheless, I would really appreciate if you could provide more details on how to change this with css. thank you so much!
Comment: I have the same problem. The name of youtube video appears in views blocks before thumbnail image. Also, instead of a file name (blabla.jpg) I get youtube video name when I use token to set up og:image in metatags module (otherwise when I use tokens for media image upload fields for the same purpose everything works just fine). So that must be a bug.
Answer: It looks like that's the field label, which can changed on the manage display page (Structure > Content Types > Manage Display)
Answer: Concerns:
Media v2 is not stable right now media 1 is fairly stable and will not give you the title problems you're seeing. You also should not be using the dev version for production sites, not only are they not stable, they will not show update and updating & flushing the database can be problematic.
Uninstall v2:
Also reverting media down is rather drawn out you need to disable sub media types (youtube at the least) then media, then file entity (media v1 comes with it's own entity_file).
Then uninstall media and install v1.
To answer your question:
You might also check http://yoursite.com/admin/config/media/file-types and check the display filters for video. The other place where rocketeerbkw mentioned http://yoursite.com/admin/structure/types/manage/ (your content types machine name example: article/book) might be worth a look as well.
If you are keen on fixing the module I'd suggest installing devel and inspecting the elements, it's probably something in a .tpl somewhere.


Organic Groups module  messes up node editing

Question: Updated header to reflect real cause of problem
I've created some content types using node references for "belongs to" or "owned by" relationships.
When I add a new node, selecting the node references seems to work fine, and the default "list view" showing the newly created nodes also shows that the relationsship is correct. However, when I try to view or edit a single node, the form displayed includes only the "Title" field, and nothing else. I've also verified through "Manage fields" and "Manage display" that my node reference field is supposed to be displayed, but it still does not seem to work.
Do you have any ideas?
Comment: Stack Exchange is not a replacement for the issue queue. If you continue to have trouble, [file an issue](http://drupal.org/project/issues/references).
Answer: Just figured out that the problem was not caused by the references module, but by the "Organic Groups" (og) module. It seems to be a known bug in the organic groups module that basically hides/disables all fields for custom content types that are not marked as group or something like that. There's a report about this in http://drupal.org/node/1029230.
Disabling the organic module make the fields come back again, and even relationships seems to be editable again. I can live without organic groups for now, and considering the severity of the bug I will definitively not try to use that module again until it has been fixed.
Comment: I just learned that the OG module also messes up the Token module somewhat (found it while using auto_nodetitle). I guess using OG is for the very brave at this stage...
Answer: FYI - this question is in reference to the new D7 "References" module (http://drupal.org/project/references) which is currently in development and has not had a formal release. Have you taken a look in the issues cue for the module related to your problem: http://drupal.org/project/issues/references?categories=All
Comment: Yes, I've looked at it, but didn't manage to figure out whether editing nodes was supported or not. There are references to views etc, but apart from actually trying to use the module, I'm not qualified to say whether those view issues are related to custom views, the views module or anything else. Creating a node works as expected, editing does not. I am trying to figure out whether that is a feature (of the module in it's current state) or whether it is a bug. If you see an issue that answers this, feel free to point me in the right direction. Thanks.


MVC Redirect is adding Virtual Directory to URL

Question: My site is hosted on a server with multiple virtual directories, and I have different domain names pointing to their respective virtual directories.  My site works fine in debug mode in Visual Studio where nothing unusual happens.
The URL is something like http://www.greatsite.com, but RedirectToAction links that are like this:
 return RedirectToAction("Profile", "Account");

I want to go here...
http://www.greatsite.com/Account/Profile
...are going here instead:
http://www.greatsite.com/greatsite/Account/Profile
...where 'greatsite' is the name of the virtual directory.
The site is being published using FTP and the FTP address points directly into the 'greatsite' folder.  So the site is published to the root as far as FTP goes.
The page displays either way.  The URL points to the virtual directory, and I'm confused why they would both work.
EDIT
I eventually found the answer here:
https://stackoverflow.com/questions/364637/asp-net-mvc-on-godaddy-not-working-not-primary-domain-deployment
So you might want to close this as a duplicate question, sorry.  Unless someone can explain this solution in more detail.
<rewrite>
    <rules>
        <rule name="Remove Virtual Directory">
            <match url=".*" />
            <action type="Rewrite" url="{R:0}" />
        </rule>
    </rules>
</rewrite>

Comment: possible duplicate of [ASP.NET MVC on GoDaddy Not Working (Not Primary Domain Deployment)](http://stackoverflow.com/questions/364637/asp-net-mvc-on-godaddy-not-working-not-primary-domain-deployment)
Answer: RedirectToAction will redirect to another Action/Controller inside the current asp.net mvc application. You can redirect to an external URL using the Redirect method.
return Redirect("http://www.externalurl.com");

or another virtual directory:
return Redirect("http://www.externalurl.com/directory");

Comment: I do not actually want to redirect to an external URL outside my application.  I am wondering why the virtual directory name is being added to the link, when I never added it, and how to avoid that.
Comment: In that case, you should set the root folder in your FTP to be the virtual directory for your app, and host it there.
Comment: Currently the path for the ftp user is the name of the virtual directory.  Is that the problem?  I'm not sure how to do it any other way.


iOS RestKit Date parsing

Question: In an old iOS project I had to parse dates that come in the format dd/MM/yyyy so I put these lines in a static method of my AppDelegate and it worked as expected
// Set the Dateformatter for the Dates returned by Knowledge tt/mm/yyyy
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[[RKValueTransformer defaultValueTransformer] insertValueTransformer:dateFormatter atIndex:0];

However in the actual projects my dates come in a slightly different format dd.MM.yyyy, so I used the same lines of code, just switched the Date format, but the date is not parsed.
For this date "ExamDate":"20.06.2014" I get (NSDate *) _examDate = 0x08f7dcd0 2014-01-01 01:00:00 CET after parsing and I can't understand why.
Update:
I made a small test with this code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd.MM.yyyy"];
NSDate *date = [dateFormatter dateFromString:@"20.06.2014"];
DLog(@"Date: %@", date);

and got in the log: Date: 2014-06-19 22:00:00 +0000
Answer: It looks like your in a timezone with a GMT offset of -2:00. Set your timezone to 0 GMT to have it printed correctly. What we usually do is just use unix time when passing around dates so we can avoid this sort of issue.
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

Since your problem appears to be in RestKit's parsing you'll need to use your own date parser. You can do this by installing what RestKit calls a Value Transformer which is what it uses when mapping data.
Here's one that you can work with to achieve what you want:
[RKObjectMapping alloc]; // This ensures you will actually insert at index 0!

[RKValueTransformer.defaultValueTransformer
 insertValueTransformer:
 [RKBlockValueTransformer
  valueTransformerWithValidationBlock:^BOOL(__unsafe_unretained Class inputValueClass, __unsafe_unretained Class outputValueClass) {
      return (([inputValueClass isSubclassOfClass:[NSDate class]] && [outputValueClass isSubclassOfClass:[NSString class]]) ||
              ([inputValueClass isSubclassOfClass:[NSString class]] && [outputValueClass isSubclassOfClass:[NSDate class]]));
  }
  transformationBlock:^BOOL(id inputValue, __autoreleasing id *outputValue, __unsafe_unretained Class outputClass, NSError *__autoreleasing *error) {
      RKValueTransformerTestInputValueIsKindOfClass(inputValue, (@[ [NSString class], [NSDate class] ]), error);
      RKValueTransformerTestOutputValueClassIsSubclassOfClass(outputClass, (@[ [NSString class], [NSDate class] ]), error);
      if ([inputValue isKindOfClass:[NSString class]]) {
          // We're mapping from a string to a date.
          // You can add your formatter here.
          // Below is mine for mapping from Unix Time to an NSDate.
          NSString* input = inputValue;
          *outputValue = [NSDate dateWithTimeIntervalSince1970:input.integerValue];
      } else if ([inputValue isKindOfClass:[NSDate class]]) {
          // We're mapping from a date to a string.
          // You can add your formatter here (if needed).
          // Below is mine for mapping from an NSDate to Unix Time.
          NSDate* input = inputValue;
          *outputValue = @([input timeIntervalSince1970]);
      }
      return YES;
  }]
 atIndex:0]; // Insert at index 0 so your formatter is always used over the default one.

Alternatively, it looks like RestKit has it's own NSDateFormatter category which adds support for adding it as an RKValueTransformer. You should be able to try something like this:
[RKObjectMapping alloc]; // This ensures you will actually insert at index 0!
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd.MM.yyyy"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
[RKDefaultValueTransformer insertValueTransformer:dateFormatter atIndex:0];

Comment: You're right... this fixes my problem with the dateformatter sample, but still it's not automating the parsing in RestKit, there I still get 1st january 2014 for this date
Comment: Which version of RestKit are you using? @Hons
Comment: I'm currently on RestKit 0.23.1
Comment: @Hons, since you're using 0.23.1, you can use a RKValueTransformer. I've pasted one into my answer. You'll need to add your own formatting code where I've commented, but this should get you on the right track.
Comment: I add your code to my project.. The first block, the validation, is called for every attribute, and for my date it returns YES, but the second block is never called
Comment: @Hons That's strange. If it's returning YES and you've inserted it at index 0 it should be using your transformation block. Try removing the `RKValueTransformerTest...` macro calls and see if that works.
Comment: @Hons It looks like internally RestKit is also making NSDateFormatter compatible with it's RKValueTransformers using a category. I'll edit my answer and give another suggesting.
Comment: By debugging I saw that there is a RKISO8601DateFormatter before my transformer in the list... but I added it at index 0
Comment: @Hons, I've added a line of code to my example which should fix this and allow your custom value formatter to be insert at index 0.
Comment: You're right. The RKObjectMapping initialize method added the ISODateTransformer at index 0, which happend after I put the transformer there. Thank you very much!
Comment: I used the second block (Alternately...) to solve a date transformation issue with a web service I'm using. Other than setting the parameters appropriate for my situation, I needed to retrieve the default value transformer:
`[[RKValueTransformer defaultValueTransformer] insertValueTransformer:dateFormatter atIndex:0];`

iOS RestKit Date parsing


prove that if $(\mathbb{Z}/n\mathbb{Z})^{*}$ is cyclic, $n=2,4 $~or~$ p^k, 2p^k$ where $p$ is an odd prime number.

Question: prove that if $(\mathbb{Z}/n\mathbb{Z})^{*}$ is cyclic, $n=2,4$ or $p^k$, $2p^k$ where $p$ is an odd prime number.
I thought of looking at two cases: $n = \Pi p_i^{k_i}$, $n = \Pi 2 p_i^{k_i}$  with $p_i \neq p_j$ if $i \neq j$ and check why these fail to be cyclic.
We see obviously that for both cases $\phi(n) = \Pi (p^{k_i} - p^{k_i - 1})$. this number is even as well because the $p_i$ are odd. Further than this i haven't come.
Any tips and tricks? Am i going to the right direction or is there a better trick in doing this?
Answer: HINT: Let $m,n$ be coprime positive integers. Then the Chinese Remainder Theorem says $\mathbb{Z}/mn\mathbb{Z} \cong \mathbb{Z}/m\mathbb{Z} \times \mathbb{Z}/n\mathbb{Z}$.
This implies that $\left(\mathbb{Z}/mn\mathbb{Z}\right)^{\times} \cong \left(\mathbb{Z}/m\mathbb{Z}\right)^{\times} \times \left(\mathbb{Z}/n\mathbb{Z}\right)^{\times}$ so in particular can't be cyclic  unless both of these components are cyclic and the orders are again coprime. This should reduce you to the case of prime powers or twice prime powers.
For powers of two, note that $(8k+a)^2 \equiv 1 \mod{8}$ whenever $a$ is odd and use this to construct an argument to why $\mathbb{Z}/2^l\mathbb{Z}$ has no primitive root for $l>2$.
Comment: I've edited my statement slightly, but if you take $m,n$ to be powers of distinct odd primes then the orders of these groups can't be coprime (they are both divisible by 2) so the product can't be again cyclic in this case.
Comment: Show that if $a \mod{2^k}$ is a generator for $k>2$ then $a \mod{8}$ is a generator for $(\mathbb{Z}/8\mathbb{Z})^{\times}$ which creates a contradiction. This is why any higher power of 2 cannot have a cyclic unit group since it fails at 8 so must fail for anything larger than 8.
Comment: This statement is the same as saying that $a^{2^k} = 1 \mod{2^{k+2}}$ for $k>1$ which is a contradiction as the unit group has order $2^{k+1}$, but I think its simpler to use the method I gave above.
Comment: can't the right hand side be cyclic if the groups have a generator with the same order?
Comment: No -  consider $\mathbb{Z}/2\mathbb{Z} \times \mathbb{Z}/2\mathbb{Z}$.
Comment: hmmmm, i can see that you can even say $n^2 = 1mod (8)$ if $n$ is odd. And it is clear that n has order $2$ but it should be $4$ to be cyclic in the case of 8. but what can  say about 1 mod 16, 1 mod 32 etc. because n^2 is not alway equal to 1 mod 16 and 1 mod 32 as well.
Comment: thanks man i get it now :)


AngularJs : change state using $state.go but want to redirect state's specific elements

Question: I have two controllers situated at different folder & using UI-router to go to different states.
able do that using $state.go('app.to-do') form "app.dahsboard" state.
I want to go to a specific element of app.to-do state !!!
how do I do it ??  is $state.go have any functionality or is there any other ways is there ??
Please help !!
<code>   for example:
    from dashboard controller
         {
           //on ng-click
            $scope.starechange = funtion () {
                $state.go('app.to-do');
                 //but want to go to specific elements of state 'app.to-do'
            }
         }
</code>
Answer: You can pass parameters
https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stategoto--toparams--options
and get with $stateParams


Create screenshot only on test failure

Question: Currently I have a function that creates a screenshot and I call it here
def tearDown(self):
    self.save_screenshot()
    self.driver.quit()

There is also a folder being created which is used to store the screenshots.
I don't want this to happen when the test passes.
What do I have to add in order for this not to happen?
Thanks for all the help
Comment: Could you share how do you run the tests? Thanks.
Comment: Idk what you mean, like command line or the unit test?
Comment: How do you run them from the command-line, right. Also, what python version are you using?
Comment: v2.7.8 and python test.py
Answer: If your test failed, the sys.exc_info will have an exception. So you can use it as pass/fail result of your test:
if sys.exc_info()[0]:
    # 'Test Failed'
else:
    # 'Test Passed'

And if you want to take a screenshot on failure:
import unittest
import sys
from selenium import webdriver

class UrlTest(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome()

    def test_correct_url(self):
        self.driver.get('https://google.com')
        self.assertTrue('something.com' in self.driver.current_url)

    def tearDown(self):
        if sys.exc_info()[0]:
            self.driver.get_screenshot_as_file('screenshot.png')
        self.driver.quit

if __name__ == '__main__':
    unittest.main()

Answer: In your initialisation method set a self.NoFailuresSnapped = 0 and check your test environment for the current number of failures being > self.NoFailuresSnapped before calling or within your function and of course set it again before returning.
Answer: Here is one way to capture screenshot only when failure:
def setUp(self):
    # Assume test will fail
    self.test_failed = True

def tearDown(self):
    if self.test_failed:
        self.save_screenshot()

def test_something(self):
    # do some tests
    # Last line of the test:
    self.test_failed = False

The rationale behind this approach is when the test reaches the last line, we know that the test passed (e.g. all the self.assert* passed). At this point, we reset the test_failed member, which was set to True in the setUp. In tearDown, we now can tell if a test passed or failed and take screenshot when appropriate.

Create screenshot only on test failure


What is an example of an Eilenberg-MacLane space that is not homotopy equivalent to a CW complex?

Question: The proofs that any two CW complexes that are K(G,n) are homotopy equivalent has no obvious extension to the general case. I assume it is known to be false in general, but I can't find an example.
Answer: The Hawaiian earring (which is a a compact path connected and locally path connected subset of the plane) is a $K(G,1)$. See https://en.wikipedia.org/wiki/Hawaiian_earring, https://mathoverflow.net/questions/163847/are-the-higher-homotopy-groups-of-the-hawaiian-earring-trivial. Its fundamental group $G$ is uncountable.
Another example is the Warsaw circle. It is $K(0,n)$ for all $n$. See How to show Warsaw circle is non-contractible? and Connor Malin's answer.
Answer: For a nice example consider the pseudocircle (https://en.wikipedia.org/wiki/Pseudocircle). This is a finite topological space which is weakly equivalent to the circle $S^1$. It follows that the psuedocircle is a $K(\mathbb{Z},1)$. However, any finite CW complex must be discrete, so it obviously cannot be CW.
Comment: Yes, I understand :) I was commenting only because the OP asked for something not homotopy equivalent to a CW complex, and your last sentence is up to homeomorphism. It is a good answer.
Comment: As far as I can tell this doesn't anything about the homotopy type, but it is an easy extension of what you say, as any map from the pseudocircle to a Hausdorff space is constant.
Comment: @MikeMiller, the Pseudocircle $X$ has the *weak* homotopy type of $S^1\simeq K(\mathbb{Z},1)$. For the reason you state it clearly cannot by homotopy equivalent to $S^1$, and cannot even admit a weak equivalence in the direction $X\rightarrow S^1$.
Comment: @MikeMiller, thanks for pointing that out, I do agree that my statement is a bit ambiguous. I actually meant that if $Y$ is finite and discrete then necessarily $\pi_0Y=|Y|$ and $\pi_1Y=0$, so since $\pi_1X\cong\mathbb{Z}$ it cannot be discrete, and hence cannot be CW. I barely even remember what a homeomorphish is anymore ;).
Answer: I think something like this might work: take a noncontractible space that has all homotopy groups zero (such a thing is necessarily not a CW complex, I think an example can be obtained from wedging two comb spaces) and wedge it with K(G,n). The resulting space should not be homotopy equivalent to a CW complex and (perhaps depending on the noncontractible space) be a K(G,n).
Comment: Or just taking G = 0 and a non-contractible space which is weakly contractible gives a counterexample!


How to obtain raw field value from db table in a view?

Question: In Views 2 I am rewriting a field to generate a link that has arguments appended.
One of those fields is referenced as [field_name_value] but outputs 'public' (and translated) value of the field.  In the database the value is stored as 0 or 1 but it outputs No or Yes respectively.  The No/Yes must be coming from the content type template which provides a pair of radio buttons, where 'No' is 0 and 'Yes' is 1.
Is there any way to obtain the raw database (0 or 1) value? Thanks.
Comment: sounds like something in the widget/format is getting in your way.  I don't have v2 up anywhere anymore to play with this, but check into the formatting of the field at the very end of the field configuration screen .
Answer: One of the last things Views does when it renders a view is to process all the fields raw data and format them according to settings, then theme according to the default or your own custom views templates.
So, if the 'Output format' options in field's settings on the view don't provide what you need, you can get the raw values - before formatting & theming - like so:

Install Views PHP so you can run code from within views fields, arguments etc.
Check the "Exclude from display" option on the fields you want 'raw' to stop them appearing in the output, but still ensure they're in the view data.
Add one "Global: PHP" field for each field for each hidden field.
In the "Output code" at the bottom of the field settings on the new Views PHP field, add something along the lines of print $row->field_you_want_raw.

Since you've got full PHP in these new fields you can format, tweak and merge any raw field data you need.
Comment: Thanks Jim, Sounds like it will work.  I did install views_php and in my fields area defined the needed field with "do not display" checked.  Then further down the list added a Global-PHP field with the output area defined as:
Answer: Exactly what Jim Kirkpatrick said but at step 4 note the following changes.

When inserting values in Output code you must enclose them in
You can use a combination to display node information use print $row->created;
To display database information use
print $data->_field_data['nid']['entity']->field_YOURFIELD['und'][0]['value'];

The module (7.x-1.x-dev) does not currently work as the documentation says or as you would expect.
Please refer to the following thread and comment for updates and a good example of how to figure out how to construct the code to print out your values.
http://drupal.org/node/1061388#comment-4943984


Strength / speed exercises for rasgueado

Question: I'm trying to learn the rasgueado strumming technique, but I just can't get my fingers to "snap" out with enough power to get an effective sound; is this just something that comes with practice or are there strength exercises I can do away from the guitar that will help?
Background: I'm not a flamenco player; mainly folk / blues. I just want to bring in some different sounds for my own enjoyment.
Comment: When you *shake down* the contents to get a clean tear (so it doesn't spill all over the counter), do this: pinch a corner with the left hand and do a rasgueado on the sugar packet with the right hand. One good one and the packet is ready to tear. ... Differently-sized packets of stuff will have different *recoil* allowing you to practice different tempos. ... I work at Starbucks and easily get bored. :)
Comment: You can practice on sugar packets and hot-chocolate mix.
Comment: It may be the fact that my toddler treats sleep as an optional extra, but I haven't the faintest idea what to do with sugar packets and hot chocolate mix to improve my technique unless it involves mixing them both up with hot water and drinking them for a delicious energy boost.
Comment: @luserdroog, if there is a better practice technique for this than the one you describe, I don't know what it is...! (Now, where did I put those sugar packets...)
Comment: @luserdroog - you should add that as an answer, as I did ask for exercises I could do without a guitar. Tim's advice is more suitable for me at this stage but I'll get some sugar packets when I have the finger movements down :)
Comment: The sugar packet analogy would help with shuffle strumming technique with a pick as well.  Applying mental imagery of things we already learned for other necessary survival purposes - to guitar technique really helps shorten the learning curve.
Answer: Tim's answer is great, so I simply wanted to add a few things. These aren't specifically related to building strength and speed away from the guitar, but should give you some more options and help your R.H. to become more agile.
By keeping your hand still as you execute a rasgueado, you are able to easily play different rhythmic variations of the basic strum. Before outlining these, I should point out that I am a classical guitarist and not a flamenco player, so I only have a few rasgueado techniques in my armoury. A flamenco player would doubtless use many more variations.
Firstly, keeping the R.H. still allows one to alternate down-strums (with either the index finger alone or with three or four fingers) with up-strums with the thumb. The primary benefit from doing this, is that the nail of the thumb is used for the up-strums, rather than using the fleshy side of the index finger, and gives a brighter, more attacking sound. (The "p" in the example below is for pulgar, spanish for thumb. Also, note the downwards arrows are the up-strums, as they move from highest string to lowest - bit confusing!)

If using three or four fingers for the rasgueado, rather than just the index finger, these can follow each in quick succession, as Tim points out in his answer, giving a dramatic, explosive sound. Instead, though, with practice these downward strums can be slightly separated, to give the impression of quick rhythmic repetition of chords. One of my teachers used to play the opening of Rodrigo's Aranjuez Concerto using this technique, instead of simply strumming up and down with the index finger. This gives a lighter, more subtle rhythmic effect:

And these separated a m i strums can then be followed by a down strum with the thumb to create a characteristic triplet rhythm (found in Bolero rhythms, for instance):

Finally, I use a kind of "tremolo-rasgueado", where I continuously strum up and down with all three R.H. fingers alternately (kind of like the way one would "drum" the fingers on a table). I've no idea if this is a legitimate technique, but it works well for me!
Like I said before, I'm no expert on flamenco technique, but find these few additions to the basic "down-flicking" strum work well for me. It would be great if some flamenco players added some information with other answers...
Comment: Bit advanced for me at the moment :) but some great things to try for later, thank you.
Comment: Good extra info ! Do you tend to rasgue (no, I made it up) with little finger first?
Comment: Hey @Tim, I just use three fingers and miss out the pinky, as I have a short nail on it and long nails on **p i m a**
Comment: So is it ima or ami?
Comment: Definitely **a m i**!
Answer: Use a very tight fist, and flick each finger out, most seem to start with pinky. Do it slowly and controlled at first, making sure to hit all the strings with equal force. Do not move your arm/wrist/hand until all four fingernails have 'rasgued'.
Comment: +1 for "don't move arm/wrist/hand". As a classical guitarist I just use three R.H. fingers, and not the pinky (which I don't have a long nail on) - I know that flamenco players will usually use all four, but I think most players would find using just three works pretty well.
Comment: I'm pretty sure I'm moving my hand wildly, so this is great advice I will try out later. Should the movement be all in the finger muscles, or does the fingertip start tucked into the palm to give more of a "flick"?
Comment: Until you get the hang of it, flick.The main finger muscle used is the one closest to the palm, as in the fingers will straighten as soon as possible .
Comment: I'm going to leave this question open a bit in case anyone else wants to chip in, but I will mark this as the answer - I had a quick go last night and the twin advice to keep a tight fist and keep my hand still is a revelation. I've already got a hugely better sound on single "flicks", and has made me much happier that I'll be able to get it if I persevere.
Comment: Marked as the answer as I'm really actually enjoying the practice now with this tip. I found this YouTube video really useful too; simple, no frills example of the target sound: https://www.youtube.com/watch?v=Sk2FXKmdoz8
Answer: After practising at the weekend I'm going to add another answer myself that I found useful :o)
Practice on the guitar, but with muted strings rather than playing a chord; it helped me focus on one thing - the speed, power and consistency of the right hand - without the distraction of worrying about whether the notes sounded right.
It also made it much clearer when I was doing it fast enough - getting a quick, clean "CHUNK" sound with each finger rather a slower "washboard" effect that ran into each other (which I'm sure would be a lovely alternative sound, but is not what I'm after right now).
Answer: In flamenco guitar, a technique often used to get a rasgueado to "snap" is to place the upper side of the nails of the fingers used in the rasgueado (mi-ami-xami, etc.) right beneath the middle joint of the thumb. It is similar to the "closed fist" technique described above, except you do not close the fist, rather you form a circle.
If you do this even without the guitar, you will notice that you can build up the energy by pressing your fingers on the thumb, and then simply release. Rest your thumb on the sixth string of the guitar and use this technique.
However, this only works if it is a single rasgueado and not a loop of consecutive rasgueados (say, just ami instead of amiami ad infinitum). Of course, rasgueado loops aren't used as accentuations and as such don't require to have a "snappy" sound. The single rasgueados are used for accentuations and require the "snappy" sound much more. For rasgueado loops, the main focus shouldn't be power as much as consistency and making sure that each finger plays all the string separately (i.e., in the case of a ami rasgueado, you play all of the strings with a before the m kicks in(because of the sympathetic muscles, this is hard to do) and the finger movement is quick (no "sliding" across, it should sound like a chord)).


How to create a tab-like registration form in Ionic 2 & 3

Question: I am creating a registration form in ionic and would like to have the registration page split into different tabs. what i mean is to have the user click on "Next" after filling the information on the first page and so on to the last page before submitting the form. Any pointers or assistance will be highly appreciated.
I am pretty much a beginner with ionic 2 & 3
Answer: I think you are finding for Ionic Slides. You can achieve your target by using this.
Please check this.
https://ionicframework.com/docs/api/components/slides/Slides/
you can lock the sliding by parameter shouldLockSwipeToNext. Then user will not be able to swipe to the next slide.
Comment: Thanks for the reply, Dilanka. Can i use this for forms? and also pass parameters?
Comment: please describe your requirement? What do yo mean by passing parameters? I suggest you go through the API. I have given the URL for that... :) don't be lazy to read the API ;)


Minimizing $\|Ax\|_2$ subject to $\|x\|_2 = 1$

Question: I have a Matlab program to estimate a vector $x$ from noisy measurements. I use the singular value decomposition (SVD) to solve the linear equation $Ax=0$ (where the number of equations is greater than the number of variables). I have read before (link below) that in this case, the solution will be the last column in the $V$ matrix (assuming <code>[U,S,V] = svd(A)</code> and $\|x\|=1$).
The problem is that when I test the program using true values of the measured quantities (quantities without noise) the estimated vector is correct. However, when I add the noise, the estimated vector has values which are far from the true ones (the estimated vector seems to have some of its signs converted "flipped" which makes the difference between it and the true vector large!)
I will be grateful if someone could help me.
http://andrew.gibiansky.com/blog/mathematics/cool-linear-algebra-singular-value-decomposition/
Comment: I missunderstood your problem; your problem is not a problem of finding least square fit to the data. As I understand the problem is: find $x$ such that $||Ax||_2$ is minimized under constraint $||x||_2 = 1$. Is it right?
Comment: Something is wrong here. What are you going to solve? If $AX = 0$ for a mxn matrix A with m > n, then usually X is zero (almost always for random A); if X is nonzero, then Y = X * Q is also solution for any Q. X is given by the last column of V if S has exactly one zero on diagonal, but this is not the case here. Is this a regression problem? If yes, then you are going to find least square solution to $AX = b$ using SVD method.
Comment: I have added the link in the original post, read the part "Applications: Solving Linear Equations". I am trying to find the least squares fit to the data.
Comment: part "Applications: Solving Linear Equations" of this note is broken.
Comment: what do you mean by broken?
Comment: I mean that this part is completely wrong, misleading, confusing. See for example [this](https://en.wikipedia.org/wiki/Linear_regression) as much better explanation of linear equations.
Answer: As I understand the problem is: find a vector $x$ such that $||Ax||_2$ is minimized under constaint $||x||_2 = 1$ for $m\times n$ matrix A.
Such problem always has solution, but solution need not be unique.
First we need to observe that $\min ||Ax||_2 = \sigma_{min}$, where $\sigma_{min}$ is the smallest eigenvalue. Let $U$, $S$, $V$ be the SVD factorization of $A$, i.e. $USV' = A$, $S$ is the diagonal matrix of size $n\times n$ containing singular values sorted decreasingly. The vector $x$ is given by the last column of $V$. To see this observe that $V'x = e_n$, where $e_n$ is the last column of $n\times n$ identity matrix. Then $Se_n = \sigma_{min} \times e_n$, and finally $Ax = \sigma_{min} U_n$, where $U_n$ is the last column of $U$. Thus $||Ax||_2 = \sigma_{min} ||U_n||_2 = \sigma_{min}$.
Hence, the last column of the matrix $V$ is one of the solution $x$ to the problem.
The second one is $-x$. There may exist other solution if the matrix $A$ has many singular values equal to $\sigma_{min}$.
Singular value decomposition is not determined uniquely. If $i$-th column of $U$ and $V$ are multiplied by -1 in the same time, then we stil have valid SVD decomposition. When the matrix $A$ is perturbed slightly, then $U$ and $V$ matrices can change dramatically, but not the S matrix.
Basically there are two solution to the problem (ignoring degenerate cases). In order to define unique solution to the problem one must impose additional constraints like for example element with maximum absolute value must be positive.
Comment: I see, So there is no other way to determine the signs of the solution than imposing additional constraints.
Answer: We would like to minimize $\|Ax\|_2$ subject to the equality constraint $\|x\|_2 = 1$. Hence,
$$\begin{array}{ll} \text{minimize} & \|Ax\|_2\\ \text{subject to} & \|x\|_2 = 1\end{array}$$
which can be rewritten as a quadratically constrained quadratic program (QCQP)
$$\begin{array}{ll} \text{minimize} & \|Ax\|_2^2\\ \text{subject to} & \|x\|_2^2 = 1\end{array}$$
Thus,
$$\|Ax\|_2^2 = x^T A^T A x \geq \lambda_{\min} (A^T A) \|x\|_2^2 = \lambda_{\min} (A^T A) = \sigma_{\min}^2 (A)$$
and
$$\|Ax\|_2 \geq \sigma_{\min} (A)$$
If $A$ has full column rank, then its SVD is of the form
$$A = U \Sigma V^T = \begin{bmatrix} U_1 & U_2\end{bmatrix} \begin{bmatrix} \hat\Sigma\\ O\end{bmatrix} V^T$$
where the zero matrix may be empty. The eigendecomposition of $A^T A$ is, thus,
$$A^T A = V \Sigma^T U^T U \Sigma V^T = V \Sigma^T \Sigma V^T = V \hat\Sigma^2 V^T$$
In this case, $\sigma_{\min} (A) > 0$, and the minimum is attained at the intersection of the $1$-dimensional vector subspace spanned by the right singular vector associated with $\sigma_{\min} (A)$ with the unit Euclidean sphere. As the singular values are usually listed in descending order, this right singular vector should be the last column of $V$. If the minimum singular value has multiplicity greater than $1$, then the minimum is attained at the intersection of a vector subspace of dimension greater than $1$ with the unit Euclidean sphere, which means that columns of $V$ other than the last could be used.
If $A$ does not have full column rank, then its SVD is of the form
$$A = U \Sigma V^T = \begin{bmatrix} U_1 & U_2\end{bmatrix} \begin{bmatrix} \hat\Sigma & O\\ O & O\end{bmatrix} \begin{bmatrix} V_1^T\\ V_2^T\end{bmatrix}$$
where the zero matrices may be empty. The eigendecomposition of $A^T A$ is, thus,
$$A^T A = V \Sigma^T U^T U \Sigma V^T = V \Sigma^T \Sigma V^T = \begin{bmatrix} V_1 & V_2\end{bmatrix} \begin{bmatrix} \hat\Sigma^2 & O\\ O & O\end{bmatrix} \begin{bmatrix} V_1^T\\ V_2^T\end{bmatrix}$$
In this case, $\sigma_{\min} (A) = 0$, and the minimum is attained at the intersection of the null space of $A$ with the unit Euclidean sphere. As the columns of $V_2$ span the null space of $A$, any column of $V_2$ would do.
Comment: Thank you for editing my post and for your answer. However, my problem is not about how to solve this kind of systems. My problem is as I stated in the post; the solution I get has its signs flipped. maybe this is -as Sto mentioned below- due to the fact that the SVD has sign ambiguity.
Comment: @maruchan Check your latest comment on this question. Do you know what you want? If you know what you're doing, the signs should not be flipped. http://math.stackexchange.com/a/1805239/339790
Comment: what do you mean by "the signs should not be flipped"?, could you explain more. From the other two answers, I would say that SVD has sign ambiguity since "If i-th column of U and V are multiplied by -1 in the same time, then we still have valid SVD decomposition" isn't that right?
Comment: @maruchan The key is "same time".
Comment: I don't know what am I doing wrong. I have a large number of noisy measurements stored in matrix A, I perform the SVD on matrix A using Matlab function svd, then I take the last column of V matrix as my solution and I find this solution's absolute value is close to the true vector absolute value, just its signs are flipped. I have no idea how to fix that!
Comment: @maruchan What is it whose signs are flipped? If you take the norm of the last column, you should get something close to $1$, as $V$ is an orthogonal matrix.
Comment: I mean the solution vector (last column of V) have some of its components with opposite signs or even wrong signs compared to the true vector components.
Comment: @maruchan Take the inner product of the last column of $V$ with the so-called "true vector". Perhaps they are orthogonal.
Comment: The problem is not to minimize $||Ax||_2$ but to find $\arg\min||Ax||_2$. If x is a solution, then -x is also a solution and the algorithm switches randomly between these two. Both solutions are valid, why we want to prefer one of them?
Comment: @ Pawel Kowal, I don't know what is (argmin||Ax||2) but yes the sign of the solution is my problem, I am estimating the inertia matrix that is why I need specific solution with the right signs as the true Inertia.
Comment: @maruchan What are the "right signs"? Must all entries of the vector be positive? Nonnegative?
Comment: @Rodrigo de Azevedo I have 6 components, one is negative, the others are positive.
Comment: @maruchan You could have mentioned that. One can solve the QCQP with nonnegativity constraints.
Comment: @maruchan So why don't you postprocess the solution to obtain correct signs?
Comment: @Rodrigo de Azevedo, I also don't know the QCQP. So you say I can solve this with nonnegativity constraints on some components of the x vector? since not all of  the x components are positive.
Comment: @Pawel Kowal, post process? could you please explain more?.
Comment: @maruchan What is the rank of $A$? Does the matrix have full column rank?
Comment: @RodrigodeAzevedo, yes A has full column rank.
Comment: @maruchan If you know, that sign of the solution $x$ is wrong, then just multiply by -1; $-x$ is also a valid solution to the problem.
Comment: @PawelKowal, yes but you see, the signs are not always the opposite of the true vector, as I stated earlier the x vector has 6 elements. the third element should be negative, the others should be positive. however in the solution sometimes I get all positive elements so in this case multiplying by -1 will not do it.
Comment: @maruchan It is not possible. It means that your "true solution" does not solve the problem you stated. You may have some bug in  the code. I don't know how you define "true solution", maybe perturbations are too large. Or smallest singular values are very close to each other.
Comment: @PawelKowal, hmmm...I think my code is correct because when I eliminate all of the perturbations and noises the solution which I get is always true. but maybe it is the perturbations or the smallest singular values are close to each other as you have suggested. do (0.3862 and 0.01865) are considered close for example?
Comment: Also I wonder if this problem is related to ill-conditioning.
Comment: @maruchan Signs of the solution can change even when perturbations are very small if one of component of the solution is close to zero. In this problem you cannot require anything about signs. If signs are important, then you need to define the problem as QCQP with inequality constraints as was suggested. But this is something completely different.
Comment: @maruchan What is the multiplicity of the minimum singular value?
Comment: many thanks for that great explanation @RodrigodeAzevedo. I would like to ask you 2 questions regarding your proof. How can we state that 1. $\textbf{x}^\top\textbf{A}^\top\textbf{Ax}\ge \lambda_{min}(\textbf{A}^\top\textbf{A})\|\textbf{x}^2_2\|$ and 2. $\lambda_{min}(\textbf{A}^\top\textbf{A}) = \sigma^2_{min}(\textbf{A})$? Many thanks in advance!
Comment: @ecjb For a proof of the inequality, take a look at [this](https://math.stackexchange.com/a/1795758/339790). The equality follows from the definition of singular value.
Answer: SVD inherently has sign ambiguity, so you will need to use some auxiliary information to resolve the direction of the vector.
You may find this answer helpful: https://mathoverflow.net/questions/41756/making-matlab-svd-robust-to-transpose-operation
This paper defines a convention for identifying the true direction of the vectors. https://www.researchgate.net/publication/227677444_Resolving_the_sign_ambiguity_in_the_singular_value_decomposition
Comment: My understanding is that the sign ambiguity might affect any singular value and that you would use the original data and the singular value to infer which direction is the true one.
Comment: so if my vector (last column of V matrix) is not affected at all every time I try to solve the sign ambiguity issue does that mean it is the right vector and nothing is wrong with its signs?
Comment: No. It's just an artifact of the numerical conditioning of the data. Have you read the paper here https://www.researchgate.net/publication/227677444_Resolving_the_sign_ambiguity_in_the_singular_value_decomposition
Comment: Yes, I have. that is why I asked that question. I do not know if I understand it correctly, but I think it says that as long as my vector is not affected then the estimation from the SVD and the flow of data are in the same direction. is that right?
Comment: Sort of. The direction of the vector may be arbitrary in sign. You should choose it's final direction by looking at the data as per Figure 3 in the paper and aligning the vector with the  data's primary direction :)
Comment: thank you very much for your help..I will keep searching.


How should I approach statistically?

Question: I am conducting a meta-analysis on the therapeutic benefits of drug A - treated vs placebo. I would like to address the possibility of side effects/tolerability/likeliness of developing side effects. The side effects are categorized into to three subgroups: mild side effects, moderate side effects and severe side effects.
I have included 20 studies in my analysis. I want to visualize the proportion of patients who develop side effects. However, the follow-up time differs among the studies. Some report side effects that occurs within the first month whereas others report side effects first, second and six month. Further, the sample size differs greatly (I do not know it this is relevant).
Can I do some sort of weighted histogram (I don't know if this exist)? Or how can I investigate this matter further/visualize it?
Comment: Could you provide more details on exactly what the different studies reported?
Comment: It sounds as though you are looking for a forest plot.
Answer: You can estimate a logit model where
1) developing side effects is the dependent variable,
2) follow-up time is one of independent variables,
3) each study is 1 observation,
4) the reported standard errors in the study are used to determine the weight of the observation (the standard errors will take account of the reported sample size).

How should I approach statistically?


How to grant permissions to android instrumented tests?

Question: I have an application that reads SMSs. The app works fine when debugging but when testing it using android instrumented test it throws the following error
java.lang.SecurityException: Permission Denial: reading com.android.providers.telephony.SmsProvider

This is my test case
@RunWith(AndroidJUnit4.class)
public class SmsFetcherTest {

   @Test
   public void fetchTenSms() throws Exception {
      // Context of the app under test.
      Context appContext = InstrumentationRegistry.getContext();

      //   Fails anyway.
      //   assertTrue(ContextCompat.checkSelfPermission(appContext,
      //     "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED);

      List<Sms> tenSms = new SmsFetcher(appContext)
              .limit(10)
              .get();

      assertEquals(10, tenSms.size());
   }
}

I'm new to instrumented tests. Is this is proper way to do this?
Or am I missing something?
Comment: InstrumentationRegistry.getContext() doesn't return the Context of the app under test. To get it, use InstrumentationRegistry.getTargetContext().
Answer: Use GrantPermissionRule. Here's how:
Add the following dependency to app/build.gradle:
dependencies {
    ...
    androidTestImplementation 'androidx.test:rules:1.4.0'
}

Now add the following to your InstrumentedTest class:
import androidx.test.rule.GrantPermissionRule;

public class InstrumentedTest {
    @Rule
    public GrantPermissionRule mRuntimePermissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);
    ...
}

Comment: [AndroidX](https://developer.android.com/reference/androidx/test/rule/GrantPermissionRule) link, dependency `androidTestImplementation 'androidx.test:rules:1.2.0'`
Comment: For me seems like this rule doesn't matter, permissions validation is always returning true.
Comment: @Akhha8 same but if I want it to return false?
Answer: You can grant the permission as follows:
@RunWith(AndroidJUnit4.class)
public class MyInstrumentationTest {
    @Rule
    public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);
    ...

}

Comment: Couldn't find class GrantPermissionRule.
Please provide the package.
Comment: [check this](https://developer.android.com/reference/android/support/test/rule/GrantPermissionRule)
Comment: @JavaBanana import android.support.test.rule.GrantPermissionRule; in our test class
Comment: can't find anything in `Manifest.permission` for USB device access permission. Any suggestions?
Comment: It should be `android.Manifest.permission` not `Manifest.permission`
Answer: If you use inheritance for instrumentation classes you should write @get:Rule in parent class.
For location:
import androidx.test.rule.GrantPermissionRule

@RunWith(AndroidJUnit4::class)
open class SomeTest {
    @get:Rule
    val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION)

If you add ACCESS_BACKGROUND_LOCATION on device where Android < Q or permission that doesn't exist in AndroidManifest you will get an exception.
Answer: For reusability I create an interface:
interface WriteExternalPermission {

    @get:Rule val writeExternalPermission: GrantPermissionRule
        get() = GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE)

}

And you can just implement it inside your test class, where this permission is needed.
Answer: For some permissions Rules are not working - like Manifest.permission.BLUETOOTH. Not sure why.
Workaround is to use Mockito and mock Context - so when context.checkSelfPermission() is called by system it simply returns Permission Granted
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {

private Context mockedContext;
private final String[] permissionArrayOne = new String[]{
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        "android.permission.BLUETOOTH",
        "android.permission.BLUETOOTH_ADMIN",
        "android.permission.BLUETOOTH_SCAN"};

@Before
public void setup(){
    mockedContext = Mockito.mock(Context.class);
    Mockito.when(mockedContext.checkPermission(ArgumentMatchers.anyString(),
            ArgumentMatchers.anyInt(),
            ArgumentMatchers.anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
}

 @Test
 public void myPermTest() {
    for (String onePerm : permissionArrayOne) {
        Log.d(TAG, "myPermTest: " + onePerm + " " + mockedContext.checkSelfPermission(onePerm));
        assertEquals(ContextCompat.checkSelfPermission(mockedContext, onePerm), PackageManager.PERMISSION_GRANTED);
    }
}
}


Pan to an Open InfoWindow Without Using InfoWindow.open()

Question: I was wondering if it's possible to manually pan to an InfoWindow using the same behavior as InfoWindow.open() without actually calling InfoWindow.open(). The reason I wish to do this is to ensure that the InfoWindow is entirely on screen (just in case the user pans the map) while avoiding the "flicker" caused by re-opening an already open InfoWindow
I have tried using Map.panTo() to pan to the InfoWindow's marker position, but this centers the map on the marker, rather than doing the minimal amount of work to pan the InfoWindow into view as InfoWindow.open() does.
I also contemplated using Map.panToBounds() to imitate the auto-pan behavior of InfoWindow.open(), but I thought I would ask here before continuing down that path.
Comment: You could always `setCenter` the map to the infowindow's `getPosition`...
Answer: I wanted to do the same thing, but couldn't find anything to trigger the "pan-to-infowindow" behaviour manually.
But since I found a re-opening not to "flicker" at all – at least in v3 of the API – I'm simply closing the infowindow, updating its contents and re-opening it again, to get the desired behaviour (just as you suggested):
infowindow.close()
infowindow.setContent("New Content")
infowindow.open(map, marker)


What does superscript of set $\Bbb N$ means?

Question: I am really new to set theory
 and i just encountered with this line
"Let $k\in \Bbb N$. A subset $A \subset \Bbb N_0^k$ is said to be a....."
However I am really confused what  $\Bbb N_0^k$ means , is that same as $\Bbb N$ with a limit to $k$ or  something ?
P.S - Novice here , So apologies for any inconvenience
Comment: Usually [$\mathbb N_0$](https://en.wikipedia.org/wiki/Natural_number#Notation) is the set of *natural* numbers starting from $0$.
Comment: $\mathbb N^{k}= \mathbb N \times \ldots \times \mathbb N$, with $k$ occurrences of $\mathbb N$, i.e. the set of all $k$-uples of natural numbers.
Answer: Here $\mathbb N_0$ is the natural numbers with $0$, and $$\Bbb N_0^k=\underbrace{\Bbb N_0\times \dots \times \Bbb N_0}_{k\text{ times}}.$$
Comment: Don't forget to like and accept this answer, @MathFreak.


differences between prototype and namespace

Question: In namespace we can use something like this:
var namespace = {};
namespace.something.nested.namespacing();

And also in prototype we can use same like name the namespace:
something.prototype.method();

In both types we are using . notation. So, how can we determine the code is using namespace or prototype?
Comment: Can you include a more *real* example, and possibly add *why* you need to determine this? In the code you provided the difference is obvious as the second case includes "`prototype`".
Comment: There are no namespaces in JavaScript. You can *simulate* namespaces using JavaScript objects.
Comment: There is no "namespace" here. Property lookup is on the object first, then its private `[[Prototype]]`, then that object's `[[Prototype]]` and so on. The object path in the accessing expression is irrelevant to how property lookup proceeds.
Answer: JavaScript doesn't have namespaces. What you're calling a namespace is just an object. It's fairly common to use objects to stand in for namespaces.
Your code:
var namespace = {};
namespace.something.nested.namespacing();

...creates an object and a variable that refers to that object called namespace. Then you add properties to that object (it looks like you've added a property, something, which is also an object, which has a property, nested, which is also an object, which has a property called namespacing which refers to a function).
Your code:
something.prototype.method();

...is also using an object. The above would actually be a really unusual thing to do, you're calling a function (method) by directly referring to the prototype property of what I assume is a function (something). That's not normally what you would do. Normally you'd create an object via the function:
var s = new something();

...and then use the prototype that got assigned to s implicitly:
s.method();

The prototype property on functions can be confusing to people new to JavaScript. It's just a normal property like any other property, which is on function instances. The only thing that makes it special is the new operator: When you call a function via new:
var s = new something();

...the JavaScript engine creates a new, blank, object, then sets its underlying prototype (sometimes called __proto__ but that's not in the spec [yet]) using something.prototype, like this:
// pseudo-code for `var s = new something()`
var tmp = {};                        // New, blank object
tmp.__proto__ = something.prototype; // Assign a prototype to the new object
something.call(tmp);                 // Call `something` with `this` referring to `tmp`
s = tmp;                             // Assign the result to `s`

(There's a detail I left out in the above to avoid confusing matters, to do with the special case where something has an explicit return statement in it that returns an object reference.)
Answer: Well, namespaces are just objects and prototype objects are objects, so from a syntactic point of view, there is no difference how you access them (foo.bar is called dot notation().
However, they serve two fundamentally different purposes:

Namespaces are used to structure your code and to avoid global namespace pollution.
Prototypes are used to share methods between multiple instances of the same constructor function.

So you usually don't call a method directly on the prototype because it most likely won't work. The purpose of this method is to be called on an instance of the corresponding constructor function. For example:
function Something() {}
Something.prototype.foo = function() {};

var s = new Something();
s.foo();

Answer: The . notation is a very general purpose tool used in javascript for accessing any properties of any object.
var x = {};
x.val = 2;

Your reference to a namespace is just a general purpose object in javascript as there is no actual namespace type in javascript.  In other words, plain objects are used to create namespace-like things in javascript.  So, as such, object properties are used to keep track of names in the namespace.

The . notation's use with the prototype is one specific instance of accessing properties on a specific type of object (the prototype).  A prototype is used on a function object and has a very specific use when creating new instances of that function.
function foo() {
}

foo.prototype.talk = function() {
    alert("hello");
}

var y = new foo();
y.talk();

Comment: It means we could only use prototypes only for function object not other types. Thanks.
Comment: @NavinRauniyar: No, all objects have a prototype. It's easy to do, but don't confuse the `prototype` property on functions (which is **not** the function's prototype) and the prototype of an object (which is **not** called `prototype`; it has no externally-visible name at the moment, but in ES6 it will be called `__proto__`). The `prototype` property of a function is a reference to an object that will get assigned to objects created if you use that function with the `new` operator.


How to only checkmarking the selected item?

Question: as a beginner i know that code is used from FMX.ListViewCheckList Sample to put the checkmark accessory on the selected item:
  if AItem.Objects.AccessoryObject.Visible then
   begin
     AItem.Objects.AccessoryObject.Visible := False;
     FChecked.Remove(AItem.Index);
   end
   else
   begin
     AItem.Objects.AccessoryObject.Visible := True;
     FChecked.Add(AItem.Index)
   end;

But i want one selected item checmarked at a time so that If i check another item, the previous is unchecked.
the code i did doesn't work:
procedure TMainForm.ListView1ItemClick(const Sender: TObject;
  const AItem: TListViewItem);
var
  i: integer;
begin
  if Assigned(ListView1.Selected) and (AItem.Objects.AccessoryObject.Visible) then
  begin
    AItem.Objects.AccessoryObject.Visible := False;
    FChecked.Add(AItem.Index);
  end else
  begin
    AItem.Objects.AccessoryObject.Visible := True;
    FChecked.Remove(AItem.Index);
  end;
end;

So cant you point me to the right direction How to do that ?
Answer: I would simply save the checked item when it's checked, and uncheck it when another is checked.
CheckedItem:TListViewItem;  //Declared as a private field in your form.

procedure TMainForm.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem);
begin
if AItem.Objects.AccessoryObject.Visible then begin
     AItem.Objects.AccessoryObject.Visible := False;
     FChecked.Remove(AItem.Index);
     CheckedItem:=nil;
   end
   else begin
     if Assigned(CheckedItem) then begin   //If you've already checked an item, uncheck that one.
       CheckedItem.Objects.AccessoryObject.Visible := False;
       FChecked.Remove(CheckedItem.Index);
     end;
     AItem.Objects.AccessoryObject.Visible := True;
     FChecked.Add(AItem.Index);
     CheckedItem:=AItem;  //Save this one.
   end;
end;

Comment: Well, It works! i understand i was in wrong logic. Thanks!
Comment: @philip-j-rayment; i've another issue, accessory property resets to its default value. How to Save status of the checked state when When listview is resized?
Comment: Solve it: in `procedure TMainForm.ListView1UpdateObjects` add `if Assigned(CheckedItem)` condition and inside it put `FChecked.Contains(FCurrentCurrency.Index)`.
Answer: And in the Update event:
procedure TMainForm.ListView1UpdateObjects(const Sender: TObject;
  const AItem: TListViewItem);
begin
  // Restore checked state when device is rotated.
  // When listview is resized because of rotation, accessory properties will be reset to default values
   if Assigned(CheckedItem) then  //If already checked an item, uncheck that one.
    begin
      CheckedItem.Objects.AccessoryObject.Visible := False; // or True, it depends
      FChecked.Contains(CheckedItem.Index);
    end;

end;


Show full hostname in bash?

Question: Any way to show full hostname in bash instead of partial?
Now for domain.com it's:
user@domain:~$
Would like it to be:
email@example.com:~$
Debian 8.5
Answer: The bash prompt is configured by the PS1 variable. You can configure it simply by setting the variable for example like this:
export PS1="$(hostname -f):~$ "

If you want to make the configuration permanent you can put the export command in your ~/.bashrc file.
I recommend reading the ArchWiki Page for more information.
Comment: seems that changing `\h` to `\H` worked aswell... anyway... how do I set it up so it would automatically use modified `bashrc` on `adduser`?
Comment: Configuration files for new users are stored under `/etc/skel`. http://unix.stackexchange.com/questions/26607/how-do-i-set-a-users-default-bashrc-file
Answer: For Debian 10 open file located at: /etc/bash.bashrc
change 21st line from:
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$

to:
PS1='${debian_chroot:+($debian_chroot)}\u@\H:\w\$

\h becomes \H
then do following command:
source /etc/bash.bashrc

or restart your bash session/relogin.

Show full hostname in bash?


Non-nilpotent and not semisimple algebra with maximal toral subalgebra = 0

Question: I am looking for 3 dimensional non-nilpotent Lie algebra whose only toral subalgebra is $0$. In $sl_2$ the element $\begin{bmatrix} 1  & 0 \\ 0 & -1 \end{bmatrix}$ is diagonalizable so the space generated by it is toral.. In fact, if $L$ is a semisimple Lie algebra then $L$ has a nonzero toral subalgebra.
Answer: By definition, a toral Lie algebra is a Lie subalgebra of a general linear Lie algebra all of whose elements are semisimple. So, first we need a linear Lie algebra of dimension $3$. Here we take the $3$-dimensional solvable, non-nilpotent
Lie algebra $L=\mathfrak{r}_3(\mathbb{C})$, given by the Lie brackets
$$
[e_1,e_2]=e_2,\; [e_1,e_3]=e_2+e_3.
$$
It has trivial center, so that the adjoint representation is faithful, and we can realize it as a subalgebra of $\mathfrak{gl}_3(\mathbb{C})$.
Now let $\mathfrak{t}$ be a toral subalgebra of $ad(L)\cong L$. It must be abelian. However, $ad(e_1)$ is not diagonalisable, and also no nontrivial linear combination of $ad(e_2)$ and $ad(e_3)$. Hence we obtain $\mathfrak{t}=0$.
Comment: Because $\langle ad(e_1)\rangle$ is an abelian subalgebra (but not total), see your other question before.
Comment: I actually have some questions in order to understand the whole situation: first, I want to make sure that algebra $\mathfrak r_3(\mathbb C)$ is the upper triangular $2\times 2$-matrices, if so why $[e_1,e_3]=e_2+e_3$. Second, why did you choose $ad(e_1)$ particularly?
Comment: Alright, thank you very much! But sorry I am used to a different notations, what is $\mathfrak r_3(\mathbb C)$?
Comment: $\mathfrak{r}_3(\mathbb{C})$ is the algebra given above. There are infinitely many different solvable non-nilpotent Lie algebras of dimension $3$, not only the $2\times 2$ upper-triangular matrices.


How would I solve the following question about matrices?

Question: $A= \begin{pmatrix}-1&3\\ -2&6\end{pmatrix}$
Find two $2\times 2$ matrices $B$ and $C$ such that $AB=AC$ but $B\ne C$.
I have tried to do some row operations along with multiplication but I keep getting the wrong answer.
Any help?
Comment: What do you mean by wrong answers? There are infinite solutions to the given problem.
Answer: We have $AB=0$ for all $B$ of the form
$$
B=\begin{pmatrix} 3\alpha & 3\beta \cr \alpha & \beta \end{pmatrix}
$$
On the other hand, $AC=0$ for $C=0$. Now choose $\alpha,\beta$ non-zero. Then we have $AB=AC$ but $B\neq C$.
Comment: You can also add the proposed matrix to an arbitrary $B$ to get a matrix $C$ with $AB = AC$.
Answer: There's no unique answer.

But the task of finding some valid answer is easy.

Since the determinant of $A$ is zero, there exists a nonzero vector $v$ such that $Av = 0$.

Find such a vector $v$, and let $B$ be the $2\,\times\,2$ matrix with both columns equal to $v$. It follows that $AB=0$.

Then just let $C$ be the zero matrix.
Answer: $B=\left(
\begin{array}{ll}
 3 & 0 \\
 2 & 1 \\
\end{array}
\right);\;C=\left(
\begin{array}{ll}
 -6 & 9 \\
 -1 & 4 \\
\end{array}
\right)$
$AB=AC=\left(
\begin{array}{ll}
 3 & 3 \\
 6 & 6 \\
\end{array}
\right)$
I did in this way
Called $B=\left(
\begin{array}{ll}
 a & b \\
 c & d \\
\end{array}
\right);\;C=\left(
\begin{array}{ll}
 e & f \\
 g & h \\
\end{array}
\right)$
I computed $AB$ and $AC$ and wrote an undeterminate system such that they were equal
I got
$g= -\dfrac{a}{3}+c+\dfrac{e}{3},\;h= -\dfrac{b}{3}+d+\dfrac{f}{3}$
And all the other unknowns arbitrary values.
Hope this can be useful


Using of RaiseCanExecuteChanged

Question: I make two methodes like this:
private void Next(string argument)
{
    Current = Clients[Clients.IndexOf(Current) + 1];
      ((DelegateCommand)NextCommand).RaiseCanExecuteChanged();
}
private void Previous(string argument)
{
   Current = Clients[Clients.IndexOf(Current) - 1];
    ((DelegateCommand)PreviousCommand).RaiseCanExecuteChanged();
}
and bind to the xaml:

Every thing work fine. And the next button becomes inactive/grey out when it hits the last post.
The problem is it (the Next button) still inactive when I click the Previous button. The Next button becomes inactive all the time.
My question is how I could make the Next button active again? Thank for all help.
Answer: I assume you are talking about a WPF Application.
There are several reasons your button could become / stay inactive:

Your CanExecute implementation is faulty and returns false even if it should return true
You didnt implement CanExecute or didnt hook it up correctly
The CommandManager didn't realize it's time to requery the commands
You've got a problem with the Focus on your Window / Control

You need to show more of the code so it gives us a broader picture of what you are trying to do.

Using of RaiseCanExecuteChanged


how to properly configure DNS when server hosting one domain is sending mail from another?

Question: i'm trying to figure out how to properly setup TXT and PTR records in the following case:
- one domain is hosted on the server  1stdomain.com on IP 126.96.36.199
- it uses remote mail server for sending mail
- remote mail server is sending email from 2nddomain.com on IP 188.8.131.52.
Quick solution qould be to send emails from same domain which is hosted on the server, but that is not possible right now.
So, i'm interested in what should be the proper DNS configuration
Should a txt record for 1stdomain.com be v=spf1 mx a ip4:22.214.171.124/32 ~all
and ptr
4-3-2-1.2nddomain.com ?
Answer: PTR record should match server hostname. If your server is named '1stdomain.com' and it resolves to 188.8.131.52 then PTR record for 188.8.131.52 should be 1stdomain.com.
Comment: Instead of matching whatever host name is set internally (ie, what resolves to 127.x), the PTR record should match whatever name the server uses to announce itself (ie, the `myhostname` setting in postfix's `main.cf`) .  For example, the hostname of my machine is node3 and the FQDN is node3.my.tld but the `/etc/mailname` and `postfix`'s `myhostname` are mail.my.tld.  The reverse dns for my IP (PTR record) points to mail.my.tld
Comment: @ivanivan, please note that my answer mentions that the server hostname is FQDN resolvable to a real IP. Setting correct hostname makes its explicit setting in mail (and any other) software configuration unnecessary in typical use cases.


Or operator in Views

Question: I've got content-type includes 'field1', field2' and 'field3'. These fields are integer value. Thanks to Views module I created page 'Page1' with contents. In main menu I've got search whit some filters. After filling filters and entering, we can see appropriate contents in 'Page1'. I'd like to create filters or fields in search to allow user to fill in 'min' and 'max' values. After it I want to choose a content only if 'field1' or 'field2' or 'field3' of that content is beetwen 'min' and 'max'. How can I do it?
Answer: In Views where it says Filter criteria there is a button that says Add, if you click on the arrow to the right you can access "And/Or, Rearrange", click that.

You now have an UI where you can group filters together and use OR between groups of filters.
In the example below the node should be Published or of type flickr_image. First thing you need to do is click Create new filter group. From there you can drag your filters into your groups. Next select if the operator between the filters should be AND or OR.

After this add your three fields. Use the filter between, if the filter is exposed it will look like this.

I would keep the first filter exposed and the other not exposed. But then comes the tricky part. The other two filters must inherit the value from the first exposed filter.
I think you need a little bit of glue code to get this going. Put the code below in a custom module. You need to change MYMODULE to the name of your module, MYVIEW to the machine name of your view. And of course field_1 and field_2 to their real names.
function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'MYVIEWNAME') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_2_value']['value']['min'] = $view->exposed_input['field_1_value']['min'];
    $filters['field_2_value']['value']['max'] = $view->exposed_input['field_1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

Comment: I see it. Thanks Pontus. But what should I do to have got only two inputs (min and max) in search and reach what I described above?
Comment: Yes, I understand it. But what filters should I add?
Comment: I created first filter. In my search appears two additional inputs (That's right). I don't understand what can I do to create two filters more without adding inputs in search. Help me, please.
Comment: I've updated my answer.
Comment: Thanks for your answer. Is there another way to do that?
Comment: Is there a chance to do that without custom module?
Comment: No, not that I know of. All you need though is to write a .info file and .module file. You can find an easy guide here http://www.cryptosmith.com/node/373
Comment: Thank you so much. Your directions are extremely helpful. Could you tell me whether in my .module file should I place only function MYMODULE_views_pre_view() ? I read guide and I think that's enough, yet I've never written custom module.
Comment: Yes, the module file will only contain a declaration of the function hook_views_pre_view().
Comment: Ok, I tried what you written and what I read. Unfortunately, I got some errors. I described it in separate question [here](http://drupal.stackexchange.com/questions/81210/inheritance-value-from-the-exposed-filter). If you want, please look at them.

Or operator in Views


Create an "About the Author" box for multilingual sites

Question: I'm having a hard time figuring out how to display a simple box containing some info about the author of a node. I have tried drupal's built-in user profile manager and profile2 module but none of these work on multilingual sites as they should...
Profile2 come with a "Profile2 translation" but it seems that it can be used only for fields labels and not for fields content.
Anyone knows a workaround on how to do it?
P.S.: I use the i18n module.
Thank you!
Comment: Drupal cannot translate itself your content. It translates only the interface. You should make your box translatable and do it yourself.
Comment: Yes I know drupal cannot translate by itself that's why I use the Internationalization module (i18n). The problem is that I can't see a way to translate user's profile fields.

Basically what I need is a box like this one, http://interactiveblend.com/blog/wp-content/uploads/2009/08/1stwebdesigner.png but for a multilingual site.
Comment: Actually I don't care if that small box represents fields from the user profile. All I want to attach a piece of content to every article written by the same author and if the node is displayed in english, the content of that small box should be in english and if the node is in german the text should be in german.
Answer: Profile2 is based on Entity and you have 2 ways of translating entities in Drupal.

by creating an instance of the entity for each language : see https://www.drupal.org/node/1280934
by defining some fields that are translatable : see https://www.drupal.org/node/1280632
Comment: The problem is that under "Translatable entity types" there are only options for Comment, Node, Taxonomy term and User. There's nothing about Profile2.

However I see an option (Users may translate all occurrences of this field:) when creating a new field, checked that and now when trying to translate a profile I see "No translatable fields"...
Comment: Concerning the first problem you describe where Entity2 doesn't appear in "Translatable entity types", you are right - there is bug here - https://www.drupal.org/node/1966640. It should be quite easy to provide a patch thought...
Comment: For i18n_fields, the mechanics seems to work (we can convert a field to be translatable) but there seems to be no way to actually translate the field, so i guess you can't do it with Profile2
Comment: Any other workaround? Something like having a block attached to all articles written by the same author? How can I do that? Thanks!
Answer: As profile2 doesn't seems to work well with i18n, what i would do is to :

create a node type "Author" with some field translatable - the name and picture doesn't need to be translated for example
create a field "Node reference" linking to the Author node using entityreference module
optionally, you could create a field to link the Author node to a Drupal User if you need for example to add a contact form or to display the "About the author" in the user page.

To display the block "About the author" in article pages, there is at least 2 solutions :

In your content type "Article", manage display tab, choose "Rendered entity" for the field Author (easier and better performance but less flexible)
Create a view with a block display containing a contextual filters on the entity reference with a validation on node type = 'Article'. This block could be displayed only on page "node/*" to avoid too much unnecessary views call.
Comment: This is what I needed! Thank you for that! I would like to add that [Translated Entity Reference](https://www.drupal.org/project/translated_entityreference) is also needed in order to get the right translation for the referred node.
Comment: Never used this module but it will probably only work if you use node translation "Enabled, with translation" and not "Enabled, with field translation". Anyway, you can try.