Algorithm for rendering non-filled Julia sets?

Question: I have a commercial application, FractalWorks, for Mac OS. It creates 2D and 3D images of Mandelbrot and Julia sets (using complex numbers and the formula Zₓ₊₁ = Zₓ² + C.) It includes support for Distance Estimates (DE) and fractional iteration values, and creates 3D height maps using DE data. (See this article for a writeup on the app: https://orbittrap.ca/?p=1294)
It renders filled Julia sets using either iteration counts or DE data. It does not, however, render just the boundaries of Julia sets.
I own copies of both "The Beauty of Fractals" and "The Science of Fractal Images", but struggle with the heavier mathematics in those texts. (I took AP calculus in high school almost 40 years ago, so my advanced math is pretty rusty. I use trig, algebra, some linear algebra and matrix math all the time as a developer.)
There is a chapter in "The Beauty of Fractals" titled "Juila Sets and Their Computergraphical Generation", but I find it hard to follow. It talks about using the inverse iteration method, and various other methods that divide the complex plane into a grid of rectangles and keeping track of how many times a rectangle is visited as you iterate the points in a plot in order to identify periodic points.
Are there sample implementations of rendering Julia set boundaries that I could study? (I'm fluent in C and several other C-family languages, and can usually figure out other languages well enough to read them, so the language isn't that important.)
EDIT:
The image from "The Beauty of Fractals" is a complex number Julia set from the equation Zₓ₊₁ = Zₓ² + C. The Julia seed point is .27334, .00742i.
The image from the book looks like this:

Note the complex, connected interior structure.
The JavaScript app recommended in the answer looks like this:

Note how the interior structure is faint and does not connect like the image from the book.
The best I can do with my app is to plot the Julia set using Distance Estimates and crank up the boundary I draw:

(My app does not yet support IIM or any other method for plotting Julia sets other than filled Julia sets.)
Comment: The specific example you refer has a *parabolic* orbit. The Julia set can be generated using the techniques described in [this answer](https://math.stackexchange.com/questions/1131293/what-is-the-algorithm-hiding-beneath-the-complexity-in-this-paper/1131453#1131453). It's quite a bit of work, though. As far as I know, there's no software that automatically detects that type of orbit and draws the Julia set accordingly.
Answer: You wrote:

Are there sample implementations of rendering Julia set boundaries that I could study?

Sure! This little web app generates images of Julia sets for functions of the form $f_c(z) = z^2+c$ using the modified inverse iteration algorithm as described in "The Beauty of Fractals" and "The Science of Fractal Images". Viewing the page source, it's pretty easy to find this Javascript code for the program.
The basic ideas behind inverse iteration, it's modification appear, and implementation for Mathematica were described in this 1998 paper. That program has been been built into the Mathematica kernel since V10. One thing that's nice about that version is that (with all the algebraic machinery that Mathematica has to offer), it's not hard to write a program that works for higher order polynomials or rational functions.
Another technique to get the boundary is called "boundary scanning". This is particularly useful for certain hard to generate Julia sets, as described in this answer.
Here's a comparison of those two algorithms for $z^2 - 0.77967939051932 + 0.11124251677182495i$:
Inverse iteration

Boundary scanning
Comment: Thanks for the reply and links!
Comment: That JavaScript web app does a little better than my app at finding the fine structure of Julia set boundaries, but not nearly as good as the images in The Beauty of Fractals. The  point 12 from preface page XII has the coordinates 0.27334,0.00742i. In B of F, the image shows the interior "tendrils" of the Julia set really clearly. The IIM image from the web app does't capture nearly as much detail.
Comment: @DuncanC I don't have the text handy but high resolution images in those texts are generally generated with boundary scanning. I've attached a couple of images to illustrate.
Comment: See the edit to my question. I included the coordinates of the image I'm using as a test case, along with a photo taken from the book, the image generated by the JavaScript app, and the best my app is able to do using Distance Estimate (DE) data.
Comment: The boundary scanning method does seem like the way to go for images with parabolic orbits. The math behind that is a bit beyond me. My app already does boundary following for speeding up rendering of connected groups of pixels with the same iteration counts. If I could understand how to identify the different segments of a filled Julia set to color them using different colors I could likely adapt my code to do boundary following.
Comment: I'm a computer guy, not a mathematician, and my interest in fractal rendering is as much aesthetic as it is theoretical. For most images, the boundaries of Julia and Mandelbrot sets, using creative coloring, or Distance Estimate based rendering of the fine filaments give very pleasing results. Some of the non-filled Julia set images are quite striking however.
Answer: To render Julia set or boundaries of filled-in Julia sets ( the image you show is filled not non filled) one can use:

Inverse iteration ( IIM/J)
Distance estimation (DEM/J)
edge detection, like Sobel
escape and attraction time
true shape algorithm ( tsa)

example:

BTW, image from the book is a parabolic Julia set, example images and code you can find here
HTH


Que falhas de segurança foram encontradas no OAuth 2.0?

Question: Ontém li esse texto falando que foram encontradas falhas graves de segurança no OAuth. O teor do texto, em particular, faz parecer que não da pra usar o OAuth nem pensar. O problema com isso, é que estou desenvolvendo um projeto que o único modelo de autenticação e autorização plausível era o fornecido pelo OAuth.
Dessa forma, existem realmente falhas tão graves no OAuth como o texto afirma? Especificamente, quais são essas falhas que o texto se refere? Existe alguma forma de proteger contra elas?
Comment: Encontrei esse artigo, dê uma lida: [Serious security flaw in OAuth, OpenID discovered](http://tetraph.com/covert_redirect/oauth2_openid_covert_redirect.html)
Comment: Pelo que entendi, é algo que faz parte do OAuth, e cabe aos implementadores evitar o problema usando uma lista de domínios autorizados (*whitelist*). Ver http://it.slashdot.org/story/14/05/02/2015227/nasty-security-flaw-in-oauth-openid
Answer: A falha não existe no protocolo mas sim na implementação de muitos servidores de OAuth.
O que se passa é que o protocolo OAuth redireciona o browser do usuário para a página de autorização do servidor, por exemplo o Facebook. Aí é passado um URL de retorno.
O Facebook pede permissão ao usuário para o aplicativo poder acessar a API do Facebook em nome do usuário. Depois que o usuário autoriza, o Facebook redirectiona para o URL de retorno.
Para evitar abusos do usuário ser redirecionado para um site não autorizado, o Facebook verifica se o URL de retorno é do domínio configurado para aquele aplicativo.
No entanto, existem situações de abuso que indicam como URL de retorno um de uma página que redireciona para outra que não é o do domínio tinha autorizado configurado, conseguindo assim burlar a verificação.
Quem tem de corrigir o problem é principalmente o servidor de OAuth, por exemplo Facebook, pois em alguns modos de uso do protocolo já retorna o token de autorização direto para a página de retorno sem uma devida verificação.
No entanto, se você tem um aplicativo que usa OAuth para acessar a API de outro site em nome de seus usuários, pode ser que alguém abuse do seu aplicativo para acessar contas do usuários no servidor de OAuth como se fosse o seu aplicativo.
Para evitar esse problema, evite ter páginas no seu site que redirecionem para sites arbitrários definidos como parâmetro no URL da página que redireciona.
O problema é mais complicado, mas esta é a versão simplista que acredito já dá para entender que precauções deve ter.


CSS+JS Carousel loses style when scrolling through it

Question: I have two carousels on my home page that seem to lose styling effects when transitioning between the first and last carousel item.
Any tips on what to change or where to look would be greatly appreciated. I've tried to look for JS events that may cause it with no success, but it doesn't seem like anything would be making it lose the styling.
The home page is:
Home Page
Once the styling breaks it seems to restore after sliding on the carousel more, but I'd like it to remain consistent the entire time. If there's a snippet or file I can send please let me know and I'll post a pastebin here.
Answer: By "lose styling effects" I assume you mean changing it's font size.
It happens because you have CSS
#hometext {
  font-size: 16px;
}

but this id appears only in first visible item on carousel (which changes during swiping).
Id in HTML must be unique (apears max once in source). Just change this to class instead:
.hometext {
  font-size: 16px;
}

and in carousel

Want a custom picture of you and your familiar? Submit your idea for a quote!


page which display only $content (no header,footer,sidebars)

Question: I wanted to show a page which displays only $content. I successfully got the output when I used this code in template.php inside my theme.
function THEMENAME_preprocess_page(&$vars) {
  if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    $vars['template_file'] = 'page-ajax';
  }
}

In page-ajax.tpl.php, I used the following code.
<?php
  echo $content
?>

Is there anyway to achieve the same thing using a custom module?
update
I think you all misunderstood my question, i want to override page.tpl with only $content, Not how to create a tpl using hook_theme!
Currently i have used the same code in my module, but the problem is i have to manually copy page-ajax.tpl to my active theme directory. You can refer the module i created http://drupal.org/project/ajax_links_api
Comment: see [`hook_theme`](http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_theme/7) to create your own template.
Answer: Drupal works its way down a function call stack to find and use hooks defined in other places. So, in much the same way that THEMENAME_preprocess_page() works, so does MODULENAME_preprocess_page - See http://drupal.org/node/223430 for the specific order that these preprocess functions are called.
Now, as for setting up the template. You define it using http://api.drupal.org/api/function/hook_theme - As an example from the block module:
function block_theme() {
return array(
'block' => array(
      'render element' => 'elements',
      'template' => 'block',
    ), // Omitted remainder.

Notice the 'template' attribute. That maps to block.tpl.php. So assume the following:
function myModuleName_theme() {
return array(
    'my_themehook_special' => array(
        //notice I am setting this up to look for the file in a subdirectory of the module
        'template' => 'moduleSubdirectory/filenameOfTemplate',
        'arguments' => array('yourArgumentObject' => null),
    )
);
}

That would register your template. Check out this blog post for more: http://www.trevorsimonton.com/blog/tplphp-hooktheme-drupal-variable-template-module
Answer: Colorbox Node lets you load just content of a menu callback in a colorbox modal via Drupal ajax framework and works well in your case.

When you create your links manually, you will need to add the class
  "colorbox-node" to the link. That is the only class required and the
  module will handle the colorbox loading internally. Your link should
  look like this: My Example
Comment: this is what i want , print content only, but not in a modal ..thanks anyway i will look into the module code to study how they implemented same
Answer: This is going to be a long answer but I read your module and I understand what you're trying to do. Here it goes (FYI, I've done this before):
What you're trying to do should not be done with a theme function or a hook_preprocess_page(). What you should be looking at is implementing what is called a "Delivery Callback". If you want any link to be returned via AJAX no matter what the link is based on your query string.
You should really do something like :
/**
 * Implements hook_page_delivery_callback_alter().
 */
function hook_page_delivery_callback_alter(&$callback) {
  // jQuery sets a HTTP_X_REQUESTED_WITH header of 'XMLHttpRequest'.
  // If a page would normally be delivered as an html page, and it is called
  // from an ?ajax Javascript lets render it as ajax_deliver.
  if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' &&
    $callback == 'drupal_deliver_html_page'
    && $_GET['ajax'] == '1') {
    // Here we change the callback. Now In my example I'm using ajax_deliver
    // but if needed can create your own. That being said ajax_deliver should
    // be more than enough.
    $callback = 'ajax_deliver';
  }
}

If for some reason you need to modify the content being returned, you can actually accomplish that by using hook_ajax_render_alter() like so:
function ugc_ajax_render_alter(&$commands) {
  if ($_GET['ajax'] == '1') {
   // Add my special ajax commands to render the data how I want.
   }
}

But in your case you're only replacing content, a simple ajax command of "ajax_command_html" should work because that's what you're doing in your JavaScript.
Also some comments on the JavaScript file. You shouldn't have to do the $.ajax request yourself.
Instead you can easily simplify the whole thing by just adding a class to your links. The same way the use-ajax class works. So in your case you can look at http://drupalcode.org/project/drupal.git/blob/refs/heads/7.x:/misc/ajax.js#l40 for an example of how to generate your AJAX request. If you change your JavaScript to work like that you won't actually have to write your callback, since the Drupal Ajax framework would handle the ajax_commands being return and replace the content with wat ever selector is on the request.
I hope this is helpful and I know it's a lot but you can read the docs Drupal 7 AJAX Framework to learn more about how to work with AJAX requests and Drupal. Reading Drupal 6, the same concept can be accomplished by using the Ctools module.
Feel free to ask any questions. I know these aren't easy answers to implement. lol but the question wasn't an easy question ;-)
Comment: FYI, I've done a very similar thing, where if a user added an ms-modal class to any link that link would be requested via ajax and display in a special modal. Sadly that code isn't public :-/
Answer: As per your question update, if you would like to include your page-ajax.tpl.php using your module rather than copying it to your active theme you can do the following.
Function in your .module add the path so Drupal knows where to look for your template.
/**
 * Implements hook_theme()
 */
function MODULE_theme() {
  return array(
    'popup' => array(
      'arguments' => array('content' => null), //Array of variables in page-ajax.tpl.php
      'template' => 'ajax',
      'path' => drupal_get_path('module', 'MODULE') .'/theme',
    ),
  );
}

Content in your MODULE/theme/popup.tpl.php file
<?php echo $content; ?>

Comment: Easy enough then. You want to look into http://api.drupal.org/api/function/hook_page_alter - You can strip out whatever is needed and it will never make it to the page template.
Comment: I think you all misunderstood my question, i want to override page.tpl with only $content, Not how to create a tpl using hook_theme!
Comment: Updated to let template be loaded from module directory instead of needing to copy to theme.
Answer: I think that you can use the same hook MODULENAME_preprocess_page but you need to register your template file using hook_theme read more about it here
I didn't do it before but I think it works that way. A quick search returns this which may help.
Comment: we can use same thing in .module but the problem is if it should work , this popup.tpl must be in my active theme folder
Answer: Finally found solution
/**
 * Implements hook_theme_registry_alter().
 */
function MODULE_theme_registry_alter(&$theme_registry) {
  // get tpl path in my custom module.
  $mod_path = drupal_get_path('module', 'MODULE') . '/tpl';
  $theme_registry_copy = $theme_registry; // Munge on a copy.
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  $hooks = array('page');
  foreach ($hooks as $h) {
    if (is_array($theme_registry[$h]['theme path'])) {
      $first_element = array_shift($theme_registry[$h]['theme path']);
      array_unshift($theme_registry[$h]['theme path'], $first_element, $mod_path);
    }
  }
}

Answer: Just to add to the answers. If all you want is to output the node content (or any content) without going through Drupal templating engine, there is a much simpler way.
function <MODULE_NAME>_menu() {
    $items = array();

    $items['some_path/%node'] = array(
        'page callback' => '_output_content', // Name of the function to call
        'page arguments' => array(1),
        'access callback' => 'node_access',
        'access arguments' => array('view', 1)
    );

    return $items;
}

function _output_content($node) {
    $node_view = node_view($node);
    print drupal_render($node_view);

    exit;
}

NOTE: Replace "<MODULE_NAME>" with your module name, replace "some_path" with the path that you want to use with your service (you can check it with http://<YOUR_DRUPAL_SITE>/some_path/1234 ), and choose a good name for your callback function, something better then "_output_content", something that has less chance to clash with other module. It's a good practice to use your module name as a prefix.
You can also output arbitrary text content:
function _output_content($node) {
    print('Hello');

    exit;
}

Or even output JSON:
function _output_content($node) {
    drupal_json_output(array(
        'key' => 'value'
    ));

    exit;
}


Setting background colour of a column depending on time using JS

Question: I have five columns each with a different time, I want to highlight the column which is before the time in the next column. They are all in time order, from earliest to latest.
To put this into context, column A has a time of 8AM, column B has a time or 12PM, column C has a time of 3PM, column D has a time of 6PM, and column E has a time of 9PM. So, if the current time was 2PM, column B should be highlighted until the time is 3PM, where column C becomes highlighted.
Each column is defined using a class, and each time is retrieved from a JSON file.
It's my understanding that I would have to use getElementsByClassName and iterate over the collection, as each result would yield a collection. However, this would target all the columns, rather than just a specific one.
This is what I have so far in terms of my JavaScript code. Note, I am not using jQuery.
Javascript
var h = addZero(currentDate.getHours());
var m = addZero(currentDate.getMinutes());
var s = addZero(currentDate.getSeconds());
var time = h + timeSeparator + m + timeSeparator + s;

if (time >= timetables[i].sunrise || time >= timetables[i].lunchtime) {
        var cols = document.getElementsByClassName('column');
            for (var i = 0; i < cols.length; i++) {
                cols[i].style.background = '#ba4346';
            }
        }

HTML

Sunrise

undefined

Lunchtime

undefined

Comment: what is all the addZero and timeSeparator stuff? is time a String? if so, you won't be able to compare it with a time (assuming that is what is in `timetables`) with `>=`. Could you post your html as well?
Comment: @thedarklord47 that just creates a time string such as 00:58, and yeah I'll update the post with that now.
Comment: so the `` with `class="time"` is where the time string is inserted (in place of undefined)?
Comment: If all you care about is the hour you can use `var hour = new Date().getHours()` which, right now, gives me `17` since it's 5:12pm in my time-zone. Prefixing with 0 turns a number into a string — numbers are easier to work with when comparing values, so no need to _addZero()_.
Comment: @thedarklord47 Sort of. "sunrise-time" would the ID that is targeted. Like this `for (var i = 0; i < timetables.length; i++) { if (timetables[i].date == dateFormatted) {
            document.getElementById("sunrise-time").innerHTML = timetables[i].sunrise;`
Answer: You can use .getHours() function
Just create a new variable date and than use .getHour() on it to get the value of the hour.
var d = new Date();
var h = d.getHours();
// and you have the current hours stored in a variable named h;

// now you can compare the hour with whatever you want and do whatever you want, e.g:
if (0 <= d <= 6 || 18 <= d <= 23) {
  alert("it's night.");
} else {
  alert("it's day.")
};

//changing background:
if (0 <= d <= 6 || 18 <= d <= 23) {
  document.getElementById("columnId").style.background = "blue";
} else {
  document.getElementById("column2Id").style.background = "yellow";
};

Tell me if you have problems and on what you have.
If you need to manipulate the DOM I really suggest you to use JQuery it's much easier, and it's just an HTTP request more than using normal JavaScript.
Answer: Basically you need to have a way of "checking the time" that is currently in each column.
var cols = document.getElementsByClassName('column');
for(var i=0; i<cols.length; i++){
    //get the string from each column
    var colTime = cols[i].children[2].innerHTML
    if (colTime < currTime){
        cols[i].style.background = '#ba4346';
    }
}

This will not work as is, because your time is displayed as a funky string. If you have access to the JSON object that you use to populate the columns, that would work alot better.
That way, rather than doing the funky innerHTML thing to pull your data out, then decode it, then do the comparison, you would just do something like this:
var cols = document.getElementsByClassName('column');
for(var i=0; i<cols.length; i++){
    if (jsonColumnData[i] < currTime){
        cols[i].style.background = '#ba4346';
    }
}

Much better.
Comment: Hmm, I see your point about the funky formatting. So what you're suggesting is, format the time correctly (e.g. 15:32, rather than 3:32 PM) in the JSON file then loop over it like you suggested above. Would there be anyway of formatting the text afterwards? I'd much prefer it if the time column read as "2:20 PM" than "14:40".
Comment: Okay so I've made use of the Moment.js library in order to format the dates in the columns from epoch time to a string, vs. what I was doing previously with the funky formatting. Here's a link to a [pastebin](http://pastebin.com/kzp3x35S). This doesn't seem to change the colour of the column though. :(
Comment: use my second suggestion. in the json, keep the time in an easy to compare format (i.e. Moment.js). That way you can use my second code snippet to compare each columns json data to the current time and color your columns accordingly.
Comment: I tried that but it didn't seem to work. I've figured out a less elegant solution which I've posted as an answer. Feel free to have a look and make any suggestions. Thanks for the help!
Answer: After much tinkering, I've managed to work out my own solution.
For each column, I assigned a div ID which allows each column to be targeted individually.

Sunrise

undefined

I converted all the non-standard time formats in each array in my JSON file to Epoch times. Following this, I wrote if statements for each column ID, checking whether or not the time is greater than or equal to the epoch time assigned in the JSON file.
if (time >= timetables[i].sunrise) {
    document.getElementById("sunrise").style.background = red;
    document.getElementById("sunset").style.background = "none";
}

In order to retain the easy to read time formatting in the columns v.s. epoch times, I used the moment.unix method to format the epoch times to a human readable one.
Maybe not the cleanest solution, but it seems to work well. Suggestions welcome.
Comment: this is essentially what I was proposing in my answer. Use epoch time in your JSON, then compare that to the current time. I would suggest selecting by class and doing this comparison in a loop though. The individual ID thing is very fragile/rigid.


Detectar ou bloquear redirecionamento com ajax?

Question: Estou tento um problema numa requisição ajax que estou fazendo.
A url requisitada é uma url x, porém, quando faço a requisição, ela me redireciona para uma url y.
Estou usando a função $.ajax do jQuery.
Gostaria de saber se tem como detectar pelo jQuery que a url requisitada sofreu um redirecionamento. Ou interromper esse redirecionamento, informando um erro.
Como o redirecionamento não conta como erro, está dando problema na forma com que trato os dados, quer dizer, mesmo com o redirecionamento, a requisição chama o success.
Comment: Possui algum código de exemplo, amigo? Fica um pouco difícil compreender o seu cenário com exatidão
Comment: @WallaceMaxters, acredito que não seja possível detectar se o servidor redirecionou a sua requisição AJAX, o que pode ser feito é adicionar um Header no servidor informando a URL processada, então você compara este header com a url enviada...
Comment: Nossa @VictorAlencarSantos precisa ser mais específico? Como vou demonstrar um redirecionamento com código? Tudo que pude explicar já está na pergunta
Comment: Um jeito de driblar isso é enviar a requisição ajax para o seu proprio servidor. Então no lado server o CURL faria a requisição. A lógica nisso é que o CURL detecta redirecionamentos. O problema é o consumo de tráfego de dados e processos no servidor só para fazer isso. Mas, de qualquer forma, se for algo tão importante, está aí uma gambiarra funcional.
Comment: @DanielOmine é uma jogada boa. Mas no meu caso fazer isso daria quase que na mesma, seria o sistema fazendo requisição para o mesmo sistema para depois retornar para o cliente.
Answer: Não posso fornecer uma resposta detalhada agora, mas posso dizer que é impossível detectar em Ajax ou requisições normais o redirecionamento, o único que sabe que houve redirecionamento é a interface de requisições interna do navegador.
Seria algo como:

Interface do usuário:
É a camada renderizada, aonde já tem a resposta pronta ou parcial, a tela do navegador (conhecido como webView)
Interface de requisições e respostas:
É uma interface interna que responde somente ao browser e gerencia todas requisições HTTP, fica responsável por resolver um servidor, enviar a requisição para o mesmo e pegar a resposta, em caso de redirecionamento ele envia uma nova requisição.
Servidor HTTP:
É um site, domínio, local ou não que é acessível através de um endereço e suas respostas são headers seguidos de textos ou dados binários que "nada fazem" (pois o responsável por interpretar isto é a interface de requisições e respostas).

Quando ocorre um redirecionamentos 301, 302, etc, quem vai gerenciar isto é a Interface de requisições e respostas, a única ferramenta que enxerga isto é o depurador do navegador (no Chrome aperte o F12 do teclado que irá exibir o depuradir).
Como resolver
A única maneira é mudar a abordagem, ou seja ao invés de redirecionar no back-end, mudar para o front-end e fazer algo semelhante ao que colocou na sua própria resposta, respostas json ou xml com "comandos" que dizem o que fazer e até criar seus próprios códigos de erro customizados, assim:

Exemplo de código de erro (as resposta HTTP sempre será 200 Ok)
{ "status": 5000, "message": "Erro na requisição" }

Exemplo de código de sucesso
{ "status": 1000, "message": "Cadastrado com sucesso" }

Exemplo de código de redirecionamento no front-end
{ "status": 9000, "message": null, "url": "/path/route" }

O código ficaria algo como:
var request = $.ajax({
  url: "/route/page",
  method: "GET",
  data: { id : 1 },
  dataType: "json"
});

request.done(function(data) {
     if (data.status === 9000) {//Detecta redirecionamento
        window.location = data.url; //Redireciona (se quiser :) )
     } else {
        //...Código segue fluxo normal
     }
});

request.fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});

Nota: Penso que talvez você tenha pensando em fazer uma requisição no servidor, até funcionaria, mas acho que além de ser mais uma gambiarra, seria bastante custoso para o servidor conforme aumentasse o numero de usuários acessando ao mesmo tempo
Comment: Never gambiarra in my code
Comment: @WallaceMaxters só o meu desenho que não ficou bom, mas no fim de semana eu faço um "mais correto" :)
Answer: Fui atrás de uma fonte para ver se posso resolver não só o meu problema.
Todo redirecionamento, geralmente trás como código de resposta 301 e 302. Quando a resposta retorna correta o status é 200.
Estou falando para entenderem o que encontrei nessa resposta no SOEN.

Na verdade, você não tem a capacidade de detectar se uma resposta 302
  ocorreu. Se o redirecionamento 302 leva a um 200, então o seu programa
  atua de forma idêntica como se o pedido inicial levou diretamente a um
  200.

Ou seja, o ajax é "enganado", por assim dizer, por um redirecionamento, atuando como se a redirecionamento fosse um comportamento esperado para retornar sucesso na requisição XHTTPRequest.
O máximo que pode ser feito nesse caso é: Se você requisita uma url x esperando receber dados json por exemplo, e é redirecionado para uma url y, como é o meu caso, você pode tratar isso verificando se encontrou os dados esperados pelo json na sua chamada de sucesso da requisição ajax.
Exemplo:
URL X
 {"message":"Cadastrado com sucesso"}

URL Y é a página inicial da minha aplicação
Requisição AJAX
$.ajax({
     url: '/x',
     success: function (response)
     {
           if (response.message) {
               return alert('Dados esperados foram retornados');
           }

           alert('Ocorreu um erro! Dados incosistentes')
     }
})

Comment: Não é que o ajax é enganado, é que faltou (desculpe a sinceridade) você entender a camada da Resposta no navegadores, os navegadores é que recebem a resposta em um nivel mais profundo e só entregam a tela a resposta final. Ajax é nada mais que uma requisição normal em uma camada aonde o javascript poderá controlar e setar em variáveis valores de respostas. Se notar mesmo em requisições normais (sem ajax) você não irá conseguir detectar o redirecionamento. O que falta é entender é a camada http para o usuário final :)
Comment: isso que você postou não é a solução do problema descrito por você.
Comment: Ninguem está discutindo, estamos vendo a melhor solução.
Comment: Solucionou o meu problema.
Comment: O ajax "é enganado" foi apenas uma expressão tosca. Eu entendo como funciona as paradas (quando abrimos o console do chrome dá pra ver que a url é redirecionada 3 vezes). Se o ajax vai pegar a resposta final, então obviamente, se não ocorrer um erro na resposta final, retornará ok


Get string of not matching items in list

Question: I'am comparing 2 List<string> wether the first list does contain an string that is not on the second List
This code works fine:
var onlyInXML = xmlList[i].columns.Except(rowAndTables[xmlList[i].table]);
                        if (onlyInXML.Any()) {
                            //Console.Write the not matching item here
                        }

I want to get the string, which is not matching. how do i do that ?
Comment: Hi @NameGuy, can you please provide us input data and expected output
Comment: Just two List Lists.. i expect a string.
Comment: What do you mean by **not matching**?
Comment: @Ammar if list1 does contain an string, which is NOT is list2.
Comment: `Except` function will return an `IEnumerable` that contains all entities that are in its first `IEnumerable` and not in its second `IEnumerable`, so `onlyInXML` is of type `IEnumerable` not a `string`, if you want to build a `string` out of it, you can use [Aggregate](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate) function
Comment: refer: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except?view=netframework-4.8
Answer: This way:
List<string> listOfStrings1 = new List<string>() { "abc", "def", "ghi", "lmn" };
List<string> listOfStrings2 = new List<string>() { "abc", "def", "lmn" };
List<string> listOfNotContainedStrings = listOfStrings1.Where(x => listOfStrings2.Contains(x) == false).ToList();

Comment: `.Where(x => !listOfStrings2.Contains(x))`
Comment: `.Except(listOfStrings2).ToList()` ??
Comment: @Prasad Telkikar: `Except` has a side effect: it *removes duplicates*, e.g. `new [] {"A", "A", "B", "C"}.Except(new [] {"C"})` will return `{"A", "B"}`; please, note that *second* (duplicate) `"A"` is removed
Comment: @DmitryBychenko, thanks for your comment. Today I learnt alternative of `Except()` where I need keep duplicates.


Find recursive formula for special function

Question: Kind of a strange question I know, but here goes:
We are given a string of letters $T$ without any gaps or commas, just letters. Depending on what $T$ is, it could be broken down to form a valid english sentence, or maybe it can't.
For example, if $T=$"HellomynameisOria" then it could be broken down to form "Hello my name is Oria".
If however $T=$"apxlrt" then it can't be broken down to form a meaningful sentence no matter how you slice it.
Let $a_1a_2a_3...a_j$ be a substring of $T$. $C(j)$ is a function that returns $1$ if $a_1a_2...a_j$ can be broken down to a meaningful sentence, and $0$ otherwise.
For example, suppose $T=$"Therearesomegoodthings" then $C(1)=0$, $C(2)=0$, $C(3)=1$,$C(4)=0$,$C(5)=1$ etc...
$C(3)=C(5)=1$ because the words "The" and "There" are valid english words, however $C(2)=0$ because "Th" is not a word.
Given a function $dict(W)$ which returns $1$ if $W$ is a valid english word and $0$ otherwise, find a recursive formula for $C(j)$.
Please note that when I say valid sentence, I mean each word in the sentence is a valid english word (meaning $dict(W)=1$). The sentence itself does not have to make sense. For example "the are you me pizza computer chair" is a valid sentence.
What I did:
I haven't made much meaningful progress. I know that $C(1)=dict(a_1)$ but from there it gets tricky. $C(2)=1$ only if $a_1$ is a word and $a_2$ is a word, or $a_1a_2$ is a word. And when you add $a_3$ it gets even worse.It's a very subtle connection between $C(j)$ and $C(j-1)$.
Edit:
I managed to come to a meaningful observation, but still no mathematical formula.
Consider the string "Thedoorisope". It has $12$ letters and can't be broken down to a sentence. so $C(12)=0$. But if we add the letter "n" then we get "Thedoorisopen" which can be broken down, so $C(13)=1$. This is because "Thedooris" is a valid sentence, so $C(9)=1$, and the word "open" is a word.
In other words, $C(j)=1$ if $C(k)=1$ and $dict(a_{k+1}...a_j)=1$.
Answer: As you say, $C(j)=1$ iff there is a $k<j$ such that $C(k)=1$ and $\operatorname{dict}(a_{k+1}\ldots a_j)=1$. This is the case iff there is a $k<j$ such that $C(k)\operatorname{dict}(a_{k+1}\ldots a_j)=1$. That product is always $0$ or $1$, so
$$C(j)=\max_{0\le k<j}\big(C(k)\operatorname{dict}(a_{k+1}\ldots a_j)\big)\;,$$
where we define $C(0)=1$. (That's to cover the case in which $a_1\ldots a_j$ is a word.)
Comment: That seems to be correct. Thank you.
Comment: @Oria: You're welcome. However, I just realized that it's not quite right: the summation should be a maximum. I'm about to fix it. (The problem is that the string may have more than one decomposition as `sentence` plus `word`: e.g., it might be `into`, which is a word as it stands *and* the 'sentence' `in to`.
Comment: True. $C(j)$ can only be $0,1$ and if you sum it, since we can have multiple breakdowns, the sum could be higher than one, which would be invalid.


Repeated coin flip experiments: what counts as a sample?

Question: Apologies if this is a little confusing. If anything needs clarifying, I'll edit the question as best I can. Thanks.

If we take a sample of, say, 100 people, we could measure their heights, and find the mean and standard deviation. We can calculate an estimate of the standard error from this single sample to find where the population mean is likely to lie.
If we repeated this sampling and measured further samples of 100 people from the
population, then finding the means for each sample would give a sampling distributions of means. The mean of this sampling distribution estimates the population mean, while the standard deviation of this sampling distribution also estimates the standard error.
This all seems fairly clear.

Now, consider a large number of trials, e.g. 20000 trials of 100 coin flips, where the number of heads in each trial is recorded and the fraction of heads obtained in each trial found. To me, it seems less obvious as to what constitutes a sample here.
Would each one of these 20000 trials be considered as a single sample, so that we have 20000 samples?
If that's right, then when we average the fractions of heads found over all 20000 trials, then — just as for the height example — the mean is an estimate of the population mean, and the standard deviation would be an estimate of the standard error.
The alternative I'm thinking of would be to treat each set of 100 coin flips as a single data point, which would give a single large sample of 20000 measurements.
Treating this data as 20000 individual samples does seem like it should be correct since it's analogous to the height example. However, it doesn't seem immediately intuitive to me. Maybe this is because each trial results in a single fraction value, instead of dealing with the 100 individual flips of each trial. So, thinking of the result of each trial as a individual sample mean seems less obvious here, as the trial effectively yields a single value. On the other hand, I can see that the fraction of heads is effectively a mean value, where we code heads as 1, tails as 0 and then divide by the total number of flips in a trial.
What confuses me further is if we then decide to work with the raw number of heads found in each trial instead of the fraction of heads. The total number of heads in a trial is a single value, rather than a mean. However, my thinking is that the same would be true: the mean of the 20000 raw numbers of heads would be an estimate of the population mean, and that the standard deviation would estimate the standard error of the mean. I'm not sure if or why this would be the case though.

Edit: Really, I think what I'm trying to understand about this:

If I take repeated trials of a fixed number of flips and compile the fraction of heads, do these give a distribution of sample means? I think from Michael Chernick's answer that this is correct.
Next, if we look at the distribution of the raw scores of heads obtained in the repeated trials of a fixed number of flips, can this be again considered as a distribution of sample means? This is exactly the same as in 1, except the measured values are multiplied by the sample size. Because of this, I assume the answer is yes, but it just seems a little dissonant. When you reframe the data like that, you're using a total value, rather than the mean number of heads (the mean being equivalent to the fraction of heads).
Comment: I am not sure I understand what you are asking, but one possible help is that 100 people are, presumably, a sample from some defined population of people. What is the population of coin flips? If you can't define a population, I don't see how you can define a sample from it.
Comment: It's not really the coin experiment itself that it's important; I'm just trying to make sure that I've got ideas of standard deviations and error down.

It doesn't need to be coin flips, I could equally pose the question in terms of anythig with a binary outcome, e.g. yes/no survey of samples of a finite population.
Answer: What confuses me about your question is what is you objective?  Are you trying to estimate a single proportion or determine the sampling distribution for a proportion estimate when the sample size is 100?
1. What to do if you want to estimate a single proportion.
If your objective is to get a point or interval estimate for a single proportion, then since each sample fo size 100 is independently chosen from a single population you can pool the data to get a best estimate for teh parameter.
2. If you want to know the sampling distribution empirically from independent samples of size 100
Compute the 20000 estimates and use that that discrete distribution as an approximation to the sampling distribution.
Answer: The answer to both of your questions (at the end of your post) is yes--they just represent sample means of different random variables. In the first case you are sampling a Bernoulli($p$) random variable with a sample size of $N$, and taking the mean. In the second case you are sampling a Binomial($N$,$p$) random variable with a sampling size of one and taking the mean. In both cases it's fair to talk about the distribution of the sample mean, though the second case is kind of trivial (because the sample size is 1).
Answer: In the way you have defined it, you would have 20000 samples.
There is a discrete sample space describing all possible outcomes of 100 coin flips.
Each time you flip 100 coins, that's an observation (though this is perhaps semantically counter-intuitive).
All of the observations constitute the sample.


Export MySQL tables into Microsoft SQL server

Question: I have an existing database in MySQL, now I need to export that database and import it into MS SQL management.
I tried generating the SQL, and executing in MS SQL Management Studio but it has errors.
anyone a clue how to import?
edit:
in phpmyadmin I selected the tables I wanted, went to export, exported as SQL.
in MSSQLMS selected created database>execute query. pasted the SQL file contents, executed it. result= loads of syntax errors
Comment: @Larnu edited it
Comment: Download and use the [SQL Server Migration Assistant](https://learn.microsoft.com/en-us/sql/ssma/mysql/getting-started-with-ssma-for-mysql-mysqltosql?view=sql-server-2017). [Here](https://learn.microsoft.com/en-us/sql/ssma/mysql/converting-mysql-databases-mysqltosql?view=sql-server-2017) is a link to the steps to follow for the conversion.
Answer: To convert MySQL database objects, you first select the objects that you want to convert, and then have SSMA perform the conversion. To view output messages during the conversion, on the View menu, select Output.
To convert MySQL objects to SQL Server

In MySQL Metadata Explorer, expand the MySQL server, and then expand Databases.
Select objects to convert :

To convert all schemas, select the check box next to Databases.
To convert or omit a database, select the check box next to the Database name.
To convert or omit a category of objects, expand a schema, and then select or clear the check box next to the category.
To convert or omit individual objects, expand the category folder, and then select or clear the check box next to the object.

To convert all selected objects, right-click Databases and select Convert Schema.

You can also convert individual objects or categories of objects by right-clicking the object or its parent folder, and then selecting Convert Schema.


$f$ is increasing and bounded, $f$ is differentiable. Show that $\int_a^b f'(x)dx=f(b)-f(a)$.

Question:
$f$ is increasing and bounded, $f$ is differentiable. Show that $\int_a^b f'(x)dx=f(b)-f(a)$.

Here the $\int_a^b$ is in the Lebesgue sense. How to prove it? By Lebesgue theorem, we only have $\int_a^b f'(x)dx \leq f(b)-f(a)$. How to use the assumption $f$ is differentiable? We have no assumption on the Riemann integrability of $f'$, but only have the Lebesgue integrability of $f'$!
Comment: @Surb The Cantor function is not differentiable everywhere...
Comment: The statement is wrong : for example [Cantor function](https://en.wikipedia.org/wiki/Cantor_function).
Comment: You should precise it in your post, because working with Lebesgue integrale normally implies that you work with class of function rather than functions...
Answer: $\int_a^{b} f'(x)dx \leq f(b)-f(a) <\infty$ and $f'\geq 0$. Hence, $f$ is differentiable (at every point) with its derivative in $L^{1}$. This implies that $f$ is absoluetly continuous and $\int_a^{b} f'(x)dx = f(b)-f(a)$. This non-trivial result is proved in Rudin's RCA.


Help me prove the result of this limit: $\lim_{x\to \infty} {\log_{x^3+1} (x^2+1) \over \log_{2e^x+1} (x^2+5x)}$

Question: The limit is
$$\lim_{x\to \infty} {\log_{x^3+1} (x^2+1) \over \log_{2e^x+1} (x^2+5x)}$$
I know that it should be equal to  $\infty$ but i have yet to prove it. Please help me do so.
Answer: Hint 1: $\displaystyle \log_a b = \frac{\ln b}{\ln a}$. So $$\frac{\log_{x^3+1} (x^2+1)}{\log_{2e^x+1} (x^2+5x)} = \frac{\frac{\ln (x^2+1)}{\ln (x^3+1)}}{\frac{\ln (x^2+5x)}{\ln (2e^x+1)}} = \frac{\ln (x^2+1) \ln (2e^x+1)}{\ln (x^3+1) \ln (x^2+5x)}$$
Hint 2: For very large $x$, $x^2+1 \approx x^2$ and $x^3 + 1 \approx x^3$. So our equation becomes $$\frac{\ln (x^2+1) \ln (2e^x+1)}{\ln (x^3+1) \ln (x^2+5x)} \approx \frac{\ln (x^2) \ln (2e^x+1)}{\ln (x^3) \ln (x^2+5x)} \approx \frac{2\ln (x) \ln (2e^x+1)}{3\ln (x) \ln (x^2+5x)} \approx \frac{2}{3} \frac{\ln (2e^x+1)}{\ln (x^2+5x)}$$
Can you take it from here now?
Comment: Thank you but i have done that. It's from here on that i can't do.
Comment: @user115947 - check the edit.
Answer: After getting to where 2012ssohn got, you might want to factor $2 e^x+1$ into $e^x\left(2+\frac{1}{e^x}\right)$ and do the same in the denominator...


Nameserver Checker

Question: I've got Bind running on a server and although access to the domains I've set up is correct. I was wondering if there was an online (or offline) tool to check if I had setup the service correctly?
Regards
Steve Griff
Answer: Bind include a set of tools for testing configuration and zone files.
The man pages of named-checkzone and named-checkconf should give you all the informations you may need.
Comment: That'll tell you if you've got the zones and server itself configured correctly, but it won't tell you if anyone on the internet will get the data, or if you've made a syntax error in the records that is "valid" but not what you mean, such as a missing trailing period.
Comment: @chris: indeed, it will only tell you if you have "setup" the service correctly, as asked by Steve.
No one except you can tell if there is a typo in a record. Your only way to find out it to check the content of the zone files.
Answer: Ask a public recursive server for the records.
For example, if I just setup some record for randomtest.example.com on my server that's authoritative for example.com,
host -t any randomtest.example.com. [188.8.131.52][1]

will tell me if it is getting out to other nameservers on the internet.
Answer: Many good Web tools (and a lot of bad ones):

http://www.zonecheck.fr/ (also available as a local command-line tool, free software)

http://dnscheck.iis.se (with DNSSEC)

http://dnsviz.net/ (specially for DNSSEC)

http://www.infoblox.com/services/dns_advisor_tool.cfm (requires your email address)
I wrote a paper summarizing the tools, the good and the bad:
http://www.bortzmeyer.org/tests-dns.html
Answer: ZoneCheck is available online or for download http://www.zonecheck.fr/
Answer: http://www.intodns.com is a good free online tool.
Comment: I like this. Gives an informative, easy to read report on the DNS.
Comment: Fails on IPv6 name servers (in 2010!), warns when there is only one MX record (they don't know the difference between email and the Web?). Poor service, IMHO.
Comment: @bortzmeyer: you must admit that IPv6 isn't mainstream yet. As for the MX record, don't you think that it's normal to *warn* the user if a domain has less than 2 MX records? By the way what's the difference between email and the web and how can a DNS checking service tell the difference?
Comment: The difference is that the Web is synchronous (you query a server, it must be available and reply immediately) while the mail is asynchronous (if the downstream MTA is not available, the upstream MTA queues and retries later). So, no, I don't agree, the vast majority of domains should have only one MX (gmail.com is of course a different case...)
Comment: @Cristian Ciupitu Regarding IPv6, the problem is not that these services do not have IPv6 support (which would be understandable).The problem is that they FAIL when they encounter an IPv6 name server (marking the server as invalid)  instead of simply ignoring it (as an IPv4-only DNS resolver would do). For instance, an option "Transport layer" of Zonecheck allows you to disable IPv6 and, in that case, IPv6 name servers are simply ignored.
Comment: @bortzmeyer: that would be a valid issue indeed, but as I've said before IPv6 is still not mainstream; I don't think that many people are affected by it.
Answer: You can issue direct queries to your server using host/dig to test Bind configuration:
host -t soa yourdomain.com server_ip # fetch SOA record
host -t ns yourdomain.com server_ip  # fetch NS records
host -t mx yourdomain.com server_ip  # fetch MX records
host yourdomain.com                  # fetch A record

or just
host -t any yourdomain.com server_ip # fetch all

I do recommend you to run tests from another machine to detect problems with firewall,
interface binding, etc. If you don't want to muck with command line just use one of the online tools.
http://www.dnsinspect.com it's an another online DNS testing tool.

Nameserver Checker


SQL JOINS: Why does Sqlite3 JOIN USING gives a correct answer but JOIN ON does not?

Question: I'm expecting to see Sally Smith listed with CityName equal to 'Kansas City' which I do get when using JOIN USING but I don't get when using JOIN ON.
Am I doing something wrong here?
sqlite> select Customer.*, City.* from Customer inner join City USING(CityId);

CustomerId  CityId      CustomerName  CityId      CityName
----------  ----------  ------------  ----------  -----------
1           1           Bob Smith     1           Kansas City
2           1           Sally Smith   1           Kansas City
3           2           Tom Smith     2           New York
5           2           Bob McKenner  2           New York

sqlite> select Customer.*, City.* from Customer inner join City on Customer.CustomerId=City.CityId;

CustomerId  CityId      CustomerName  CityId      CityName
----------  ----------  ------------  ----------  -----------
1           1           Bob Smith     1           Kansas City
2           1           Sally Smith   2           New York
3           2           Tom Smith     3           Houston

sqlite> select * from Customer;

CustomerId  CityId      CustomerName
----------  ----------  ------------
1           1           Bob Smith
2           1           Sally Smith
3           2           Tom Smith
4                       Mary Smith
5           2           Bob McKenner

sqlite> select * from City;

CityId      CityName
----------  -----------
1           Kansas City
2           New York
3           Houston
sqlite>

Answer: You are joining on the wrong columns:
select Customer.*, City.* from Customer inner join City
on Customer.CustomerId=City.CityId;

change it to:
select Customer.*, City.* from Customer inner join City
on Customer.CityId=City.CityId;

Comment: Fine if it is solved and don't forget to accept the answer.


Saving form field data (string) in database column

Question: I'm having problems while submitting the form and saving the filled fields within my database. Actually, this is happening just for one of my fields (model.CampoExtra), which in this case is a multiple select dropdowlist (lPagamentos). I need to save the keys of user selected items in my database, but when the user select more than one item I'm saving just a single key(the first one) and losing the rest of them.
The string containing the selected keys has this format 'key1,key2,keyN, ....'. The column in question that must receive these values has enough size, it was declared as [varchar] (80), so I really do not understand where I'm missing. I'll share sample of the code and hopefully someone can point out a mistake.
Sample of Form code (View)
@{

    List<SelectListItem> lPagamentos = new List<SelectListItem>();

    DropDownList DDList = new DropDownList();

    lPagamentos = DDList.GetListaCampoExtraFormasPGTO();

}

<link href="~/Content/CSS/select2.css" rel="stylesheet" />

Cadastro de Mensagens

        @using (Html.BeginForm(Acao, "SMS", FormMethod.Post, new { id = "FRMSms" }))
        {
            @Html.AntiForgeryToken()

Preencha com as informações do formulário!

                    @Html.HiddenFor(model => Model.MensagemID)
                    <input type="text" id="TotalFP" name="TotalFP" value="@ViewBag.TotalFP" />
                    ****

                    @if (Area == "MAS")
                    {

                            @Html.LabelFor(model => model.EmpresaID, htmlAttributes: new { @class = "control-label" })
                            @Html.ValidationMessageFor(model => model.EmpresaID, "", new { @class = "text-danger" })
                            @Html.DropDownListFor(model => model.EmpresaID, (List<SelectListItem>)lEmpresas, " - SELECIONE - ", new { @class = "form-control" })

                    }
                    else
                    { @Html.HiddenFor(model => model.EmpresaID)}

                        @Html.LabelFor(model => model.Tipo, htmlAttributes: new { @class = "control-label" })
                        @Html.ValidationMessageFor(model => model.Tipo, "", new { @class = "text-danger" })
                        @Html.EditorFor(model => model.Tipo, new { htmlAttributes = new { @class = "form-control", placeholder = "Tipo" } })

                        Descrição 120 caracteres restantes.
                        @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control", maxlength = 120 } })

                        Mensagem 155 caracteres restantes.
                        @Html.ValidationMessageFor(model => model.Texto, "", new { @class = "text-danger" })
                        @Html.TextAreaFor(model => model.Texto, new { @class = "form-control", maxlength = 155 })

                        Formas de Pagamento - <input type="checkbox" id="chkTodos" /> Selecionar todos
                        <input type="hidden" id="PgtoID" name="PgtoID" />
                        @Html.DropDownListFor(model => model.CampoExtra, (List<SelectListItem>)lPagamentos, new { @class = "form-control mySelect2", name = "CampoExtra", multiple = "multiple", style = "width:100%;" })

                        @Html.LabelFor(model => model.Situacao, htmlAttributes: new { @class = "control-label" })
                        @Html.ValidationMessageFor(model => model.Situacao, "", new { @class = "text-danger", maxlength = 1 })
                        @Html.DropDownListFor(model => model.Situacao, (List<SelectListItem>)lSituacao, " - SELECIONE - ", new { @class = "form-control" })

                        Cadastro
                        <input id="Cadastro" name="Cadastro" tabindex="-1" type="text" readonly class="form-control" value="@Cadastro" />

                    <input type="submit" value="@ViewBag.Label" class="btn btn-primary"> | @Html.ActionLink("Cancelar", "../Sms/", new { id = "", acao = "" }, new { @class = "btn btn-primary" })

        }

Controller
public ActionResult CadastrarSMS(Sms_Mensagens SmsMensagem)
        {
            bool IsLogado = (Session["IsLogado"] is null);
            if (IsLogado)
            {
                return RedirectToAction("Login", "User", new { acao = "ErroSessao" });
            };
            if (!ModelState.IsValid)
            {
                return View("FormSms", SmsMensagem);
            }

            int MensagemID = SmsMensagem.MensagemID;

            if (MensagemID == 0)
            {
                DBCtx.MensagensDB.Add(SmsMensagem);
            }
            else
            {
                DBCtx.Entry(SmsMensagem).State = EntityState.Modified;
            }

            DBCtx.SaveChanges();

            ViewModelSucesso ViewMS = new ViewModelSucesso();
            ViewMS.Controller = "SMS";
            ViewMS.View = "Index";
            return View("Sucesso", ViewMS);

        }

        public ActionResult FormSMS(int id = 0, string acao = "")
        {

            bool IsLogado = (Session["IsLogado"] is null);
            if (IsLogado)
            {
                return RedirectToAction("Login", "User", new { acao = "ErroSessao" });
            };
            ViewBag.Id = id;
            ViewBag.Acao = acao;

            ViewBag.Label = "Cadastrar";
            if (acao == "Editar") { ViewBag.Label = "Atualizar"; };
            if (id == 0)
            {
                ViewBag.EmID = 0;
                ViewBag.FiID = 0;
                return View();
            }

            Sms_Mensagens SmsMensagem = DBCtx.MensagensDB.Find(id);
            ViewBag.EmID = SmsMensagem.EmpresaID;

            if (SmsMensagem == null)
            {
                return View();
            }
            return View(SmsMensagem);
        }

Model
public class Sms_Mensagens
    {

        [Key]
        [Display(Name = "ID Mensagem")]
        public int MensagemID { get; set; }

        [Display(Name = "Empresa")]
        public int EmpresaID { get; set; }

        public string Tipo { get; set; }

        [Required(ErrorMessage = " - Preencha a descrição da mensagem!")]
        [Display(Name = "Descrição (até 120 caracteres)")]
        public string Descricao { get; set; }

        [Required(ErrorMessage = " - Descreva o texto da mensagem")]
        [MaxLength(155, ErrorMessage = " - O texto deve conter até {1} caracteres.")]
        [Display(Name = "Mensagem (até 155 caracteres)")]
        public string Texto { get; set; }

        [Required(ErrorMessage = " - Selecione uma ou mais areas!")]
        [Display(Name = "Areas")]
        public string CampoExtra { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}", ApplyFormatInEditMode = true)]
        public DateTime Cadastro { get; set; }

        [Required(ErrorMessage = " - Selecione a Situação")]
        [Display(Name = "Situação")]

        public string Situacao { get; set; }
        public virtual Empresas Empresas { get; set; }

    }

public List<SelectListItem> GetListaCampoExtraFormasPGTO()
        {
            List<SelectListItem> Lista = new List<SelectListItem>();
            var data = new[]{
                new SelectListItem{Value = "CC", Text = "CARTÃO DE CRÉDITO" },
                new SelectListItem{Value = "BB", Text = "BOLETOS" },
                new SelectListItem{Value = "DC", Text = "DÉBITO EM CONTA" },
                new SelectListItem{Value = "TE", Text = "TRANSFERÊNCIA ELETRÔNICA" },
                new SelectListItem{Value = "CE", Text = "CONTA DE ENERGIA" },
                new SelectListItem{Value = "CT", Text = "CONTA DE TELEFONE" }
            };
            Lista = data.ToList();
            return Lista;
        }

Comment: You have to make the CampoExtra field to string[] from string as suggested by Roman. You can also use MultiSelectList as described here https://www.mikesdotnetting.com/article/265/asp-net-mvc-dropdownlists-multiple-selection-and-enum-support
Answer: When your form is submitted, selected options from your CampoExtra dropdown are sent one by one. So the body of your request will contain something like this:
CampoExtra=key1&CampoExtra=key2&CampoExtra=key3

Your Sms_Mensagens.CampoExtra has a string type so it accepts a single string. Try to change this property to have IEnumerable<string> or string[] type. Of course, you'll have to join your selected options manually(string.Join(",", SmsMensagem.CampoExtra)) in order to save it as a single value in the DB.
Note that it might not be a good idea to store comma-separated values in one column(at least in the relational database), maybe it's better to propper normalize your tables.


SQL injection Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003 issue

Question: I got this news today about  SA-CORE-2014-005 - Drupal core - SQL injection.
We are not using drupal in build authentication. We have a custom authentication, which resides behind SSO and gateway. A user can only get access or even get access page if the user is the in SSO and Gateway servers.
Is this kind of setting also vulnerable to this attack, as access is not handled by drupal?
Answer: Yes, your site is vulnerable. If your network is stopping people accessing the Drupal site without prior authentication then you're (potentially) safe from those outside the network, but still vulnerable to those inside it.
As with all security issues, upgrade as soon as physically possible.
Comment: Hi Clive, The site is behind SSO one need to have access on SSO or Ldap to get access.
Comment: Yeah I over-simplified that a bit, just updated it
Answer: I have gone through this link about the vulnerability Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003 and suggest you to monitor your website for any backdoor attack as advised in the above link.
Consider changing your server location and all important passwords to remain in total safe area.


How can I use jQuery to style /parts/ of all instances of a specific word?

Question: Unusual situation. I have a client, let's call them "BuyNow." They would like for every instance of their name throughout the copy of their site to be stylized like "BuyNow," where the second half of their name is in bold.
I'd really hate to spend a day adding  tags to all the copy. Is there a good way to do this using jQuery?
I've seen the highlight plugin for jQuery and it's very close, but I need to bold just the second half of that word.
Comment: Rather than marking it strong, I would think you'd want to  it so you can apply CSS to mark it strong, blue, or whatever... not that that answers your jquery question ;-)
Comment: Yes, semantically **Now** is not strongly emphasised, unless you *really* shout "NOW!" when you say the company name! It's a typographical quirk, for which `` would be much more appropriate.
Comment: Have a look at [mark.js](https://markjs.io/) which will do it for you.
Comment: @SingleShot - agreed, a `` with a class will afford you more flexibility
Answer: To do it reliably you'd have to iterate over each element in the document looking for text nodes, and searching for text in those. (This is what the plugin noted in the question does.)
Here's a plain JavaScript/DOM one that allows a RegExp pattern to match. jQuery doesn't really give you much help here since selectors can only select elements, and the ':contains' selector is recursive so not too useful to us.
// Find text in descendents of an element, in reverse document order
// pattern must be a regexp with global flag
//
function findText(element, pattern, callback) {
    for (var childi= element.childNodes.length; childi-->0;) {
        var child= element.childNodes[childi];
        if (child.nodeType==1) {
            findText(child, pattern, callback);
        } else if (child.nodeType==3) {
            var matches= [];
            var match;
            while (match= pattern.exec(child.data))
                matches.push(match);
            for (var i= matches.length; i-->0;)
                callback.call(window, child, matches[i]);
        }
    }
}

findText(document.body, /\bBuyNow\b/g, function(node, match) {
    var span= document.createElement('span');
    span.className= 'highlight';
    node.splitText(match.index+6);
    span.appendChild(node.splitText(match.index+3));
    node.parentNode.insertBefore(span, node.nextSibling);
});

Answer: Regular Expressions and replace() spring to mind. Something like
var text = $([selector]).html();
text = text.replace(/Now/g,'Now<\strong>');
$([selector]).html(text);

A word of caution in using html() to do this. Firstly, there is the potential to replace matched strings in href attributes of  elements and other attributes that may cause the page to then incorrectly function. It might be possible to write a better regular expression to overcome some of the potential problems, but performance may suffer (I'm no regular expression guru). Secondly, using html() to replace content will cause non-serializable data such as event handlers bound to elements markup that is replaced, form data, etc. to be lost. Writing a function to target only text nodes may be the better/safer option, it just depends on how complex the pages are.
If you have access to the HMTL files, it would probably be better to do a find and replace on the words they want to change the appearance of in the files if the content is static. NotePad++'s Find in Files option is performant for this job in most cases.
Going with SingleShot's suggestion and using a  with a CSS class will afford more flexibility than using a  element.
Comment: Just testing one! Also note setting `html()` will lose all your non-serialisable information, such as event handlers, JavaScript references and form data.
Comment: Don't parse HTML with regex. `` -> whoops.
Comment: @bobince - I'll put some caveats in the answer. The safest way would probably be to only operate on text nodes, but I see that you've got that angle covered in your answer :)
Comment: You should better cache the element than the text: `var elem = $([selector]); elem.html(elem.html().replace(/Now/g,'Now<\strong>'));`
Comment: The content will ultimately be in a CMS, so doing a global find/replace (in Coda, in my case :) was not my favored solution, though it crossed my mind. I opted for the other solution simply because the bolded word is also used frequently throughout the site, including page names, so that's out too. But thanks. :)
Answer: I wrote a little plugin to do just that. Take a look at my answer to a similar question.
Instead of downloading the plugin suggested in the accepted answer, I strongly recommend that you use the plugin I've written--it's a lot faster.
Answer: var Run=Run || {};

Run.makestrong= function(hoo, Rx){
 if(hoo.data){
  var X= document.createElement('strong');
  X.style.color= 'red'; // testing only, easier to spot changes
  var pa= hoo.parentNode;
  var res, el, tem;
  var str= hoo.data;
  while(str && (res= Rx.exec(str))!= null){
   var tem= res[1];
   el= X.cloneNode(true);
   el.appendChild(document.createTextNode(tem));
   hoo.replaceData(res.index, tem.length,'');
   hoo= hoo.splitText(res.index);
   str= hoo.data;
   if(str) pa.insertBefore(el, hoo);
   else{
    pa.appendChild(el);
    return;
   }
  }
 }
}

Run.godeep= function(hoo, fun, arg){
 var A= [];
 if(hoo){
  hoo= hoo.firstChild;
  while(hoo!= null){
   if(hoo.nodeType== 3){
    if(hoo.data) A[A.length]= fun(hoo, arg);
   }
   else A= A.concat(arguments.callee(hoo, fun, arg));
   hoo= hoo.nextSibling;
  }
 }
 return A;
}

//test

**Run.godeep(document.body, Run.makestrong,/([Ee]+)/g);**

Answer: This is not a jQuery script but pure javaScript, i believe it can be altered a little.
Link.


Compare and Print in Lua?

Question: I like to compare and print,
I have parent child relationship, where I have category,group,questions and sub-questions
Each sub-question is part of a question, each question is part of a group and each group is part of a category.
my problem is that my category name prints on each group, I like to set if they have the same name to category not to print it but to show the next one when needed.
Let me show you what I mean:
a = category
b = group
q,e,r =questions
t = sub-question

(Category Name) Cat 1
(Group Name)Group 1 (part of Cat 1)
(Question Name) Question 1  (part of Group 1)
                Question 2  (part of Group 1)
                Question 3  (part of Group 1)
 (Sub question) -Sub-question 1 (part of Question3)

 (Group Name)Group 2 (part of Cat 1)
 (Question Name) Question 1  (part of Group 2)
                Question 2  (part of Group 2)
                Question 3  (part of Group 2)
 (Sub question) -Sub-question 1 (part of Question3)

 (Category Name) Cat 2
 (Group Name)Group 3 (part of Cat 2)
 (Question Name) Question 1  (part of Group 3)
                Question 2  (part of Group 3)
                Question 3  (part of Group 3)
 (Sub question) -Sub-question 1 (part of Question3)

The result is:
 Cat 1
 Group 1
 Question 1
 Question 2
 Question 3
 Sub-question 1
 **Cat 1 *(this is what I like to skip)**
 Group 2
 Question 1
 Question 2
 Question 3
 Sub-question 1
 Cat 2
 Group 3
 Question 1
 Question 2
 Question 3
 Sub-question 1

If they are from the same Category don`t print it twice or 100 times just once.
Comment: Can you provide your actual data fragment? Can you provide the print function you use?
Comment: There is a problem either in your data or in your code. How can we help you if you provide neither data nor code?
Comment: Im sorry but I use the LUA as a script, so my code is with variables from DB not actual LUA code I can provide...but a simple idea will  be perfect
Comment: is this and of help?
In this case each time there is Category it will print the Category.
I like something that will only show if they are not same...

[?if a:Category()~= nil then ?]
[?=a:Category().Name?]
[?end?]
Comment: The current situation is called *insufficient information*. It's your turn now.
Comment: The idea is to get this in Lua...

var A = "";
foreach(var B in lista)
{
 if(B != A)
  print(B);
 A = B;
}
Answer:
t = { jek="1kat", jek="1kat", jek="1kat", pek="2kat", trek="3kat",
  cetrek="4kat", petrek="5kat", petrek="5kat", sesrek="6kat",
  sedmrek="7kat"}

previous = k
for ki,k in pairs(t) do
if (k~=previous) then
print(k)
end
end
thx for all ur help!!

Compare and Print in Lua?


Limpar campos de um formulário

Question: Então moçada eu to com um problema aqui que é o seguinte:
Eu tenho 2 formulários. O formulario2 que fica dentro do formulario1. E eu queria um botao pra resetar apenas os campos do formulario 2. Só que o input type="reset" que eu coloco dentro do formulário 2, acaba limpando os 2 formulários.
Teria como eu fazer um botão apenas pra limpar os campos do formulário2 ?
Answer: HTML explicitamente proíbe a inserção de form dentro de outro form.
veja aqui
Nesta parte:

Content model:
  Flow content, but with no form element descendants.

Nesta parte destacada do link, está dizendo quais tipos de categorias de conteúdo um form pode ter dentro dele. No caso pode ter elementos pertencente às categorias de conteúdo de fluxo, exceto outro elemento form. (A exceção se deve ao fato de que form é um elemento pertencente à categoria conteúdo de fluxo). Veja mais aqui.
Uma possível alternativa, seria isso:

$('input.limpar').on('click', function() {

  $('div.campos').find('input').val('');

});
input {

  display: block;

  margin-top: 5px;

}

<form>

  <input type="text" value="campo 1" />
  <input type="text" value="campo 2" />
  <input type="text" value="campo 3" />

  <input type="text" value="campo 4" />
  <input type="text" value="campo 5" />
  <input type="text" value="campo 6" />

  <input class="limpar" type="button" value="limpar" />

</form>
Comment: Poxa, desde já obrigado pelo toque ai! Mas teria alguma outra forma?
Comment: Vey fino demais! Era bem isso mesmo! Valeu!!!!
Comment: @JaiderMasterInfo, você pode deixar um form só. Aí, você envolve os campos do formulário que você quer limpar em um div. Pra limpar, crie um botão que ao clicar procure todos os camos dessa nova div e retire os valores. Estou no trabalho agora, meio enrolado. Quando aliviar posso criar um exemplo aqui.
Comment: Beleza cara, se puder dar essa força ai, valeu mesmo!
Comment: @JaiderMasterInfo, editei minha resposta com um exemplo. Dá uma olhada e veja se consegue adaptar para as suas necessidades. Qq coisa, estamos aí!

Limpar campos de um formulário


Get fetchall result from different class

Question: let me explain what i'm trying to do.
In one DBcommand.php file i have :
class DBcommand Extends PdoDB {
     public function selectAll() {
       $stmt = $this->dbh->prepare("SELECT hwid,username,pcname FROM users");
       $stmt->execute();
       $columnn = array();
       $result_returned = $stmt->fetchAll(PDO::FETCH_CLASS);
       foreach($result_returned as $key=>$result) {
         $columnn['hwid'] = $result->hwid;
         $columnn['username'] = $result->username;
         $columnn['pcname'] = $result->pcname;
         //return $columnn;
         //$columnn= new us($result->hwid,$result->username,$result->pcname);
       }
       return $columnn;
     }
}

And i'm trying to get my result on another page called View.php
$cmd = new DBcommand();
//$get = $cmd->getInfo('1234');
$result=$cmd->selectAll();

echo '
<input type="checkbox" class="checkthis" />	' . $result['hwid'] . '	' . $result['username'] . '	' . $result['pcname']. '
<button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ></button>

<button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ></button>

';
                                        ?>

The issue i have is , my selectall works , but my view.php only get 1 info from it, either the first one or last one.
Even if i try to make some kind of while on the view.php part, it never get all result.
lets say my selectAll return array('123','azerty',azerty'); and array('6547','qwertty',qwerty');  , my print_r from selectAll will show me what i want to see, but my result from view.php, will only show me one of these 2 result.
--
I even tried to create another class that takes $this->_hwid, so i'll use this class later, but didnt manage, since its object in string result.
--
Getting stuck, Thanks for your help.
Comment: You're overwriting values in your `foreach` loop. And why are you injecting an object of `PdoDB` in `DBcommand` you're alreading extending it.
Comment: Yes thanks i corrected the DB thing, it was due to an old test. Yes in this exemple, i am overwritting, but even if i put the return inside the foreach, result remind the same
Answer: public function selectAll() {
    $stmt = $this->dbh->prepare("SELECT hwid,username,pcname FROM users");
    $stmt->execute();
    return $stmt->fetchAll();
}

this is ALL the code for the problem function you need.
your other code also requires minimal understanding of a technology you are using. At least you have to realize that you're getting multiple rows from the table, in the form of array, which usually being looped over using foreach() command.
Answer: Your foreach always fills just one item in the array.
try this instead:
 foreach($result_returned as $key=>$result) {
   $columnn[$key]['hwid'] = $result->hwid;
   $columnn[$key]['username'] = $result->username;
   $columnn[$key]['pcname'] = $result->pcname;
 }

Comment: How do i get result from this on the view.php side?


Proving nonsingularity of this block matrix

Question: I have received this question to solve, but, quite frankly, I have no idea how to do it. Can anyone help?
Let $A,B,C,D \in R^{n \times n}$ Show that if $B,D,A-BD^{-1}C$, and $C-DB^{-1}A$ are nonsingular, then
$$\begin{bmatrix}
       A & B\\[0.3em]
       C & D\\[0.3em]
       \end{bmatrix}^{-1} = \begin{bmatrix}
       (A-BD^{-1}C)^{-1} & (C-DB^{-1}A)^{-1}\\[0.3em]
       -D^{-1}C(A-BD^{-1}C)^{-1} & D^{-1}-D^{-1}C(C-DB^{-1}A)^{-1}\\[0.3em]
       \end{bmatrix}$$
I don't know whether you can apply the same rules as with numerical matrices or not, that's where the root of my problem is. Thanks in advance!
Comment: Your alleged inverse is not quite right.  Several typos.
Comment: I adjusted it, typos have been fixed!
Answer: Multiplication of block matrices works the same as that of ordinary matrices, except that you have to be careful of the order of things because matrices don't
commute.  Thus
$$ \left[ \matrix{A & B\cr C & D\cr} \right] \left[ \matrix{E & F\cr G & H\cr} \right] = \left[ \matrix{AE+BG & AF + BH\cr CE +DG & CF + DH\cr} \right]$$
So multiply $\left[ \matrix{A & B\cr C & D\cr} \right]$ by its alleged inverse (after you get that corrected), and check that you can simplify the result to $\left[\matrix{I & 0\cr 0 & I}\right]$.


Splash Screen will not display

Question: I am trying to implement a Splash Screen using this java and xml code. I created a separate java class from my main activity and placed the java code inside. I created an xml layout in my layout file and placed the xml code inside. However, my app appears normally without a splash screen. It never shows, but the app does not have any errors. Eclipse is not showing any errors either. What could be the cause to this? Thank you in advance. Here is the code.
Java:
package com.carouseldemo.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;

public class Splash extends Activity {

    private final int SPLASH_DISPLAY_LENGHT = 1000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.splash);

        /* New Handler to start the Menu-Activity
         * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(Splash.this,Menu.class);
                Splash.this.startActivity(mainIntent);
                Splash.this.finish();
            }
        }, SPLASH_DISPLAY_LENGHT);
    }
}

XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <ImageView android:id="@+id/splashscreen" android:layout_width="wrap_content"
                android:layout_height="fill_parent" android:src="@drawable/cat"
                android:layout_gravity="center"/>
        <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content" android:text="Hello World, splash"/>
</LinearLayout>

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.carouseldemo.main"
      android:versionCode="1"
      android:versionName="1.0"
      >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" android:screenOrientation="portrait"/>
    <application android:icon="@drawable/buttonone" android:label="@string/app_name">

        <activity android:name=".MainActivity" android:label="@string/app_name" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Comment: The splash screen display time is 1 sec,can you keep it something around 4-5 Seconds and check it again.
Comment: I increased the time to 10 seconds. It shows a black screen for about a second and opens the app.
Comment: What about Manifest File??Have you registered the splash screen as a Launcher Activity..can you please post your manisfest file here??
Comment: Your java code is Ok and it does n't need to be changed..thier would a minor problem.
Comment: I have updated my question with the Manifest File.
Comment: Replace .MainActivity in manifest with .Splash
Comment: @LuluR be careful next time :P
Answer: Replace the Handler part with this :
Thread splashThread = new Thread() {
    public void run() {
                try {
                Thread.sleep(SPLASH_DISPLAY_LENGHT);
                } catch (Exception e) {
                } finally {
                Intent i = new Intent(Splash.this,Menu.class);
                startActivity(i);
                finish();
                }
            }
        };
    splashThread.start();

Comment: The splash screen still does not appear. Thank you for responding, do you have any other ideas?
Comment: what is Menu.class all about ?
Comment: I am using code I found from a similar question I found on here. I tried to make it work before posting the question. I'm just a beginner and it seemed necessary.
Comment: Any service, what do you mean by that? Can you be a bit more specific?
Comment: Check manifest file :
Comment: I mean did you making any internet connection calls ? BTw check manifest file
Comment: No, I did not make any internet connection calls. I have updated my question with the Manifest file.
Comment: What do I do in the Manifest file?
Comment: by Default your manifest contains Menu.class as first activity to start. So replace `android:name=".Menu"` with `android:name=".Splash"`. Also add one more activity tag for Manu class like `
`
Comment: My Manifest file is posted above in my question. I do not have android:name=".Menu" Only <activity android:name=".MainActivity" Do I still replace it?
Comment: but in your Spash class, you putting intent from Splash screen to Menu class. ?? Where would you want to navigate right after the Splash screen ?
Comment: I want to navigate to the Main Activity right after the Splash Screen.
Comment: Then in your splash class code, change Menu.class to MainActivity.class. Also perform what i said in manifest file. replace android:name=".MainActivity" with android:name=".Splash". Also add one more activity tag for MainActivity class like
Comment: Answer suggested by Santhosh is what i am saying about. He is right
Answer: Try out as below :

 public class Splash extends Activity
  {
   private final int SPLASH_DISPLAY_LENGHT = 1000;
       @Override
         public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
               setContentView(R.layout.splash);
               new Thread(){
        public void run()
        {
            try
            {
                sleep(SPLASH_DISPLAY_LENGHT);
               Intent mainIntent = new Intent(Splash.this,Menu.class);
                         Splash.this.startActivity(mainIntent);
                        Splash.this.finish();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        };
    }.start();
}

EDITED:

  <activity android:name=".Splash" android:label="@string/app_name" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Comment: Your code did not bring errors, but the splash page did not come up either.
Comment: I can see that you have set defined `MainActivity` as launcher in your manifest. Besides you should define the `Splash` activity as launcher. Please change it. And check my answer.
Answer: private static final int STOPSPLASH = 0;
private static final long SPLASHTIME =3000;

public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.splash);
            context = getApplicationContext();
            if(savedInstanceState == null){
                Message msg = new Message();
                msg.what = STOPSPLASH;
                spHandler.sendMessageDelayed(msg, SPLASHTIME);
            }
        }

    private Handler spHandler = new Handler() {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
            case STOPSPLASH:
                gotoHomeScreen();
                break;
            default:
                break;
            }
            super.handleMessage(msg);
        }
    };

    public void gotoHomeScreen(){

        Intent i = new Intent();
            i.setClass(Splash.this,Home.class);
            startActivity(i);
            finish();
            spHandler = null;

    }

try this.
in your manifest
<activity android:name="Splash" android:configChanges="keyboardHidden" android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Answer: MainActivity is launcher activity in manifest file. So, splash is not showing.
Change the launcher activity MainActivity to Splash and write another  for MainActivity.
<application android:icon="@drawable/buttonone" android:label="@string/app_name">

        <activity android:name=".Splash" android:label="@string/app_name" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" />
    </application>

Comment: I was wondering how I could have MainActivity as the android name and Splash at the same time in the activity. Thank you for demonstrating this. Everyone was right, but this is what solved it.
Answer: Another way to achieve using CountDownTimer
public class MyCounter extends CountDownTimer {

        public MyCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {

            startActivity(new Intent(SplashScreen.this,
                    TabSample.class));
            finish();

            MCObject.cancel();

        }

        @Override
        public void onTick(long millisUntilFinished) {

        }

    }

Within OnCreate
     MyCounter MCObject;
    MCObject = new MyCounter(3000, 100);
    MCObject.start();

Answer: Replace your handler
new Thread(new Runnable() {
    public void run() {
        try {
            Thread.sleep(SPLASH_TIME);
            startActivity(intent);
            finish();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}).start();

Comment: Unless I'm supposed to replace intent with something of my own code?
Answer: Use this code, it might help you.
public class SplashScreenActivity extends Activity {

    protected int _splashTime = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        Thread splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    sleep(_splashTime);
                }
            } catch (InterruptedException e) {
                // do nothing
            } finally {
                startActivity(new Intent(SplashScreenActivity.this,
                        MainActivity.class));
                SplashScreenActivity.this.finish();
            }
        }
    };
    splashTread.start();
}

Hope it will help you.

Splash Screen will not display


Trying to send a  with webform

Question: I have a Webform that does some calculations (javascript) based on user selections, which i would like to send along with the user-selectable fields to a user's email.
Is it possible to append these div's to the HTML email along with the fields?
Comment: Are you using the Webform module or are you creating the form in a custom module?
Comment: I am using the Webform module.
Answer: You could add a regular webform field to capture the calculation result, filling it via Javascript.
Then you hide the field via CSS.
Storing a bunch of html has a security risk though.
Answer: You can create a custom module with the next hook:
function yourmodulename_webform_submission_presave($node, &$submission){
   ...
}
var $node contains the webform node on which this submission was made and submission contains the webform submission that is about to be saved to the database. So, that way you can get the values from submission and alter them.

Trying to send a  with webform


Dimension of extension of scalars

Question: The context is this: Let's say $X$ is an affine scheme of finite type over a field $k$. Then if $K$ is a field extension of $k$, you can consider the affine scheme $X_K$. Are the dimensions of $X$ and $X_K$ equal?
Comment: You are asking if a finite type $k$-algebra $A$ has the same Krull dimension as $A\otimes _k K$ for some extension $K/k$...
Comment: Yes...I'm guessing that the dimensions should be equal because I'm just extending scalars, but I don't know how to prove that from the definition of Krull dimension.
Answer: Let $A=\mathcal O(X)$ be the  ring of $X$. Noether's normalization lemma says that there is an inclusion $k[T_1,\cdots,T_d]\subset A$ with $d= \dim A=\dim X$ and $A$ finite and thus integral  over $k[T_1,\cdots,T_d]$ .
 Since $K$ is flat over $k$, tensoring by $K$ over $k$ yields a new inclusion: $$K[T_1,\cdots,T_d]=k[T_1,\cdots,T_d]\otimes _k K\subset A\otimes_k K$$ But this inclusion is still integral,  so that  $\dim A\otimes_k K=\dim K[T_1,\cdots,T_d]=d$ and finally $\dim X_K=\dim A\otimes_k K=d=\dim X$, as desired.
[I have used that in an integral inclusion of rings $A\subset B$ one has $\dim A=\dim B$]
Comment: Thank you. I'm trying to learn the theory of algebraic groups over an arbitrary field, whereas before I had read more elementary books where they work with the rational points over an algebraically closed field (essentially with matrices), so now I'm "relearning" the whole theory in the scheme-theoretic way.
Comment: Good luck in your relearning, dear CoffeeBliss.

Dimension of extension of scalars


animating components in Jpanel

Question: I have this idea that I want to implement into my project.
I know it is doable, but I do not know where to start.
I have a JPanel,
in there will be a Jbutton , a JLabel, and a ComboBox, and a JtextArea.
Originally, there is only the JtextArea and JButton on my panel.
When I hit the button, the Combobox, and JLabel will slide in or fade in, or drop down, or event rotate in.
So how would I accomplish this, I know I have to use graphic g, repaint(). It is easy to do the Jlabel but what about the combobox.
Should I add the combobox and Jlabel into a separate Jpanel and make that panel animated in. but even that, I do not know how to make this panel in motion.
Please help me on this, and example would be appreciated
Thank you!
Comment: [What have tried?](http://www.whathaveyoutried.com)
Comment: I tried, I have the basic frame up, and my JLabel moving around, but I have no idea how to make the combobox moves.
Comment: @LanNguyen - exactly the same way.  They're all `JComponent`s so the same methods are available to everyone.  (That is, if you're using a JComboBox.)
Comment: I did something simular using a AnnatedLayout, which basically acted as a proxy to the components current layout manager
Answer: To get started, you'll probably need to research these terms:

Slide layout (thanks @Andrew Thompson)
setLocation
TimerTask (I think, or maybe just Timer)
clobbering graphics objects

Once you know about that stuff, you'll be in a position to make the design decisions that you're asking about.
It sounds like you'll have a child panel with a slide layout. Try not to use null layouts when possible.
You'll set its location or style per each tick in a timer task.
If you're setting a style, you'll need to clone your graphics object to avoid "clobbering" it - that is, work on a copy of the graphics object, so the original isn't changed or repainted accidentally while you're working on it.
Comment: +1, but perhaps we should make it clear for newbies that `SlideLayout` represents a **custom** layout.
Comment: *"null layout"*  If you have the logic needed to size and position the component during slide, it should be encapsulated in a `SlideLayout`.  This is not a good case for `null` layout.
Comment: "set its location or style per each tick in a timer task". Now this is the key players, thanks, problem solved :P.

animating components in Jpanel


Is $\int_0^t K_s \mathrm d s$ $\mathcal F_t$-measurable in case the sample paths of $(K_s, s\ge 0)$ are continuous only almost everywhere?

Question: Let $(\Omega, \mathcal F, \mathbb P)$ be a probability space. Let $K=(K_t, t\ge 0)$ be a process adapted to a filtration $(\mathcal F_t, t\ge 0)$ such that the map $t \mapsto K_t (\omega)$ is continuous for all $\omega \in \Omega$. We define the process $V=(V_t, t\ge 0)$ by
$$
V_t := \int_0^t K_s \mathrm d s \quad \forall t \ge 0.
$$

Theorem $V$ is adapted to $(\mathcal F_t, t\ge 0)$.

My questions

Could you have a check on my below attempt?
In my proof, I use the fact the everywhere pointwise limit of a sequence of measurable functions is again measurable. It seems the function $V_t$ defined by $V_t := \int_0^t K_s \mathrm d s$ is not necessarily measurable if the sample paths are continuous only almost everywhere. Could you confirm if my understanding is fine?

Proof Fix $t>0$. We will prove that $V_t$ is $\mathcal F_t$-measurable. We fix an increasing sequence $0=t_0^n<\cdots<t_{p_n}^n=t$ of subdivisions of $[0, t]$ whose mesh tends to $0$. Let
$$
X_n := \sum_{i=0}^{p_n - 1} K_{t_i} (t_{i+1} - t_i) \quad \forall n \ge 1.
$$
Then $X_n \overset{n \to \infty}{\longrightarrow} V_t$ pointwise everywhere. Because $X_n$ is $\mathcal F_t$-measurable for all $n$. So $V_t$ is $\mathcal F_t$-measurable.
Answer: Fix $t>0$. We need to prove that $K:[0,t]\times\Omega\rightarrow\mathbb{R}$
is $\mathcal{B}([0,t])\otimes\mathcal{F}_{t}$-measurable. Then, that
$V_{t}$ is $\mathcal{F}_{t}$-measurable follows from Fubini Theorem.
The joint-measurability of $K$ follows from the fact that $K$ is
adapted to the filtration and that it has continuous sample paths.
We prove this fact as follows:
For each $n$, define $K^{n}:[0,t]\times\Omega\rightarrow\mathbb{R}$
by
$$
K^{n}(s,\omega)=K(0,\omega)1_{\{0\}\times\Omega}(s,\omega)+\sum_{k=0}^{2^{n}-1}K(\frac{t(k+1)}{2^{n}},\omega)1_{(\frac{tk}{2^{n}},\frac{t(k+1)}{2^{n}}]\times\Omega}(s,\omega).
$$
Since $K(\cdot,\omega)$ is continuous for each $\omega\in\Omega$,
it is routine to verify that $K^{n}\rightarrow K$ pointwisely. Note
that for each $k$, $(s,\omega)\mapsto K(\frac{t(k+1)}{2^{n}},\omega)$
and $(s,\omega)\mapsto1_{(\frac{tk}{2^{n}},\frac{t(k+1)}{2^{n}}]\times\Omega}(s,\omega)$
are $\mathcal{B}([0,t])\otimes\mathcal{F}_{t}$-measurable. Hence,
$K^{n}$ is $\mathcal{B}([0,t])\otimes\mathcal{F}_{t}$-measurable.
It follows that $K$ is $\mathcal{B}([0,t])\otimes\mathcal{F}_{t}$-measurable.
Comment: So the measurability of $K$ depends on the fact that $K(\cdot , \omega)$ is continuous for **all** $\omega \in \Omega$. Could you elaborate on the case where $K(\cdot , \omega)$ is continuous for **almost all** $\omega \in \Omega$?


Balance after partial payments according to terms

Question: The Ski Shop received an invoice for $\$9600$ dated August 11, terms $5/10$, $2/30$, $n/90$, for the shipment of skis. The Ski Shop made two partial payments.
a) How much was paid on August 20th to reduce the unpaid balance to $\$7000$
b) How much was paid on September 10 to reduce the outstanding balance by $\$3000$
c) What is the remaining balance on September 10?
This questions is giving me troubles because I do not know how much money is in each partial payment.
Comment: I suppose the key to the problem is "terms 5/10, 2/30..."
Answer: The term $5/10$ means, that you have a reduction of $5\%$ of the required payment, if you pay within 10 days. Similar meaning of $2/30$. And $n/90$ means, that the invoice has to be fully paid after 90 days.
At a) the payment is within 10 days. You want to reduce the unpaid balance to $\$7000$. Therefore the reduction is $\$2600$. And you have to pay
$\$2600\cdot (100\%-5\%)=\$2600\cdot 95\%=\$2600\cdot 0.95=\$2470$
I think you can take it from here. If there are any questions, feel free to ask.