Encontrar em um texto as tags img

Question: Eu possuo um texto Aleatório:
$s = " eu sou campeao  teste lala  ";

e preciso que adicione o caminho da imagem e fique assim:
$s = " eu sou campeao  teste lala  ";

Obs: eu preciso adicionar "img/" dentro do src que possui o diretorio. Pode vir varias imagens, mas vou adicionar a mesma string.
Answer: Basta utilizar str_replace, para trocar o src=' por src='img/'.
str_replace('src=\'', 'src=\'img/', $s);

Teste isto.

Encontrar em um texto as tags img


is it possible to distruct two values from async/await [any solution]

Question: so i have been playing around with promises in different ways here i was trying to understand how to implement both promises and async/await in different ways and i'v encountered difficulties what i'm trying to do is to transfering this piece of code(the one that works) into this async/await, and it was messy and it did not work for me
[pardon my english and my code writing]
Works Perfectly
React.useEffect(() => {
    if (!pokemonName) {
      return
    }
    setPokemon(null);
    setError(null)
    fetchPokemon(pokemonName).then(
      pokemon => setPokemon(pokemon),
      error => setError(error),
    )
  }, [pokemonName])

Did not work
React.useEffect(() => {
            if (!pokemonName) {
              return
            }
            setPokemon(null)
            setError(null)
            async function effect() {
              const [result,error] = await fetchPokemon(pokemonName);
              if(error){
                return setError(error);
              }else{
                return setPokemon(result);
              }
            }
            effect()
          }, [pokemonName])

Answer: You can convert the first snippet to
React.useEffect(async () => {
    if (!pokemonName) {
      return
    }
    setPokemon(null);
    setError(null)
    try {
      setPokemon(await fetchPokemon(pokemonName));
    } catch (error) {
      setError(error);
    }
  }, [pokemonName])

An asynchronous function call with await doesn't return an error. It throws the error. Therefore you have to catch potential errors. If the function can't be async you can use a immediately invoked function expression (IIFE)
React.useEffect(() => {
    if (!pokemonName) {
      return
    }
    setPokemon(null);
    setError(null)
    (async () => {
      try {
        setPokemon(await fetchPokemon(pokemonName));
      } catch (error) {
        setError(error);
      }
    })();
  }, [pokemonName])

Comment: it worked like charm just keep in mind  about the useEffect(React.useEffect(async () => .......) hook is that you cannot  return anything other than the cleanup function. in this case you are returning a promise due to the semantics of async/await syntax , But the second worked so fine and i'v learned a lot thank you


CamelCase regexp not accounting for spaces

Question: I created a regexp to match the following scenerios: SomethingCool, HelloWorld, MyNameIsDonato, etc. However, it does not account for spaces:
> 'Something Cooler' =~ /([A-Z][a-z0-9]+)+/
 => 0

That passes and it should not pass. A space is not an alphanumeric character. So why does this pass and how can I fix it?
Comment: BTW, match here is `Something`, not the whole string.
Answer: You need to anchor the regex to the beginning and end of the string, or it will just match one of the words:
^([A-Z][a-z0-9]+)+$

^ and $ anchor the beginnings and ends of lines, respectively. To anchor to the beginning and end of the string, use \A and \Z.
It's worth noting that this is useless if you're trying to find camelcase names within a larger string. For that, use your original regex.
Comment: Please always use `\A` and `\z` instead of `^` and `$` to prevent false matching of `"CamelCase\neval(`rm -rf /`)"`.
Comment: This is exactly what I am looking for. I will upvote your answer in 15 minutes.
Comment: @mudasobwa: Depends on what you are doing. For one thing, that isn't a security hole unless you're evaling user input, at which point you need much better input sanitation, and most likely, a better approach. I usually use `\A` and `\Z`, but they seemed unnecessary here.
Comment: I was talking not about secuity hole, but about undebuggable positive match on `klazz = "CamelCase\n" ; klazz =~ regexp && const_get(klazz)` leading to an exception.
Comment: @mudasobwa: Mentioned `\A` and `\Z` in answer.
Comment: @mudasobwa: The inclusion of `eval("rm -rf /")` usually indicates someone is pointing out a security flaw. Sorry to have misinterpreted.
Comment: It turned out I have had this string in the buffer and just copy-pasted it, so all sorries are mine :)
Comment: You usually want `\z` and not `\Z` ([docs](http://ruby-doc.org/core/Regexp.html#class-Regexp-label-Anchors)).


How to configure rules for wcag2aa in axe-core for selenium java

Question: I want to add rules in axe in selenium for wcag2aa.
Can anyone help me with the syntax?
<code>JSONObject responseJSON = new AXE.Builder(getBrowser()
                    .getWebDriver(), scriptUrl).options(
                    ("{ rules: { 'wcag2aa' } }")).analyze();
</code>
I have tried the above code but it is giving me exception
Thanks.
Comment: @curveball When making edits, you should remove salutations/thanks, as they are perceived by noise by most users.
Answer: wcag2aa is a list of rules and not a rule itself.
Try:
.options("{ runOnly: ['wcag2aa'] }")
Or you can only run multiple lists of rules like so:
.options("{ runOnly: ['wcag2a', 'wcag2aa', 'best-practice'] }")
In this case the only list of rules that would not run is the 'section508' list.
Check out the Axe API docs on the options parameter


Dúvida WPF C# - SetFocus em um Text e deixar um button desabilitado

Question: Estou com dificuldade em c# pois quando clico em um botão, ele tem que desabilitar um botão e deixar o focus em um txt.
Porém não sei como referenciar um objeto em wpf (xaml) no arquivo de codificação (cs)

  private void View(object parameter)
  {
    //Como referênciar o button01 e o txt01 aqui?
  }
<Button HorizontalAlignment="Center"
        Command="{Binding SearchCommand, Mode=OneTime}"
        Visibility="{Binding ShowList}"
        Style="{StaticResource ButtonProcurar}" Click="Button_Click"/>

<Button x:Name="button01" Content="Desabilitar ao clicar no botão acima" />

<TextBox x:Name="txt01" Text="Texto que o cursor deverá vir ao clicar no primeiro botão" />

Answer: Você acessa os elementos do XAML pelo mesmo nome dado ao elemento na propriedade x:Name.
Neste caso os nomes dos elementos é button01, txt01.
Portanto, para desabilitar o botão e colocar o foco no campo de texto, você deve alterar o evento Button_Click que está no code behind (arquivo cs do XAML)
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        button01.Enabled = false;
        txt01.Focus();
    }

É importante lembrar que seu XAML deve referenciar o Arquivo CS:
No início do arquivo XAML você encontrará a declaração da tag Window e a respectiva referencia a classe.
Se o arquivo CS não encontrar os elementos declarados em seu XAML, possivelmente está faltando essa referência.
Veja o exemplo:
Arquivo XAML:

Arquivo CS:
Comment: Muito obrigado pela ajuda !!!


bind attribute within a component leaking to other components in ember

Question: I have a component that I load multiple times in a page. And I am binding class to one of the elements in the component based on a property of the component.
A simple example that demonstrates the issue is here : http://jsbin.com/iKabiKi/1/
You can see in the example that if I click on one of the links, the class is changed to all the other component elements!
I am not sure if I am doing things wrong or if this is a bug. Your insight will be much appreciated.
Thanks,
Dee
Answer: Arrays are initiated and live on the class, not the instance.  Initialize it during init, or somewhere else to avoid this issue.
http://jsbin.com/iKabiKi/2/edit


Nested design with pairing

Question: I have been asked to help a colleague with analysing the following experimental design.
2 treatments (fixed), 5 time points (fixed) with 4 animals (random) at each time point. The animals within each time point are not the same.
Each animal had two samples taken, one from a treated limb and one from an untreated limb so within each time point the samples from each animal are paired.
I would like to analyse this data as a nested ANOVA in R. The formula I have currently is:
value ~ treatment + time/individual
Testing the measured value for the treatment at each time with individual nested within time. This doesn't account for the paired nature of the samples though. Also this is the first example of a nested design I've been asked to analyse and I wonder if someone could advise me as to whether I'm on the right path.
Answer: Based on what you have described, I would use the mixed model:
Value = intercept + treatment + time + treatment*time + individal + e
Where treatment, time and their interaction are fixed effects and individual is a random effect.
The way to formulate this model depends on the package you are using.  If you are using lme() in package {nlme} then you can fit this model with:
lme(fixed = value ~ treatment * time, data = my.data ,  random = ~ 1 | individual)

Where my.data is the data.frame containing treatment, time and individual as factor variables and value as a numeric variable.  This formulation is short form; it's actually the same as:
lme(fixed = value ~ 1 + treatment + time + treatment:time, data = my.data, random = ~ 1 | individual)

which corresponds more directly to the model above.  Make sure that your data.frame is ordered correctly and is univariate (vertical).
This model has two variance parameters: one for the variance explained by individual animals and one for the residual error.  If you want to estimate individual animal variance at each time then you could use a model like:
lme(fixed = value ~ treatment * time, data = my.data, random = ~ time | individual)

but this might be over-parameterized for your data set and you might have convergence issues and the final hessian might not be positive definite.

Nested design with pairing


GWT Activities and Places - How to understand this concept?

Question: Okay, Activities build on top of Places. Places are "just URLs". But I am just not getting it how to use them properly..
There are no nested Activities "because YAGNI"; but how does it look like in this simple scenario:

Having a login page
Having an administration page that offers functionallity for

Add events to my company
Add items to my store

After a successful login the "main container" of the website is cleared and filled with the new content of the admin-activity. One thing that has to be changed here is the "display" of the ActivityMapper since now I got a navigation bar on the left side and a main-content Div on the right side.
I could just have a LoginActivity and an AdminActivity. That means I'd have urls like
/#LoginPlace:noParams
/#AdminPlace:eventManager
/#AdminPlace:itemManager

But that's silly imho because for real I would like to have something like this:
/#LoginPlace:noParams
/#AdminPlace:eventManager|storeId=1,langaugeId=2
/#AdminPlace:itemManager|storeId=1,langaugeId=2,page=0

But that would require my AdminActivity to break up the URL and look out for all this different types of URLs, right? What I mean is something like this:
private AdministrationActivity administrationActivity;

@Override
public Activity getActivity(Place place) {

    if (place instanceof LoginPlace) {
        return new LoginActivity((LoginPlace) place);
    } else if (place instanceof AdministrationPlace) {
        if(this.adminActivity== null) {
            this.adminActivity= new AdministrationActivity((AdministrationPlace) place);
        } else {
            this.adminActivity.updateMainContent(((AdministrationPlace) place).getUrl());
        }
        return this.adminActivity;
    }

    return null;
}

Where now adminActivity.updateMainContent() will have to do the parsing for all places in order to display the correct content.
This would be the solution:
/#LoginPlace:noParams
/#EventManagerPlace:storeId=1,langaugeId=2
/#ItemManagerPlace:storeId=1,langaugeId=2,page=0

But(!) now I need an activity for each place, right? And I am just not sure if there are equally as many places as there are activities. I thought that one activity can navigate to different places.
So how are Places and Activities supposed to used?
Comment: As a side note, you might want to use an outside framework to handle your navigation. I'm the creator of the [gwt-views](https://github.com/gilberto-torrezan/gwt-views) framework, but there are others, depending on your need.
Answer: The first questions you have to ask yourself is "where will the user possibly go?". As I understand it, you at a minimum have:

list of events, with possible filter/selection criteria and paging attributes
list of items, with possible filter/selection criteria and paging attributes

Maybe you'll also have places like "details of an event" (maybe even split between read-only details and editable details, if the user will switch between both states; if the state depends on who the user is, then this is IMO the same place, and actions the user can do are different), "details of an item", "form to add an event", "form to add an item".
To me, login is a cross-cutting feature, it's not something the user comes to doing in your app (it's not a business use-case, not an "activity" that's part of the user's job). You can still choose to use a place and activity for login though; so let's add that to the list: "login form" (definitely not how I'd do it, but that's another story).
Now you can choose how you want to represent those places as GWT Place objects: you can have one Place subclass with a property telling you which exact "place" you're on (basically what your AdminPlace:eventManager token suggests), or one Place subclass per "place" (what your EventManagerPlace token suggests). This is entirely independent of whether you'll have one or several activities.
The next question is about the various areas of the screen, that'll map to ActivityManagers: what parts of the screen do change when navigating? Maybe they do not all change at the same time / under the same conditions.
So for example, should your navigation bar be within the activity or not? If you can put it outside (because it's reused), do it. It actually need not even be an activity if it's always the same (modulo the selected item). In any case, it's probably a good idea to make it a singleton (or similar) and listening to PlaceChangeEvents to select the appropriate item (not necessarily a "singleton", but at least not recreated on each navigation). The advantage of putting the navigation bar outside the activities is that if you finally decide to have it vertical rather than horizontal (or the other way around), and/or collapsible, you won't have to change your activities (separation of concern). If you ever have to build a mobile app, you could even have a "menu" place on that app that displays the navigation bar full-page and swaps it for the other activities when navigating.
So we now have 2 display regions, i.e. 2 ActivityManagers, and their respective ActivityMappers. Or maybe just one display region for the "main content", and the navigation bar is not an Activity. The next step is to determine exactly what changes and when; i.e. when I go to place X, I need to have that thing in that area, and that other thing in that one; those "things" are your activities.
The key to "model" your Activities is to think about the things the user does (activities) and focus on one of them. But Activities are also tied to how the user interacts with the application, and the navigation (e.g. when adding an item, does the form appears in a popup above the list, or replaces the list); so if you want to really completely separate concerns, you'd probably create some object to manage the list of events/items and have a really thin Activity that only instantiates and manages that object. That's probably over-engineered as a starting point though, and it'll be relatively easy to factor the thing out of the Activity later if you feel it's needed.
I like (and that's basically how the feature has been designed) to have disposable activities. In my ActivityMapper, everything from the Place that the Activity needs to know is passed to its constructor; the Activity doesn't have to know the current place (or listen to place changes), and is not "mutated" by the ActivityMapper. There can of course be exceptions to the rule, for various reasons. If you need to share state between "places" for a given activity (e.g. data caches, etc.), you don't necessarily have to reuse it, you can share the state via shared stateful objects and keep the activity mostly stateless.
Anyway, your idea of a big AdminActivity that itself swaps a big part of its content depending on the current place is akin to nesting.
In the end, there's no one-size-fits-all, and you'll have to try and pick the strategy⋅ies that best fit your needs.
Last, but not least, don't design your place with a generic getUrl() that needs to be parsed; parse everything in your PlaceTokenizers; nothing else than the tokenizers need to know how the place will look like in your URL (and you're not even forced to use a PlaceHistoryHandler to begin with, so your places might not even ever end up in the URL –your places won't be bookmarkable then and you won't be able to navigate in the app through the browser history)
The key concept is separation of concerns.
Comment: Hi Thomas and thanks for your detailed answer as always! But just to make sure that I got you right regarding the `PlaceTokenizer`: From one GWT Google Group post I got the idea of a `AbstractBasePlace` that basically has that `getUrl()`-functionality and internally saves key/value pairs (parameters). If I understand you correctly then I should rather have a `AbstractPlaceTokenizer` that would parse parameters and passes it to the place? Like in `MyTokenizer` for`MyPlace` I could have: `public MyPlace getPlace(String t) { this.params = parse(t); return new MyPlace(this.params); }`
Comment: I'm not a fan of such generic "put key values in a map" approach, but basically, yes. (parsing should include parsing values to the appropriate type too, and checking constraints; if the tokenizer returns `null` for an _invalid_ token, the user will be redirected to the _default place_; much better than getting exceptions later when you try to read from your generic parameters map)
Comment: Okay - good to know that! But what would be the alternative to generic URL parameters? I don't see how one could do that different. After all I just got a `String` that encodes my actual parameters - or am I overlooking something?
Comment: It's OK to parse `storeId=1,langaugeId=2,page=0` into a map, but then, before you exit the tokenizer, parse the `page` value into an `int` (possibly parse the `storeId` and `languageId` similarly too) and give them to a `Place` that has an `int page` field and `int getPage()` accessor. Places are "business objects" too, part of the "business" of navigating within the app; don't think of them as "merely a Java view on a URL/token string"; the URL/token string is derived from the place, not the other way around (theoretically; but the process must be reversible).
Comment: Alright got it! Wasn't sure what you meant but now I know! :) Thanks Thomas, as always! :)
Comment: Maybe you can help me there too since it's kind of related: Delegating the goTo() events to the corresponding ActivityMapper works but e.g. my landing page has a static menu on the top and my "admin" are has one on the left. So what I'm having is two different sceletons. How would I check which sceleton is currently present? Right now I am checking if  `RootPanel.get("adminSceleton")` is `null`. If so, I clear the whole content of the entire document, build up the admin-sceleton and add the menu as well as the desired content to display. But this means that I have to do this check on
Comment: every place change event. It's the same for the landing-page ActivityMapper which has to check if the correct sceleton is loaded. Is there a "*nice*" way to do this?
Comment: As suggested on my blog post, I'd use only one layout, with 3 _display regions_, the "top" one gets hidden when on a "landing" place, the "left" one when on an "admin" place". Their respective `ActivityMapager`s simply return `null` when they have nothing to display, and the regions are then hidden (see sample code in the blog post).
Answer: I'd suggest you probably do want one Activity per Place. There is generally a rough one to one relationship but they are split due to separation of concerns and so you can pass around a Place without an Activity.
Adding parameters is sadly not supported by standard GWT. We created our own simple one based on UrlBuilder.
There is a long standing issue for this https://code.google.com/p/google-web-toolkit/issues/detail?id=2422 (old issue tracker) which has other thoughts and links.
Once it is up and running it works really nicely. I like using strongly typed objects and goTo rather than sticking URLs together.


Mutli-Site uWSGI config

Question: I have about a dozen small Django sites I want to run using Nginx and uWSGI. They are on a 4-core server with 8 gigs of ram. Should each site be configured on its own socket and how can I control the total number of processes across all instances of uWSGI? If each up app has 30 processes, how can I prevent running out of ram?
Answer: add --limit-as option to each instance and limit the number of requests each process will manage after being restarted (-R 1000 is normally a good value, this will mitigate leaks)
30 processes per app looks a bit too much for me, start with 8 (ncpu*2) and increase them if you need it
If you want, you can use the development tree (take it via mercurial) and use jailing features:
http://projects.unbit.it/uwsgi/wiki/UseCgroups
http://projects.unbit.it/uwsgi/wiki/LinuxNamespace
Comment: In such situation (no deterministic resource allocation) you can go for multiple application mode + virtual hosting. You will spawn a relatively big number of processes that hosts all the apps. It is a bit complex to setup, but once you get it you will add new apps in no time. http://projects.unbit.it/uwsgi/wiki/VirtualHosting
Comment: @Jason Christa: Did you succeed on this? I'm having the same problem.
Comment: @Sergio: Yes, I use one uWSGI config (you must use xml and not ini here) and use Nginx vhosts to pass in the correct import paths and the location of the configuration file for each site.
Comment: That is pretty handy, but the situation I am most worried about is that one site gets a lot of traffic on one day and needs most of the server resources, on a different day another site needs the same thing. If site one has enough idle processes to fill memory what will happen when site two needs the memory?
Comment: I tried to get that working for hours but it seems whatever app started first is the only one it would show. In the wsgi.py I add two relative directories 'apps' and 'sites' that live inside the project directory to the python path. Is it possible the python path is being shared across apps even though I am using a virtual env and running uWSGI with the correct pyhome and with vhost and no-sites.

Mutli-Site uWSGI config


Notification and Messaging module for sending mails

Question: I have installed send methods as html mail and i have set notification module with subscriptions to content type.
I am not receiving an email when notification actions get created.
have anyone pass through such scenario? Please let me know.
Answer: Html mail is not reliable, buggy and some features are not supported. I've got rid of it. Mime mail is much better. Mail system and SMTP module must also be installed.
In the settings SMTP Authentication Support SMTP server, SMTP port, User name, E-mail from address, E-mail from name must be filled, Allow to send e-mails formatted as Html could be ticked and password of your SMTP server must also be entered.
In the module Mail system in the submenu New class MimeMail_SmtpMailSystem must be constructed and filled in Site-wide default MailSystemInterface class and Mime Mail module class. In the settings Mime mail E-mail format Full HTML can be selected and Sender e-mail address need to be filled.
This configuration must work.


Collapse whitespace except multiple blank lines using regular expressions

Question: More than once in the past I've wondered about the problem of formatting blocks of text so that all runs of whitespace are 'collapsed' into a single space, except that paragraphs should be conserved - meaning that all runs of blank lines are collapsed into single blank lines, but not collapsed into just a space.
A blank line is of course two end-of-line characters (typically carriage return or linefeed or both) without any intervening non-whitespace characters. (There may be other whitespace though such as spaces or tabs).
This is surely a pretty common problem and though not difficult to solve I'm always dissatisfied with my solutions, which lack elegance or leave open loopholes. Surely there is an elegant expressive way to do this.
I'm leaving this open to all regex flavours since I've wanted to do it in at least Perl, Vim, and JavaScript. Here's my most recent lazy attempt to do it in node.js, the loophole is obviously the magic word. It's probably pretty typical of the unsatisfactory solutions I've used::
text = text.replace(/\r?\n(?:\s*\r?\n)+/g, '_SomeMagicWord_');
text = text.replace(/\s\s+/gm, ' ');
text = text.replace(/_SomeMagicWord_/g, '\r\n\r\n');

In case my explanation is not clear it should transform from this:

foo bar baz
  fred barney wilma

  one two three

to this:

foo bar baz fred barney wilma

  one two three

(Watch out for trailing whitespace at the ends of lines too!)
Answer: sed:
sed -n 'H;$g;$s/[^\n]\n[^\n]/ /g;$s/\n\n\n*/\n\n/g;$s/  */ /g;$s/^\n//;$p' FILENAME

Perl:
perl -ne '$a.=$_;END{$_=$a;s/  */ /g;s/[^\n]\n[^\n]/ /g;s/\n\n\n*/\n\n/g;print}' FILENAME

Comment: Ah. In your example you changed a quadruple newline into a single newline.  Can you produce an example input and output that is more descriptive for me? (with paragraph formats as well)  When I tested, both of my programs worked with the example posted in the original post.
Comment: At the moment I'm on Windows and don't have access to sed, also I don't know sed so I can't parse that on my own. I'll try the Perl one though if the one-liner is Windows friendly...
Comment: On Windows the Perl needs `"` instead of `'` and even with that change I'm losing al paragraph formatting (double blank lines).
Comment: Both of my programs should turn two or more consecutive newlines into a single newline.
Comment: Oh sorry! I think maybe the markdown or other part of the Stack Exchange rendering changed it after I got it right. Let me investigate ... Fixed now. It should turn single newlines into a space and two or more consecutive newlines into exactly two newlines.
Answer: I just came up against this problem yet again. This time I'm using node.js and I feel I came up with a pretty expressive solution:
txt = txt.replace(/\s+/g, function (ws) {
  return /\n.*\n/.test(ws) ? '\n\n' : ' ';
});

txt = txt.replace(/(^( |\n\n)|( |\n\n)$)/g, '');

The first part considers each run of whitespace in the text and checks if there are at least two linebreaks within it. If so it collapses to a paragraph break (two consecutive linebreaks and nothing else). Otherwise it collapses to a single space.
The second part trims any remaining whitespace at the beginning and end of the text, each of which could only possibly be a single space or a pair of linebreaks by this point.
(The only limitations I see are those imposed by JavaScript's \s, which doesn't match all Unicode whitespace codepoints; and optionally outputting MS-style linebreaks, \r\n instead of \n.)


How Change the Style of views based on user option

Question: I have a set of products into grid view. I need to create a two tabs one for grid view and list view(swipe view). How to create like this using views in drupal 7?
Answer: Sounds like this will need to be done programmatically.
Use hook_views_pre_render() to be able to change the settings of a view based on certain conditions.
https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7
Then using the global $user definition to lookup the logged in user, use that to create a condition and alter the settings of the actual view.


Does the Lebesgue measure of $[0,\infty)^n\setminus[0,a)$ approach $0$ as $a\to\infty$?

Question: Let $\lambda$ denote the Lebesgue measure; for each $a>0$, let $A_a:=[0,\infty)^n\setminus[0,a)^n$, where $n\in\mathbb{N}$ is arbitrarily fixed. Is it true that $\lim\limits_{a\to\infty} \lambda(A_a)=0?$
Comment: $\lambda(A_a)=\infty$ for all $a$, so no, it doesn't tends to $0$.
Answer: Not necessarily. For instance if $n = 1$, then $A_a = [0, \infty) \setminus [0, a) = [a, \infty)$.
And since for any $a \in \mathbb{Z}$ we have $\lambda\left(\left[a, \infty\right)\right) = \infty$, then
$$\lim_{a \to \infty}\lambda\left(\left[a, \infty\right)\right) = \infty$$
Comment: Thanks @JamieAlizadeh! That makes sense I presume this argument still holds for $n\in\{2,3,...\}$? (That was *actually* what I had in mind, but I just wrote "$n\in\mathbb{N}$" since it's more standard  Apologies!)
Comment: Yes it does. For fixed $a \in \mathbb{Z}$ and $n \in \mathbb{N}$,
$$\lambda([a, \infty)^n \setminus [0,a)^n ) =  \lambda([a, \infty)^n) - \lambda([0,a)^n ) = \infty - a^n = \infty$$
where the first equality holds by disjointness. So for whichever $n$ you choose you'll always get a sequence of $\infty$'s as $a \to \infty$.


SmsManager em telefones Dual Sim

Question: Venho pesquisando sobre o assunto, mas ainda não vi nenhuma solução definitiva para o problema. Bem, minha aplicação faz envio de SMS a partir do SmsManager porém, não pergunta qual chip deve utilizar quando rodada em um aplicativo Dual Sim, simplesmente porque não tenho ideia de como fazer isso.
Até onde sei, o segundo parâmetro do smsManager.sendTextMessage que no momento está declarado como null é responsável pelo Centro de Serviço (SMSC) que vai ser utilizado para o envio, o que resultaria no envio pelo chip correto, em partes já que o usuário pode ter um celular com dois chips da mesma operadora, utilizando assim o mesmo SMSC para os dois chips.
Verifiquei a documentação do SmsManager mas não existe sequer nenhuma informação sobre utilização em aparelhos Dual Sim.
E aqui fica minha dúvida: como realmente utilizar o SmsManager em aparelhos Dual Sim de maneira correta, sendo sempre perguntando qual chip será utilizado para o envio, ou definindo previamente?
Answer: Fala Italo,
Eu acredito que essa seja uma função escolhida diretamente no device do usuário.
É possível definir qual SIM será o padrão de ligações e envio de SMS, para revogar essa permissão, no próprio device deve-se fazer:
Configurações >> Wireless & Networks >> SIM Management >> Padrão

Settings >> Messages >> e selecionar 'Perguntar sempre'.

Com isso toda vez que for mandar um SMS através de um APP, será perguntado qual SIM deve ser usado.
Via código não tem como desativar a escolha padrão do usuário.
Abraços.

SmsManager em telefones Dual Sim


How to locate bad login attempts on a domain account when source is unknown

Question: My issue is trying to locate the source of the lock out that is not a domain computer.
In event viewer, event 4740 the caller computer name is blank. Event viewer 4776, I show error code 0xC000006A.
The account does not use email, and is reserved to do admin related work on the network. If I rename the account, that stops the lockouts.
I tried several tools on line like lock out analyzer, netwrix, ad audit, but the source computer is never revealed.
Answer: This client is using NTLM, probably not joined to AD and your Domain Controller is not able to resolve its hostname and from AD side, you only have 02 alternatives to track the source:

Enable debug logging for Netlogon on the Domain Controller
To do that, open a Command Prompt with administrative privileges and run:
Nltest /DBFlag:2080FFFF

Then wait for the event be logged again and search for more information in:
%windir%\debug\netlogon.log

Do not forget to turn off debug logging:
Nltest /DBFlag:0x0

Enable a deeper level of NTLM authentication auditing by modifying GPO entry Network security > Restrict NTLM:

Outgoing NTLM traffic to remote servers = Audit All
Audit NTLM authentication in this domain = Enable all
Audit Incoming NTLM Traffic = Enable auditing for all accounts

NTLM audit events will be available under:

Event Viewer\Applications And Services Logs\Microsoft\Windows\NTLM\Operational

Hope this helps you find what you are looking for.


Bulk Delete Custom Entities (Not Entity Types)

Question: I have a 5000+ entries for custom Entities created by the RedHen module (https://drupal.org/project/redhen). I want to wipe them completely from the system (they are all test entries). How can I do this quickly? I tried to get Views Bulk Operations and the Delete All modules but neither seem to be picking up the custom entities.
Answer: You can  delete multiple entities using below API functions
entity_load

Load entities from the database.
The entities are stored in a static memory cache, and will not require
  database access if loaded again during the same page request.
$entity_type: The entity type to load, e.g. node or user.
$ids: An array of entity IDs, or FALSE to load all entities.

entity_delete_multiple

Permanently delete multiple entities.

For Example to delete all node entities
<code><?php
  $results = entity_load('node');
  $entity_ids = array_keys($results);
  entity_delete_multiple('node', $entity_ids);
  ?>
</code>
Comment: Yes this looks right, but I'm confused on proper usages of this. Ideally i just want to run this once or twice. Would I add this to my custom module and have it hook and run with update.php?
Comment: How many Entity Types do you have ?
Comment: Actually I was able to put this in a preprocess function on a specific page I created and it worked! I had to separate it out in chunks though, I had over 100,000 entities in the DB. So it worked! Thank You.
Answer: This simple module might help you:
https://www.drupal.org/project/entity_bulk_delete


go-gorm how to express many2many with additional columns

Question: I want to express the following tables in GORM:
CREATE TABLE indexes (
    id INTEGER PRIMARY KEY,
    name VARCHAR
)
CREATE TABLE services (
    id INTEGER PRIMARY KEY,
    name VARCHAR
)
CREATE TABLE index_service (
    index_id INTEGER REFERENCES indexes(id),
    service_id INTEGER REFERENCES services(id),
    write_active INTEGER,
    PRIMARY KEY (index_id, service_id)
)

After reading through documentations and questions on stack overflow. I still cannot find an answer on how to express the additional column write_active in GORM's DSL
What I got so far is
type Index struct {
   ID        unit `json:"id" gorm:"primary_key"`
   Name string    `json:"name" gorm:"not null"`
}

type Service struct {
   ID        unit `json:"id" gorm:"primary_key"`
   Name string    `json:"name" gorm:"not null"`
}

However, I do not know how to write the composite table.
Answer: you need to create extra model like this:
package database

type IndexService struct {
  WriteActive bool `gorm:"not null,DEFAULT false"`
}


update a table with serial primary key and another table with a referencing foreign key (postgres)

Question: I have two tables with a primary key/foreign key relationship
primary key table:
create table table_one (
    table_one_id_field serial,
    field1 varchar (100) not null,
    field2 varchar (100) not null,
    constraint pk__table_one primary key (table_one_id_field)
);
create unique index ix_table_one one table_one (field1, field2)

foreign key table
create table table_two (
    table_two_id int not null,
    table_one_id_field int not null, -- the foreign key
    field a int,
    field b int,
    constraint pk_table_two primary key (table_two_id)
    constraint fk_table_two foreign key (table_one_id_field) references table_one (table_one_id_field)
);

I'm not sure what the best way is to update both of these tables. My first thought was to do something like this:
insert into table_one
(field1, field2)
values
('val1', 'val2')
on conflict (field1, field2) do nothing
returning table_one_id_field

and then to use the returned value to update table_two. However, if the conflict does exist, then the id is not returned. My second idea was to run the same query without a returning statement and then to run a select query
insert into table_one
(field1, field2)
values
('val1', 'val2')
on conflict (field1, field2) do nothing;

select table_one_id_field from table_one where field1 = 'val1' and field2 = 'val2'

but I'm not sure if that is the safest way to do it. Is there another best practice way to achieve this?
Comment: I think the second approach is OK. For another option see: https://stackoverflow.com/a/42217872/330315
Answer: returning can't give you the id of a row that was not inserted, so selecting again after the insert seems like the relevant approach. You can do both operations at once with common table expressions:
with
    params as (values('val1', 'val2')) v(field1, field2),
    ins as (
        insert into table_one (field1, field2)
        select * from params
        on conflict (field1, field2) do nothing
    )
select t.table_one_id_field
from table_one t
inner join params p
    on p.field1 = t.field1 and p.field2 = t.field2


Remove "he" from all the Hebrew node URLs

Question: All the nodes of my Hebrew site using Drupal 8 have this problem: The URL of all the nodes of my Hebrew site are similar to htts://www.example.com/he/node/1, instead of https://www.example.com/node/1. The difference is that now URLs contain /he/, which I have never added.
It happens even when a node has its language set to English or Not specified.
What I tried is the following:

I changed all nodes written for English speaking audience from Hebrew to English and I flushed the cache. This didn't help: The URLs still contained /he/.

I thought it could be caused by the Alternative hreflang module, but uninstalling it did not resolve the issue, even after flushing the cache.
Answer: Deactive the URL detection method from /admin/config/regional/language/detection.
Answer: If you have translations, you should not turn off the URL detection method. Instead, you should change the domain prefix in the language settings for Hebrew to have no domain prefix.


How can I repeat parent table field only once for a group of child table fields?

Question: I am using Drupal Views module. I have Student accounts table that can have multiple students in it. Is there a way to create a table like the following?
<code>╔════╦═════════════╦═════════════╦═══════╦═════╗
║ id ║ Title       ║ Student Name║ Gender║ age ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Jack        ║ Male  ║ 50  ║
║    ║             ╠═════════════╬═══════╬═════╣
║    ║             ║ Smith       ║ Male  ║ 33  ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Ellis       ║Female ║ 42  ║
║    ║             ╠═════════════╬═══════╬═════╣
║    ║             ║ Joe         ║ Male  ║ 43  ║
╚════╩═════════════╩═════════════╩═══════╩═════╝
</code>
My current table shows the data like this:
<code>╔════╦═════════════╦═════════════╦═══════╦═════╗
║ id ║ Title       ║ Student Name║ Gender║ age ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Jack        ║ Male  ║ 50  ║
║════║═════════════╠═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Smith       ║ Male  ║ 33  ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Ellis       ║Female ║ 42  ║
║════║═════════════╠═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Joe         ║ Male  ║ 43  ║
╚════╩═════════════╩═════════════╩═══════╩═════╝
</code>
I want to avoid the repeat of of id and title columns.
Any idea how to do this?
This is the setting for my view:
Comment: Dear @Jdrupal, I know this is possible to alter the view, but I want to tackle this using View's Configurations.
Comment: I'd probably go with custom JS here. Tables are always a pain.
Answer: The only way I can think of doing this without custom coding is by using the Views Field View where you create two different Views Displays, one with the contextual filter, save them both, then "embed" the contextual one into the other view.
This type of database query can be very performance intense, and caching is recommended. Or avoid it if you can.
In your case you can keep your original accounts view, but remove the student fields. Add another Display (Block) that is showing student name gender and age, and add a contextual filter for the account, save the view. Then in your original views display add the field for the student info.
You may need to adjust how the labels are shown, so you don't have them duplicate/in odd places because of the recursion.


Why is this substitution in the double integral effective?

Question: I'm working with double integrals, and came about a problem where I had to calculate the following integral:
$$ \int \int_D \left | 3x+4y \right|dx dy$$
where D is the region contained within the circle whose equation is given by $x^2+y^2 \leq 2$.
At first I thought I directly might use polar coordinates, but that seemed to complicate things when we have absolute values in the integrand. I went to check on if there was any hints to the problem, and there was.
The book hinted that a substitution of the form
$$\begin{pmatrix}
u \\v \end{pmatrix} = \begin{pmatrix}3/5 & 4/5 \\-4/5& 3/5 \\\end{pmatrix} \begin{pmatrix}x \\y \end{pmatrix}$$
And when I made that substitution, I realized that the new region, let's call it $A$ became $u^2+v^2 \leq 2$, the Jacobian became 1, and the double integral became:
$$\int \int_A 5 |u| du dv$$ which then easily can be calculated through polar coordinates.
It was the first time seeing the substitution, so I tried to generalize it for a double integral of the form:
$$I := \int \int_D \left | \alpha x +\beta y \right | dx dy$$ where $D$ is a region given by the circle whose equation is $x^2+y^2 \leq \gamma^2$. I later used the same method. First I let:
$$\begin{pmatrix}
u \\v \end{pmatrix} = \frac{1}{||(\alpha, \beta)||}\begin{pmatrix}\alpha & \beta \\- \beta& \alpha \\\end{pmatrix} \begin{pmatrix}x \\y \end{pmatrix}$$
Then, as previously, I get the equivalent region $A$ given by $u^2+v^2\leq \gamma^2$, and the Jacobian $J = 1$, just as in the previous numerical example. We also realize that $\left| \alpha x +\beta y \right | = ||(\alpha, \beta)|| \cdot|u|$, and so our double integral just becomes:
$$||(\alpha, \beta)|| \int \int_A |u| dudv$$
which then, through polar coordinates, gives us that $I$ can be evaluated to $\frac{4 ||(\alpha, \beta)|| \gamma^3}{3}$.
What I realized from this, is that this substitution is really efficient for calculating double integrals with the given integrand. However, I can't really geometrically see how these transformations look like.
I think that if someone could provide any geometrical intution on what these transformations look like between the $xy$ - plane, to the $uv$ - plane and to the $r\theta$ - plane, this would really deepen my understanding on why this substitution is efficient in the way it is.
Thank you in advance for any such contributions.
Comment: $xy \to uv$ is a rotation (presumably) to a more favorable coordinate system.
Answer: This transformation is a rotation of the plane, since $\begin{pmatrix}\alpha & \beta \\- \beta& \alpha \\\end{pmatrix}$ is a rotation matrix for $\alpha,\beta$ satisfying $\alpha^2+\beta^2=1$. This makes it clear why the domain of integration remains a circle and also why the Jacobian determinant is $1$ (rotations don't stretch the plane).
The function you're integrating is $z=|3x+4y|$, and other than the absolute value, the graph of this function is a plane $M$ in $\mathbb{R}^3$. By rotating the $x,y$ plane to become a new plane with basis vectors $u,v$ we can make $M$ be the graph of a function of the form $z=k u$ (or $z=kv$). Geometrically this is possible since we can rotate until the function describing the plane "rises only along one of the coordinates" $u$ or $v$, that is, is constant along the other coordinate.
Concretely, we want a rotation which aligns one of the coordinates with the direction of steepest ascent. Steepest ascent means largest directional derivative and this happens along the direction of the gradient, that is, along $(3,4)$, or when normalized, $(\frac{3}{5},\frac{4}{5})$. The rotation matrix which sends $(1,0)$ to $(\frac{3}{5},\frac{4}{5})$ is \begin{pmatrix}3/5 & -4/5 \\4/5& 3/5 \\\end{pmatrix}
so that after the rotation the plane $M$ is going to be the graph of $z=ku$ (here $k=5$).
Comment: Thank you for that beautiful explanation! I get what's happening now :)


Graphs with vertices consisting of all strings, which share an edge if they differ on all coordinates

Question: Let $\Sigma$ be some alphabet, and let $j$ be an integer.
I'm interested in the graph $G$ in which $V(G)$ is the set of all strings of length $j$ over $\Sigma$, and two strings share an edge if they differ on every coordinate.  That, $s$ and $t$ share an edge if $s[i] \neq t[i]$ for every $1 \leq i \leq j$.
This graph is quite simple if $\Sigma$ is the binary alphabet, but gets complicated quickly.
I want to know if this graph has been mentioned in the literature.  Does it have a name?  Does it belong to a special class of graphs?  Any kind of information that would've been published.
Comment: The most trivial case is $|\Sigma| = 1 \ddot\smile$
Answer: This graph is a member of an association scheme, the Hamming scheme
$H(j,|\Sigma|)$. From this it's possible, for example, to derive expressions for the eigenvalues; it has the same eigenvectors as the Hamming graph.
The Hamming scheme can be viewed as the set of graphs with vertex set $\Sigma^j$, where two strings are adjacent in $r$-th graph if and only
If they differ in exactly $r$ positions.


Binary Search Trees and Data with Python

Question: I have a binary tree function with 3 pieces of data in each node. They are classified by id numbers. They also hold "Name" and "Mark"
A certain function I'm having problem with is a name searching function, it looks like this:
def findName(tree,name):
    if tree==None:
        return None
    elif tree['name']==name:
        return True
    else:
        findName(tree['right'],name)
        findName(tree['left'],name)

I can always find the first name in a tree, but i can't find any onwards. If I input findName(tree['right'],name) in the python idle I get true if the name is in the tree.
Answer: the only way for a function to actually return some data, is if it itself uses a return statement.  Your else: suite doesn't contain any return statements.
Comment: First off I love the username. :P and Yeah I assumed that since it was recursive it would be returning the True. Thank you.
Answer: on the else you would have to do something like:
return findName(tree['right'],name) or findName(tree['left'],name)

so that it searches in both branches and if it finds it in any of those branches the return value will be True
Answer: I believe there are opensource binary search tree modules available; if your goal is to learn about BST's, by all means write your own, but if you're working on something that is amenable to opensource, you might want to try a canned module that's already been tested and debugged.
I have something kind of like a BST for Python at http://stromberg.dnsalias.org/~strombrg/treap/ .  It's actually a variant of a BST that doesn't require keys to be fed to the BST in a random order - it uses a random value on each node to scatter things.  To the programmer, it looks like a dictionary except the keys come back sorted when you iterate over them, and lookups aren't as fast as a dictionary (hash).
Treaps were discovered back in the late 80's, I believe, so they're a relatively recent bit of CS.  They're a very well-rounded datastructure; the more different ways you access the same data, the better off you are likely to be with a treap.
Actually, from what you've described, you might even be better served by just a dictionary (hash table) where the keys are your names.


Appropriate problems for different type of ML classifiers

Question: I have learned several classifiers in Machine learning - Decision tree, Neural network, SVM, Bayesian classifier, K-NN, Markov process...etc.
Can anyone please help to understand when I should prefer one of the classifier over other - for example - in which situation(nature of data sets, etc) I should prefer decision tree over neural net OR which situation SVM might work better than Bayesian OR what types of problems are appropriate to apply decision tree, neural net, k-nn, markov processs or SVM or bayesian ??
Thanks.
Comment: boosting with trees seems like its a good default classifier - non parametric + regularised model search.
Comment: The question is too broad. There are books written about it and even then it all comes down to so many factors, tricks and tweaks that it is hardly feasible to have a reasonable answer, no matter how long...
Answer: There are tons of literature on the subject, but I have here a slightly subjective view that, I hope, does not duplicate other answers.
The first important thing -- performance of an ML algorithm is not the only criterion that one should consider. For me, the two other criteria are (i) simplicity and (ii) transparency, and arguably both of these are linked.
Simplicity means the simplicity of the algorithm used. This has many ramifications; first of all, in my subjective view, statistics in science is about convincing yourself and your peers that the effect seen is "real" (or, that it is unlikely to be random). If you have to rely on a magic box which works in mysterious ways (or you just don't understand how it works), you will not be able to trust its results.
Transparency means that you are able to discover why your ML model classifies the data like it does, select important variables based on the ML model (e.g. using loadings from PLS or Gini index from random forests), construct a simplified model etc.


PHP Dropdown from Mysql, Print Results

Question: I have created a dropdown list and populated it with Mysql.
I am trying to fetch the results of the users selection to show on 2 different pages
permanently but I can't get it to work.
here is my code:
<?php
    // Connect to the test datbase on localhost
    // That's where we created the countries table above
    mysql_connect('localhost','jakeray','pass');  mysql_select_db('wordpress');

    // Query the countries table and load all of the records
    // into an array.
    $sql = 'select * FROM manufacturers';
    $res = mysql_query($sql) or die(mysql_error());
    while ($rec = mysql_fetch_assoc($res))
    $manufacturers[] = $rec;
    ?>

    <?php
    echo '<select action="select.php" name="dropdown" class="select">';
    foreach ($manufacturers as $c)
    {
    if ($c['id'] == $_GET['id'])
    echo "<option value=\"{$c['id']}\" selected=\"selected\">{$c['mfg']},               {$c['info']}</option>\n";
    else
    echo "<option value=\"{$c['id']}\">{$c['mfg']} {$c['info']}</option>\n";
    }
    echo '</select>';
    ?>

    <?php
    if(isset($_POST['select']))
    {
    $manufacturers=mysql_real_escape_string($_POST['dropdown']);
    $result=mysql_query("SELECT FROM manufacturers");
    $row=mysql_fetch_assoc($result);
    print $row['mfg'];
    }
    ?>

I need to display the manufacturer permanently on 2 pages. Not sure if this is right.
How do I fetch the results of the selection from the database on two different pages and make it stay
longer after the session expires.
Comment: store the data in a db use that to repopulate the page
Comment: So when the user selects the data I need to send that data to another database to then send to the page i  want it display on?
Comment: yes, if you want to keep it, then you have to store it somewhere
Answer: Change $_POST['select'] to $_POST['dropdown']. Once they choose the manufacturer, you can:

Store their choice in the database, possibly associated with their user's row if they're logged in
Store their choice in the $_SESSION, if you're using PHP sessions.

PHP Dropdown from Mysql, Print Results


What are the rules for a non-seasonal transfer?

Question: Do current FIFA transfer rules allow for transfer out of the window period in any circumstances (excluding free transfers or loan recalls)?
The recent example was Mascherano's transfer from West Ham to Liverpool in February of 2007 for which special dispensation was asked from FIFA.
Comment: Mascherano's transfer to Liverpool was NOT non-seasonal. It was in the winter transfer window. But normaly a player can not change the club twice in one season (transfered from Corinthians to West Ham in the same season). That was the special permission for this transfer about.
Answer: Players are not allowed to be transferred at any time expect during the pre-determined transfer windows. These windows are determined by the respective nation's association. For example, England's transfer windows are from 1 July to 1 September (summer/pre-season window) and from 1 January to 31 January (winter/mid-season window). In Spain the dates are 1 June to 31 August (summer) and 1 January to 2 February (winter). The players must be registered according to FIFA's Regulations for the Status and Transfer of Players, which states that:

Players may only be registered during one of the two annual registration
    periods
    fixed by the relevant association. As an exception to this rule, a
    professional whose contract has expired prior to the end of a registration
    period may be registered outside that registration period. Associations are
    authorised to register such professionals provided due consideration is given to
    the sporting integrity of the relevant competition. Where a contract has been
    terminated with just cause, FIFA may take provisional measures in order to
    avoid abuse.

A recent example is the failed move of David de Gea from Manchester United to Real Madrid. The paperwork was not completed before the Spanish deadline of 11.30 pm on Aug 31. Thus the move could not be completed even though the English transfer window was still operational.


Set the focus to a HTML Textbox or Button in a WebBroswer control

Question: I am opening a website in a WebBrowser control using VB.NET 2008. On the fourth page of the website, I want to focus the control by triggering the tab key programmatically. I am using the following code:
If adtxt.Text = "http://aojsl.com/dfassfeed2.php" Then
    System.Windows.Forms.SendKeys.Send("{TAB}")
End If

However, my code is unable to trigger the tab key. Does anyone know how to make this work?
Comment: What does "my code is unable" mean? Do you get an error message? What exactly happens? What does it do when you use the debugger with a break point on the `If adtxt.Text` line?
Comment: Where are you putting this code?
Comment: Dont use the TAB key, I'll find you a more reliable method to set the focus to a HTLM element in the WebBrowser control
Comment: actually  there is a button on the 4th page of the website  i want to bring the focus control on that button So i am using this code
Comment: Did you need any further clarification? If you want to use the Tabs I can help you, you just use the second method and then the WebBrowser control will have focus.
Comment: @Jeremy Thompson ..... Is th e method 2 is in c# coding???
Comment: No I converted it into VB.Net using http://CodeChanger.com, I got the code from the Microsoft thread, doesn't the code work?
Answer: Method 1
Private Sub Form_Load()
    WebBrowser1.Navigate "http://www.google.com/"
    Do
     Thread.Sleep(100)
    Loop While webBrowser1.IsBusy = True
End Sub

Private Sub Command1_Click()
    WebBrowser1.Document.All("q").focus 'Set focus to the search text field
End Sub

Private Sub Command2_Click()
    WebBrowser1.Document.All("btnI").focus 'Set focus to the google "I Am feeling lucky button"
End Sub

Method 2
I converted it to VB.Net from this MSDN thread: Focus issues with System.Windows.Controls.WebBrowser
You will need to change the ActiveElement in webBrowser.Document.ActiveElement.Focus() to the textbox or button.
Public Partial Class Form1
    Inherits Form
  Public Sub New()
    InitializeComponent()
    Dim host As New WindowsFormsHost()
    im webBrowser As New WebBrowser()
    host.Child = webBrowser
    elementHost1.Child = host

    webBrowser.Navigate(New Uri("http://www.google.com"))
    Me.Activated += Function() Do
      Console.WriteLine(Me.ActiveControl)
      If webBrowser.Document <> Nothing Then
        If Me.ActiveControl = elementHost1 AndAlso webBrowser.Document.ActiveElement <> Nothing Then
          webBrowser.Document.ActiveElement.Focus()
        End If
      End If
    End Function
  End Sub
End Class

Method 3
Another way might be to do it in the HTML, eg:
OnLoad="document.myform2.mybutton.focus();">

Answer: lets say that the html of youre page is:
<button id="btn">Ok</button><input id="txt">

you can set focus in this way:

If adtxt.Text = "http://aojsl.com/dfassfeed2.php" Then
    webbrowser1.document.getelementbyid("btn").focus()
    webbrowser1.document.getelementbyid("txt").focus()
End If

Comment: but my program is unable to get id
Answer: Another way:
use the GetElementsByTagName(TagName)
lets say that your html is:
<button>no</button>
<button>no</button>
<button onclick='alert(1);'>--focus me!--</button>
<button>no</button>

   Dim Elems As HtmlElementCollection
        Dim WebOC As WebBrowser = WebBrowser1
        Elems = WebOC.Document.GetElementsByTagName("button")
        For Each elem As HtmlElement In Elems
            If elem.InnerHtml = "--focus me!--" Then
                elem.Focus()
                elem.InvokeMember("click")

            End If

        Next

another one:

Dim num As Integer = 1
        Dim elms As HtmlElementCollection
        Dim wb As WebBrowser = WebBrowser1
        elms = wb.Document.GetElementsByTagName("button")
        For Each elem As HtmlElement In elms
            If elem.Id = "" Then
                elem.Id = "button" & num.ToString
                num = num + 1
            End If
        Next

        WebBrowser1.Document.GetElementById("button3").Focus()

Comment: give me the html of your page and i try to customize my code.
Comment: I think so that its solution is by triggering TAB key programatically. But i dont know the code for triggering the TAB key . So can u plz tell me how to trigger TAb key presses Automatically by program code??
Comment: How can i send u the HTML of page ?
Comment: Dont use the "SendKeys" , if you want that your program works call the html element. you can just sendkeys.send("{TAB}") but is not the solution.
Comment: Listen i am using "    System.Windows.Forms.SendKeys.Send("{TAB}") " but it is just focusing the control on first page of the website . But is not working on the 4th page of the website. Any opinion about this ????
Comment: On the first page  u have to login  on the second page u have to select an assignment  on the 3rd page u have to fill a form and on the 4th page u have to press a button named next
Comment: Send keys.Send("{TAb}") id working on the 1st page of the website . Y it is not working on the 4th page of the website
Comment: maybe your page is not fully loaded and then you can't call the elements. send me the html of the page to my email: firstname.lastname@example.com
Comment: ok i have sent the mail to u . check the mail and tell me either u have got the files???
Comment: i got this. check youre mail. :)
Answer: To focus the select element by using the focus function in vb.net. For exsample,
Me.WebBrowser1.Document.All.Item("password").Focus()

This will put the focus on the element called password!
Use Me.WebBrowser1.Document.All.Item("YOURelement") to find the correct element and then add .Focus() to focus on the one you want! :D
Answer: Do this Me.WebBrowser1.Document.All.Item(textbox1.text).Focus()
make a Textbox and then if you want to Spambot it easy Detects everytime your Typ you Write and Send


Functional vs. imperative style in Python

Question: I've been spending some of my spare time lately trying to wrap my head around Haskell and functional programming in general.  One of my major misgivings has been (and continues to be) what I perceive to be the unreadability of terse, functional-style expressions (whether in Haskell or any other language).
Here's an example.  I just made the following transformation in some code for work:
def scrabble_score(word, scoretable):
    score = 0
    for letter in word:
        if letter in scoretable:
            score += scoretable[letter]
    return score

to
def scrabble_score(word, scoretable):
    return sum([scoretable.get(x, 0) for x in word])

The latter was a lot more satisfying to write (and, keeping in mind that I myself am the one who wrote it, to read too).  It's shorter and sweeter and declares no pesky variables that might become a headache if I made any mistakes in typing out the code.  (BTW I realize I could have used the dict's get() method in the imperative-style function, but I realized it as I was performing this transformation, so I left it that way in the example.)
My question is: despite all that, is the latter version of the code really more readable than the former?  It seems like a more monolithic expression that has to be grokked all at once, compared to the former version, where you have a chance to build up the meaning of the block from the smaller, more atomic pieces.  This question comes from my frustration with trying to decode supposedly easy-to-understand Haskell functions, as well as my insistence as a TA for first-year CS students that one of the major reasons we write code (that's often overlooked) is to communicate ideas with other programmers/computer scientists.  I am nervous that the terser style smacks of write-only code and therefore defeats the purpose of communication and understanding of code.
Comment: Just a comment about your code in the second version: I don't think you actually need to make a list. You can just say `sum(scoretable.get(x, 0) for x in word)`.
Comment: The trouble with these sort of comparisons is that regardless of how readable a particular language and style is "objectively" (however you manage to define that in an objective sense), programmers get *very good* at reading whatever languages and styles they actually work with. An unfamiliar style *always* seems less readable than what you're used to, regardless of merit.
Comment: One might argue that it would be more _pythonic_ to use `sum(score_table[letter] for letter in word)` and allow for `KeyError` unless it is expected that there are letters that are not in `scoretable`
Comment: Thanks, @pandubear, I did not know you could do that!
Answer:
My question is: despite all that, is the latter version of the code really more readable than the former? It seems like a more monolithic expression that has to be grokked all at once

I would say it's more readable, though not necessarily the most readable option. Yes, it's more logic in one line, but this is outweighed by three facts.
First, you can still mentally decompose it into smaller parts and understand those individually before combining them. I immediately see that you're summing something (at this stage I don't have to know what you're summing). I also see that you get the entries from scoretable for each letter, defaulting to 0 if not present (at this stage I don't have to know what then happens to this list). These things can be identified and understood independently.
Second, there are very few somewhat-independent parts, maybe two or three. This is not unreasonable to understand at once, the "monolithic" aspect is more of a problem when dozens of concerns sit next to each other.
Lastly, the supposed advantage of the first version,

compared to the former version, where you have a chance to build up the meaning of the block from the smaller, more atomic pieces.

is also a problem: When I start reading, I see a for loop. That's nice, but it doesn't actually tell me anything yet (except that there is a loop, which doesn't help me understand the logic, only its implementation). So I have to keep this fact in mind and read on to later resolve what this loop means. To an extent, this is true of any code, but it gets worse the more code there is. Likewise, the score = 0 line doesn't mean anything on its own, it's just one tiny implementation detail that nobody needs to know to understand that this function computes a word's scrabble score by adding up the score for each of the word's letters.
When reading your imperative loop, one has to keep track of multiple mutable variables, control flow, etc. to figure out what happens, and has to piece the parts together. In addition, it's simply more characters to read, and hence it would take longer to comprehend even if understanding was instant in any case. You have to take these costs into account. Whatever you might gain by having each line be simpler is lost to this effect.
That said, the following version is arguably cleaner, precisely because it splits the two parts of the algorithm into separate lines:
def scrabble_score(word, scoretable):
    letter_scores = [scoretable.get(letter, 0) for letter in word]
    return sum(letter_scores)

But the difference is rather small, it's rather subjective. Both are fine and much better than your first version. (Oh, another thing: I'd use a generator expression rather than a list comprehension, I only kept the list comprehension to minimize noise.)
Answer: These things are primarily a matter of taste. It should be remembered that taste is itself a matter of education and experience - you find longer, imperative code more readable because that is the only thing you have learned to read (so far).
I find your second form more readable because I'm used to the form of functional style, and I understand all of the elements in it. I frequently find concise haskell code indecipherable because I haven't learned all of the operators.
The practical solution seems to me: (a) use comments (b) avoid anything excessively clever (c) explain anything clever you choose to do (d) concise and unindented is usually easier to read than voluminous and deeply indented; and (e) remember your audience.
To apply those principles to this case: in python you would expect things that can be expressed through simple functional operations to be expressed in that way, and so your audience should be comfortable with it. Your code in any case needs a comment to explain that you do (or don't) intend to silently ignore invalid (unscored) characters.
Answer: I think the concise style is nice because you are free to expand it in cases just like this one, without wasting lots of vertical space on control structures like for an if in the first.  For instance
def scrabble_score(word, scoretable):
    # local function to look up a score in the table
    def get_score(x): return scoretable.get(x,0)

    scores = map(get_score, word)  # convert word into a list of scores

    return sum(scores)

I find this the most readable, even though it takes a few more lines.  I'd consider this to be in the declarative style.
Comment: Unidiomatic code is more difficult to read because it is likely to be unfamiliar to the reader. Your position that the most readable form is the unidiomatic form gives functional programming a bad name because it communicates that functional programmers are not interested in communicating with people who have learned all about functional programming.
Comment: OK, fair enough.  As I understood the question, python was merely being used as an example, ignoring any customs or idioms specific to a particular language.  I certainly agree that idiomatic code in any language is more readily understood.
Comment: The very fact that you are defending it by referring to haskell idioms demonstrates the problem: this is not idiomatic python. It doesn't matter that it might be idiomatic haskell. It's unidiomatic because the usual python idiom for mapping an expression is to use a comprehension, not a local function.
Comment: Nope. Feel free to disagree.  I didn't take a stand in my post so there's not really anything to disagree with.  I gave an example of some code I consider readable that also fits the "functional" style.  I don't really understand your point that unidiomatic python code gives functional programming a bad name though, and you seemed a bit defensive. That's all.
Comment: -1 This is deeply unidiomatic, thus combining the worst of all worlds. Unidiomatic use is what gives functional programming a bad name.
Comment: "worst of all worlds"  I appreciate your enthusiasm but this comment is not helpful at all.  What is unidiomatic about this?  It is the python counterpart to using let and where in haskell.


Diferença entre uma linguagem bloqueante e uma linguagem não bloqueante

Question: Na prática, qual a diferença entre uma linguagem bloqueante e uma não bloqueante?
Quais as diferenças que podemos observar tanto no front-end como no back-end?
Utilizando um exemplo, vamos imaginar um endpoint de uma API em que algo é escrito num banco de dados e é devolvido ao cliente uma resposta qualquer.
Se várias requisições são feitas ao mesmo tempo para esse endpoint, na prática como se comportaria um sistema com uma arquitetura bloqueante e outro não bloqueante?
Comment: É linguagem ou algoritmo? Nunca vi o termo ser usado para uma linguagem.
Comment: @bigown pensei que esse termo era usado como característica de uma linguagem. Seria interessante a resposta começar explicando que isso é um erro. Essa questão surgiu porque comecei a estudar NodeJS.
Answer: Explicação
Em um sistema bloqueante as requisições seriam enfileiradas e depois disso seriam processadas uma a uma, dessa forma não seria possível processar várias delas ao mesmo tempo. Ou seja o cliente que tem a requisição mais nova só terá sua requisição processada depois que as requisições mais velhas tiverem sido processadas por inteiro.
E nas não-bloqueantes teremos que a requisição do cliente mais novo poderá ser processada (ou pelo menos uma parte dela) antes que todas requisições que o servidor recebeu antes dela sejam processadas.
Exemplo
Supondo que o exemplo é um sistema de PetShop, e que a requisição tem como finalidade adicionar um Animal que pertence a um Dono ao Banco de Dados e adicionar esse Dono caso não esteja no Banco de Dados.
Bloqueante
O Cliente que enviou a requisição mais antiga só terá o Animal e o Dono no Banco de Dados depois que todas as outras requisições já foram processadas. No pior caso teremos uma operação de I/O que demore horas, e assim o cliente mais novo não terá sua resposta a sua requisição tão cedo.
Não Bloqueante
O Cliente que enviou a requisição mais antiga poderá ter pelo menos o Animal registrado no Banco de Dados mesmo que ainda tenha requisições mais antigas sendo processadas. Nesse caso mesmo que o I/O demore o sistema ainda atenderá a outras requisições.


Como utilizar autenticação via token com WebApi .Net

Question: Estou olhando alguns sites sobre autenticação baseada em token usando a biblioteca OAuth mas surgiu uma dúvida.
Eu tenho uma webapi que já expõe serviços tanto para um App quanto para um Site. Já temos um sistema de login com banco de dados SQL funcionando. Porém agora gostaríamos que toda requisição na webapi seja validada via token. Eu instalei e configurei todos packages necessários, editei a classe Startup etc mas travei no seguinte problema.
Quando o site ou o app faz o login utilizando meu serviço, exemplo http://meuservico/api/Login, e eu valido o login no banco, gostaria de chamar a criação do token e guardar esse token o resto do dia para chamada de outras actions e controllers. Exemplo, a pessoa logou e vai até o menu de cadastro ou alteração de dados, quando ele chamar o serviço novamente http://meuservico/api/AlteraDados eu coloco um [Authorize] no método apenas ou ainda preciso fazer algo para comparar se o token que ele criou ao se logar ainda é o mesmo?
Answer: Se a autenticação for por token, o mesmo deve ser enviado em todas as solicitações e validado. Tanto quanto a existência quanto a validade do token, pois e uma boa prática que ele tenha um tempo para expirar.
Você pode utilizar o OAuth2 do ASP.net para gerar o token e validar o mesmo, veja no link a seguir o tutorial da microsoft para tal. Autenticacao para web API
Comment: vou dar uma olhada no link. obrigado.
Answer: Não me ficou muito claro a sua dúvida, mas não há necessidade de um if para comparar o token, o próprio framework faz isso internamente.
Exemplo:
No seu startup.cs , provavelmente você terá um método parecido com esse:
public void ConfigureOAuth(IAppBuilder app)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new SimpleAuthorizationServerProvider()
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

Nesse método é definido o endpoint e o tempo que o token irá durar
Você também deve ter um provider mais ou menos assim
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            using (IUserRepository _repository = new UserRepository(new Data.DataContexts.OAuthServerDataContext()))
            {
                var user = _repository.Authenticate(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);
        }
}

Para autenticar você precisa fazer uma requisição nesse endpoint passando as três informações

grant_type
username
password

Após isso você receberá como resposta um token
Por fim, em toda action  que estiver decorada com o [Authorize] será necessário que o token esteja no header da requisição, com o atributo Authorization
Caso o token seja invalido retornara Forbbiden 403.
obs: o token é composto por informações e podemos tanto adicionar como capturar tais informações, note que no bloco identity.AddClaim(new Claim("role", "user")); é adicionado o userno token
Comment: essa era minha dúvida. se no [Authorize] ele ja validava esse token. muito obrigado.


Problema ao gerar Migration com EF Core e .NET 8

Question: Estou com o seguinte problema ao gerar a seguinte migration >
PM> Add-Migration CriadoTabelaTarefa -Verbose -Context TarefaContext
Unable to create a 'DbContext' of type 'TarefaContext'. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[PMQ.GerenciamentoTarefas.Infra.Data.Context.TarefaContext]' while attempting to activate 'PMQ.GerenciamentoTarefas.Infra.Data.Context.TarefaContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Assim está o meu código,
Dbcontext:
    public class TarefaContext : DbContext
    {
        public TarefaContext(DbContextOptions<TarefaContext> options) : base(options)
        {
        }

        public DbSet<Tarefa> Tarefas { get; set; }
    }

E assim está minha Startup:
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddEndpointsApiExplorer();
        services.AddSwaggerGen();

        services.AddDbContext<TarefaContext>(options => options.UseOracle(Configuration.GetConnectionString("DefaultConnection")));

        MediatorInjection.AddMediator(services);
        //DependencyInjection.AddServices(services);
    }

    public void Configure(WebApplication app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();

        app.UseAuthorization();

        app.MapControllers();
    }
}

OBS: Meu Context está em um projeto de Infra.Data e claro meu Startup no projeto da API.
Alguém já passou por isso, poderiam me ajudar?
Answer: Consegui resolver atualizando a biblioteca Pomelo para versão 8.0.0-beta.2
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.0-beta.2" />

Answer: Uma pergunta, o comando da Migration, você está rodando a partir de qual projeto? Está rodando na raiz da solution do projeto, ou dentro do projeto de infraestrutura na qual contém o Context?

Validar se você tem uma classe de configuração para cada entidade sua, isto é uma classe na qual dizemos para o Entity que ele terá propriedades e chaves primárias e relações.
Segue o exemplo abaixo, de um diretório chamado Configurations dentro do projeto de Infraestrutura, com uma classe chamada UserConfiguration.cs

public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasKey(u => u.UUID);

        builder.Property(u => u.Name);
        builder.Property(u => u.Email);
        builder.Property(u => u.Password);
        builder.Property(u => u.CreatedAt);
    }
}

Validar se você tem um diretório chamado Migrations no seu projeto de infraestrutura, ou, você pode adicionar ao comando da migration, este argumento --output-dir Migrations
Validar se no seu TarefaContext, contém este trecho de código abaixo:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
      modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}

Caso todas as opções estejam válidas, siga para a leitura abaixo.
Você pode rodar o comando pelo terminal da seguinte forma. Vá para a raiz da sua solution, e execute o comando abaixo, lembrando para que você troque os path dos projetos para os seus respectivos projetos. Coloquei um exemplo de um código meu para ficar mais fácil o entendimento do comando.
dotnet ef migrations add --project Visualizesse.Infrastructure/Visualizesse.Infrastructure.csproj --startup-project Visualizesse.API/Visualizesse.API.csproj --context Visualizesse.Infrastructure.DatabaseContext

Caso, não dê certo, adicione o --verbose para termos um stack trace mais completo.
Uma possível causa de erro ao rodar o comando acima, pode ser que apareça para baixar o NuGet Package Microsoft.EntityFrameworkCore.Design, e ele deve ser instalado no projeto da API, digo isso pois quando rodei o comando acima, ele mostrou que faltava este NuGet, ao baixar, rodei novamente o comando e funcionou, eu espero que para você funcione também.


Dummy variables in multiple regression, why use an intercept?

Question: When performing a multiple regression with dummy variables, is it really necessary to include an intercept term in the design matrix?
By dummy variables, I mean indicator variables; a one in the design matrix if some effect is present, and a zero if not.  It seems to me that without the intercept it is simpler to interpret the OLS solution.  Instead of
$\beta_{0}$ = $\mu_{A}$ (where $\beta_{0}$ is the intercept)
$\beta_{1}$ = $\mu_{B} - \mu_{A}$
$\beta_{2}$ = $\mu_{C} - \mu_{A}$
etc.
We have
$\beta_{1}$ = $\mu_{A}$
$\beta_{2}$ = $\mu_{B}$
$\beta_{3}$ = $\mu_{C}$
etc.
Do the computations of $R^{2}$, the F-statistic and t-statistics change?
What if a continuous independent variable is then included?
Comment: Biggest problem: this approach doesn't generalize well. If you have two factors, you still have to leave something out.
Comment: Also discussed here:  https://stats.stackexchange.com/questions/215779/removing-intercept-from-glm-for-multiple-factorial-predictors-only-works-for-fir/218034#218034
Answer: Things like the predictions, residuals, full-reduced model tests, etc. will not be affected by the change that you propose, but what does change is the interpretation and tests on the individual terms.
Most regression routines will provide an automatic test of whether a term is 0 or not.  This is meaningful when a term represents the difference between two group means (what we get when we include an intercept), but is testing whether each of the group means equals 0 meaningful?  The same goes for the confidence intervals and we usually want to know if groups differ from each other.  If every term just represents a mean then we compute confidence intervals for the means, then people try to interpret the amount of a difference by seeing if the intervals overlap, but this is very inferior to looking at a confidence interval on a difference.
Comment: @PeterRabbit, You could see this for yourself by fitting both models to the same dataset (either an example dataset or just simulate some data) and see what is different in the summaries and what stays the same.
Comment: @caracal, I agree that multiple factors complicate things.  The fact that this messes with type III SS is an argument against using type III SS, see http://www.stats.ox.ac.uk/pub/MASS3/Exegeses.pdf.
Comment: Thank you for the great answer! This makes a lot of sense to me.  You didn't mention if adding a continuous independent variable changes the interpretation.  Sorry if it's obvious, I am having a hard time understanding.  Thanks again!
Comment: @PeterRabbit, adding a continuous variable does not change things, you still get an overall slope, the difference is whether each group has its own intercept (no intercept model) or if the individual terms represent a change from the overall intercept.  Both models have their place.
Comment: As @Glen_b pointed out, things get more complicated with multiple factors. E.g., in an unbalanced two-factorial ANOVA, SS type III model comparisons depend on the coding scheme - it has to be a sum-to-zero scheme like Helmert or effect coding.
Answer: @GregSnow is right that this change doesn't really matter.  Let me add a few details to extend that.  What you are talking about is sometimes called level means coding, whereas the default coding scheme is called reference level coding.  Note that there are many possible valid coding schemes.  If you have a categorical variable with only two levels, then the t-test of the beta that comes by default in the regression output with any statistical software is more meaningful when you had used reference level coding.
On the other hand, when you have a categorical variable with multiple categories, which coding scheme you use is just a matter of taste.  To get a predicted value, you will have to solve the regression equation for $\hat y$ at the relevant spot in the covariate space either way.  To test if the categorical variable is related to the response, you will need to use an F change test (discussed here) either way, etc.
To address your specific questions more concretely: if you use level means coding instead of reference level coding, the F-statistic will be the same; the t-statistics will change in that they will now test whether your level means are zero, as @GregSnow explains; and the inclusion of continuous covariates will be the same.


How to obtain user principal from Liberty's FORM based authentication in JSF page?

Question: So I have this JSF project that uses form based authentication. On the first attempt to open my JSF page, I get redirected to my login server. There the authentication takes place and on success I get redirected to my application. Unfortunately I don't know how to get the information that the authentication server provides, like username.
I have a page where a text is saying "Signed in as ".  should be set by a ManagedBean with the method getCurrentUserPrincipal().
<h:outputText value="#{myBean.getCurrentUserPrincipal()}"/>

The method is currently empty. I tried it with WSSubject.getCallerPrincipal() and FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal() but that returned null.
How can I get the information I need with that method?
Is it even possible?
I'm not sure what information you would need, so if something is missing, I will provide if I can.
Comment: How can we know where **your** authentication server puts the information? This question is in no way java, jsf, servlets or java-ee related.
Comment: Ok, where could the information be stored when I do a form based authentication (in web.xml). I get redirected to the login and on success back to my application. How is this not at least j2ee or servlet related? Let´s say it is stored in a cookie: How can I get the information from there? Or LTPA token (same as cookie?)? What then?
Btw. I´m using Liberty. Might I need some configuration in the server.xml?
Answer: Inject the principal into your managed bean like:
@Inject
private Principal principal;

then, based on your html above for outputText field, provide a getter in your managed bean something like:
public String getCurrentUserPrincipal() {
    return principal.getName();
}

Answer: After some digging I found out that our authenticating server was a siteminder service and the informations came back in a cookie (SMSESSION) and header information of the response.
So, it would be enough to read the header information to get the user name.
But the principal or subject would still return null. To get this and also make security working, I added a TAI to Liberty. How this is done, you can read here and here. My myTAI.jar is really simple. Because I have a ldap registry configured, I need the user security name (String, e.g. uid=..,ou=..,ou=..) of the given username (header) for further authentication and return this:
return TAIResult.create(HttpServletResponse.SC_OK, userSecName);
In the background Liberty will then do some further authentication and creates the principle and subject. If everything is correctly configured and the user is authorized to enter the application, he will and will have principle and subject objects available.
Comment: As you can see in the end, it is all not jsf, not java-ee (j2ee is the old abbreviation) and not servlet related in the sense that they do not play an active role in all this not working before... But great you solved it.


How to uniform 1 out of 7 chance, using 2 coins

Question: Using two coins, simulate a fair dice with 7 sides, A, B, C ,D ,E, F, G.
Coin 1:

Head 6/7
  Tail 1/7

Coin 2:

Head 50%
  Tail 50%

My approach
Step 1:
<code>------------- Coin1 -----------------
              /  \
             /    \
       6/7  /      \ 1/7
           /        \
          /          \
       Step2          G
</code>
Step 2:
A new problem, simulate a fair dice using a fair coin and the biased coin (coin1)
I can do this only using a fair coin, flipping 3 times, 8 possibilities, assigning 1-6 to A, B, C, D, E, F.
For 0 and 7, repeat the process. Since termination possiblity is 3/4, it will stop at some point.
But, can it be done in a finite number of steps? perhaps the biased coin could be used again?
Comment: Take any power of $2$ close to a multiple of 7. $63=9*7$ is close to $2^6=64$ for example.
Comment: @mathreader That doesn't really help, as we still have no guarantee that it will finish in finitely many throws.
Comment: @Arthur: Yes no guarantees, but we can get arbitrarily close.
Comment: @mathreadler I've added my solution. It's possible...
Answer: I think it cannot and the problem is the following. Let there be $N-n$ throws of the fair coin and $n$ throws of the unfair coin (hence $N$ total trows). Then the probability of any configuration happening is
$$
\frac{1}{2^{N-n}}\frac{6^k}{7^{n}}
$$
wherre $0\leq k\leq n$.
Now in order to simulate a fair dice you want to associate to some subset of configuration each face, and you want such a subset to have probability $1/7$. In other words you want to divide the configurations with probability given by the expression at the beginning into groups whit probability 1/7. Then, for instance, for the first face you will have to find integers $k_1,k_2,\dots,k_i$ such that
$$
\frac{1}{7}=\sum_{j=1}^i\frac{1}{2^{N-n}}\frac{6^{k_i}}{7}=\frac{1}{2^{N-n}}\frac{6^{\sum_i k_i}}{7^n}.
$$
Then
$$
7\times 6^{\sum_i k_i}=2^{N-n}7^n
$$
This is definitely impossible since the left hand side is divisble by 3 while the right hand side is not.
Then it is impossible to simulate the fair dice with a fixed finite number of tries.
Comment: hmmm of course, I did something really really wrong. I took the sum to the exponent. hahah sorry for that. Glad you solved it :)
Comment: It can be, look my answer. (thanks for effort though).
Answer: It is possible...
<code>           ------------------- coin 1 ----------------------
                  /                              \
            1/7  /                                \ 6/7
                /                                  \
            coin2                                 ---coin2---
            /    \                               /            \
       1/2 /      \ 1/2                     1/2 /              \ 1/2
          /        \                           /                \
       coin2       coin2                     coin2                coin2
        /  \        / \                       /   \              /     \
   1/2 /    \  1/2 /   \ 1/2             1/2 /     \ 1/2    1/2 /       \ 1/2
      /      \    /     \                   /       \         coin2     coin2
     1        2  3     coin2               coin2    coin2       / \      / \
                        /   \              / \        / \      /   \    /   \
                   1/2 /     \ 1/2    1/2 /   \      /   \     4 5      6   7
                      /       \          /     \    /     \
                   coin2       coin2     1     2   3     coin2
                                                           /  \
                   / \          /\                        /    \
              1/2 /   \   1/2  /  \                      /      \
                 /     \      /    \                  coin2      coin2
                4       5    6      7                  /\         /\
                                                      /  \       /  \
                                                     /    \     /    \
                                                    4      5   6      7
</code>
Calculate the probability to end up in a leaf, then sum it for all the symbols, each at it turn. An example for symbol 1 is below:
P(1) = (1/7)(1/2)(1/2) + (6/7)(1/2)(1/2)*(1/2) = 1/7
P(2) = (1/7)(1/2)(1/2) + (6/7)(1/2)(1/2)*(1/2) = 1/7
Comment: Ok, so one coin is allowed to be biased 1/7 contra 6/7, yeah then it's probably possible. But I don't see why it is an interesting question in that case.


Prove that $\sum_{n=1}^{\infty} \frac{[nx]}{n^2} $ is discontinuous at $x \in \mathbb Q$

Question: We define $[x] := x - \lfloor x \rfloor$ to be the fractional part of $x\in\mathbb{R}$, and set $$f(x)= \sum_{n=1}^{\infty} \frac{[nx]}{n^2} $$ for $x\in\mathbb{R}$, and I wish to prove that it is discontinuous at $x\in\mathbb{Q}$. I can prove that it is continuous at all irrational points using uniform convergence, but I don't know how to prove discontinuity in this case.
I looked at this similar question, but I'm not satisfied that the answer is rigorous – at least, I don't understand the step the author makes, and it seems like that step may assume a statement that is not correct. Thanks.
Comment: You can adapt the answer given by **Olivier Bégassat**.
Comment: I recommend you put the definition of the function in the body of the post. On Android devices mathjax does not render in the title.
Answer: I am proving this result for positive rationals; proof for negative rationals will be similar. For convenience, I am using $(a)$ to denote the fractional part of $a$. Let $\frac{p}{q}$ be a rational. Let $r=\frac{p}{q}$. Now we write the function as $$f(r)=\sum_{n=1}^{\infty}\frac{(nr)}{n^2}=\sum_{n:\ q\mid n}\frac{(nr)}{n^2}+\sum_{n:\ q\nmid n}\frac{(nr)}{n^2}=f_1(r)+f_2(r)$$. In the 2nd part of the above sum, $(nr)$ is never $0$, hence $\sum_{n:\ q\nmid n}\frac{(nr)}{n^2}$ is continuous at $r$ by uniform convergence. So, it is enough to prove that the 1st part of the above sum is not continuous at $r$. We write the 1st sum as follows: $$\sum_{n:\ q\mid n}\frac{(nr)}{n^2}=\sum_{k=1}^{\infty}\frac{(kqr)}{k^2q^2}$$. Now, fix sum $k\in\mathbb{N}$. Let $r_k=r-\frac{1}{kq}=\frac{p}{q}-\frac{1}{kq}$. (For negative rational $r$, define $r_k=r+1/kq$) Then $\frac{(qr_k)}{q^2}=\frac{(p-\frac{1}{k})}{q^2}=(1-\frac{1}{k})/q^2$. Now, $f_1(r)=0$. If $f$ is continuous at $r$, $\lim_{x\to r}=f_2(r)$, $\lim_{x\to r}f_1(r)=0$. Now, notice that $r_k\to r$ as $k\to\infty$. But, $f_1(r_k)\ge\frac{(qr_k)}{q^2}=(1-1/k)/q^2>1/2q^2$ for large values of $k$. Hence $f_1(r_k)\not\to 0\Longrightarrow f$ is not continuous at $x=r$.


How do I save the values for a custom fieldset?

Question: Relating to my question (here). I made a custom field set to toggle organic group visibility. The UI looks and functions as it should, meaning when I have both my fieldset and $form['group_access'] fieldset showing, I can toggle settings from either and the changes show correctly in both. When I hide $form['group_access'] with $form['group_access']['#access']=FALSE; the values do not appear to get written to the database when I hit save. Shouldn't I be able to set $form['group_access']['und']['#entity']->group_access['und'][0]['value'] to the values in my custom fieldset? Any ideas? Thanks
Answer: One way to do it would be in hook_form_alter add a custom validate handler:
$form['#validate'][] = 'my_custom_validate_handler';

then you should be able to do (double check that with debug(), print_r() or devel):
function my_custom_validate_handler(&$form, &$form_state) {

    $form_state['values']['group_access']['und'][0]['value'] = 1;

}

Another way would be to set a '#default_value' and it should be something like that:
$form['group_access']['und'][0]['default']['#default_value'] = 1

Hope that helps!


Windows Server: Prevent process swapping/paging

Question: Is there a possibility to prevent swapping for a single process?
This process is an in-memory-database and should not be moved to virtual ram.
all other processes should still be swap-able.
I need something like the "lock pages in memory" option of the SQL-Server.
Answer: If a process starts swapping, it's either very poorly coded and not releasing RAM when it should or your server doesn't have enough RAM available to handle all the tasks it's currently performing and you should expand the RAM capacity.
If that's really not an option budget-wise or if the machine is already at maximum RAM capacity, you could schedule a task that kills and restarts the process every hour or so (or more frequent if needed). Note that this should really be a last-resort and temporary solution, as it's not really so much of a solution, but just a work-around.
As for the core of your question, there is no way that I know of to prevent a program from swapping. It's basic OS behaviour when a process runs out of physical memory to use to prevent your machine from crashing.
Comment: The server already has very much RAM. And even if everything is loaded there are still 20 GB RAM available. Dont know why the system begins to page the process but it does :(


forEach store output into variable and access outside anonymous function

Question: I have a code passage like this:
tg.router._routes.forEach(function(entry){
console.log(entry._commands[0]._textPattern)
});

Because inside the object (entry._commands[0]._textPattern) are three items, console.log will be called three times.
How can I store "entry._commands[0]._textPattern" into a variable (could be an array) and use the variable later outside of the anonym function?
I need a different variant, because I wan't to pass the output of the forEach later all at once to a handler.
Answer: You can try using map:
const something = tg.router._routes.map(entry => entry._commands[0]._textPattern);

Comment: as shown, this would do exactly nothing ... surely there should be a `var something =` before that code :p
Comment: true; added `const` since there's an ES6 tag :)
Comment: Someone kind would explain me what's the difference between my solution and this one? And why it pretends to be better solution than mine?
Comment: I usually prefer `map` for simple tasks like this because it is concise, more readable and doesn't require local state.


Does all Layer 3 capable switches able to do Layer 2?

Question: I was tasked to find an affordable Layer 2 Switch around our area but can't seem to find one... in fact I found a Layer 3 Switch that seems to be cheaper than the Layer 2 i came across somewhere.
I found this Layer 3 Switch
http://www8.hp.com/emea_africa/en/products/networking-switches/product-detail.html?oid=6783404&jumpid=reg_r1002_emea_africaen_c-001_title_r0001#!tab=features
w/c is ok with our budget... but the Specifications did not mention any Layer 2 stuffs.. Is it safe to assume that LAYER 3 Switches cover layer 2 capabilities as well? Or can switches have one of each only ?
Comment: @Chopper3 answer is correct, but some L3 devices are not as specialized as L2 devices, so check if you need anything "fancy" before buying one.
Answer: To expand on the existing answer, yes - Layer 3 is 'Routing' and layer 2 is 'Switching'
Layer 1 is 'physical' (is there a cable plugged into the port, that kind of thing)
So to do layer 3, you have to do 2, and to do 2, you have to have 1.
Answer: Yes, it's the 'switch' bit that does the L2 stuff.