Do device drivers communicate with each other, or are they asynchronously called?

Question: I will paint an example of what I am asking in crystal clear detail.
Say we are in a typical userland app, like painting software or text editing, and we decide to hover the mouse or click a combo box. From this input alone the mice's trackball will need to be fetched from the device driver on the low-level, but the video driver will also need to update the position of the pointer on the screen accordingly at the (seemingly) same time as follows:

As the picture illustrates, not moving the mouse, but calling the driver/updating the screen constantly works. However, what if we choose to both click the menu combo box/drop down list, and update the framebuffer feed constantly? Are both drivers called almost at the same time, and what calls them (the GUI desktop, the app directly, etc.). Because the mouse works ANYWHERE, on an app or not ... that makes me question if the mouse input is indefinitely system called, however, video output depends more on what the app is(like below, texpad).
Answer: The mouse driver has nothing to do with the video driver. You're getting the distinction wrong between what happens in the kernel space and user space.
The kernel has no idea of a concept of a 'mouse pointer'. It only exports an interface saying, "I have a input device that gives X and Y coordinates". Likewise with the video driver, it only exports an interface saying, "I have a device where you can output pictures" - it doesn't know what a mouse pointer is.
The GUI is all handled in user space and that's where you get the concept of drop down boxes, mouse pointers etc... Whatever program handles your GUI takes the kernel interfaces and does stuff with it, such as associating the input device with a mouse pointer and outputting video to the screen.
How the contents of the screen is actually pushed to the hardware will be driver dependent and doesn't involve user space. The GUI just tells the kernel, "I want the screen to look like this" and the kernel handles the rest.
Both drivers can certainly run in parallel if you have a multi-core CPU but, unless you're implementing the driver or scheduler, you don't need to know the details.


How do I get a short snare sound?

Question: How do I get a short snare sound?
I recently bought a used Pearl M 1330 (maple piccolo snare). I cleaned it up really well and got new heads (Evans HD Dry batter side / Evans Clear 200 snare side).
After reassembling it and tuning it, the snare rattles for way too long. How do I get the snare to fall off quickly?
The bottom side head is reaaaally thin. If I put a thicker one one there, will that help? If I tighten the hell out of the snare strainer, is that going to help?
Any help would be appreciated. Thanks in advance.
Comment: BTW, my answer is a bit involved, if you want a quick and dirty possible way to shorten the snare rattle, try tightening the snares themselves.
Answer: Snare resonator heads are supposed to be ridiculously thin. Don't worry about that.
The best way to control the sustain of any drum is with tuning (it's also important for best tone). Snares also have, well, snares that can be tuned a bit. But definitely start with tuning the drum.
Basically, every drum has a lowest resonant frequency based on its diameter and depth, and there is also an overtone series above that frequency where the drum will resonate. A good way to find these is to detune both heads, throw of the snares and dampen the resonator head, and then slowly tune up the batter head until it really takes off when you hit it.
If you like that frequency, then good, you're done with phase one. If you want it higher, keep tightening until you hit the next resonant frequency. If you want it lower, too bad, you need to buy a different drum.
So by now you have the batter head tuned to a resonant frequency. Flip the drum over, mute the batter head, mute the snares (really just loosen the screws on one side and pull the snares away), and tune up the resonator head until it's at the same frequency as the batter head. Now when you hit the drum, it really takes off and sounds big and lasts a little while.
Ok, maybe you're thinking "Todd, you fool, I want a short sustain!" To which I smugly reply with the fact that the shortest sustain tuning is very close to the longest sustain. You just want to detune one of the heads a bit until it really shortens the sustain. In the case of a snare, I would probably detune by tightening the batter head a little bit.
So now you have what is effectively a high frequency tom with a very short sustain. Clamp down the snares again and then start tightening them up. Many snare levers also have a thumbscrew like thing that tightens and loosens the snares. To get them as tight as possible, you might have to throw them off, tighten a bit, and throw them back on and see how it sounds. Tighter is shorter.
If the snares are still too long in sustain, then you can buy different snares. You would want thinner and fewer snare wires on a replacement snare set.
Damping drum heads is a quick fix but can really hurt the tone and projection of the drum. If you tune routinely and carefully and frequently, your drums will have a more open sound with more projection and character, while still having the sustain and qualities you want for situation.
And finally, I can't talk about drum tuning without recommending a drum dial like device that measures head tension. Not only does it help make sure the tuning is even across the whole head, but once you have a head tuned perfectly, you can write down the tension and easily and quickly tune up to it before gigs, etc.
Comment: Thanks for the in-depth answer. I'll spend some time on it this week, and see what kind of sound I can get.
Answer: Out on a bit of a limb here, but dampen the top head, make sure the two heads are non resonant, and tighten the snare itself. Haven't played proper drums for decades, but that's the way I'd go.
Answer: The snare head determines the response speed of the snares. The tighter the head, faster and more controlled the response. I'd start by cranking the bottom head with 3 full turns on each tension rod. When I snare drum isn't behaving the way I'd like it to, I can usually fix it by tightening the bottom head.

How do I get a short snare sound?


Checking the integrity of windows 2008 server backup

Question: There is a simple way to check the integrity of a backup made with Windows Backup in Windows 2008 Server Enterprise (not R2)?
Today i tried to restore some files from a backup I made some days ago, and the Windows Backup snap-in reported that the file was unreadable. I think the corruption occurred due to the network share in wich the files were being stored went offline during the backup process, that was my fault.
Regards
Norberto
Comment: Note that it is always a good idea to run a test restore of your backups on a routine basis (i.e. every _n_ months) to validate that your backup will be genuinely useful in the event of an actual emergency.
Comment: Sure. Luckly this wasn't an emergency. Thanks for the advice.
Answer: wbadmin get versions -backuptarget:\\server\share
if you need more details:
wbadmin get items -version:mm/dd/yyyy-hh:mm -backuptarget:\\server\share
Comment: Unfortunatelly I overwrote the corrupted backup and I won't be able to make a test. I will accept this as an answer. Thanks Chris.
Comment: So, my backup became corrupted again. This time I really don't know why. The problem is that these commands don't report any error. None of the two. I'll keep looking.
Comment: @Norberto, What kind of server are you backing up to (the one hosting the file share)? Is it a NAS, Samba Server, or older Windows box?
Comment: It's a Windows XP SP3.
Comment: You've got me; I don't see anything inherently wrong with what you're doing. It's a support configuration. Perhaps the disk has issues? Have you tried running chkdsk on the XP box, or checking the event log for SMART messages?
Comment: I have some entries like this on the server (translated from portuguese):

lsass (676): Failure while writing on file "\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy30\Active Directory\NTDS\ntds.dit" on displacement 5603328 (0x0000000000558000) to 8192 (0x00002000) bytes after 0 seconds with system error 21 (0x00000015): "Device not ready. ". The write operation will fail with error-1022 (0xfffffc02). If this error persists then the file may be damaged and may need to be restored from a previous backup.

After I deleted the corrupt backup, the backup ended without any error.
Comment: I think it's because I'm backing up to a Samsung S2 USB external drive, it's not the appropriate device for this task. However, the point is that I want to automate the process of validating the backup, to see if the backups are usable.
Comment: @Norberto, Those errors are definitely the backup failing; I'm not sure why it would have any problems with that though. Perhaps try plugging the USB drive into the server directly and see if that fixes it. This is sounding more and more like a weird quirk somewhere, not a big per-se.
Comment: @Chris: I already have tried to plug it directly to the server, but Windows Server Backup has some problems with the sector size of the drive, so I made this workaround (see http://social.technet.microsoft.com/Forums/en-US/windowsbackup/thread/5d9e2f23-ee70-4d41-8bfc-c9c4068ee4e2)
Comment: @Norberto, well I'm surprised that Windows Backup can't adapt to different sector sizes, but apparently that's the problem.
Answer: I do not think the above commands are 100% useful.
I tested them on injured backup (i know it for sure) and both commands have confirmed the correctness of this backup.

use the commands:
wbadmin get versions -backupTarget:x: -machine:Xxx
wbadmin get items -version:xx/xx/xxxx-xx:xx -backupTarget:x: -machine:Xxx


stdev and mean from gaussian fit vs. from classical formula

Question: I have a set of data - measured speed of molecules in water.
I made a histogram and fitted it with function
$$A\exp\frac{(x-B)^2}{C}$$
calculating mean and standard deviation from values B and C
If I use the classical formula for standard deviation the results are different.
It's clear they can't be the same. I guess the problem is, that I don't have enough data.
But now what is the difference between those values? Which one is better to use?
Comment: At least one of your curves has the wrong area beneath it (at least integrated across all the reals)
Comment: Well they are not normed. For the dashed function I used A instead of the normal coeficient so that the curves are easier to compare
Answer: Fitting a curve to a histogram is troublesome, because the result will in general depend on the number and width of the bins you chose when creating the histogram.
For an extreme example, assume you measured the values $\{\frac{1}{5},\frac{1}{4},\frac{1}{3},\frac{1}{2}\}$. If your bins are $\left((-1,0],(0,1],(1,2]\right)$, your histogram is $\left(0,4,0\right)$. If, on the other hand, your bins are $\left((-\frac{3}{4},\frac{1}{4}],(\frac{1}{4},\frac{5}{4}],(\frac{5}{4},\frac{9}{4}]\right)$, the hisogram becomes $\left(2,2,0\right)$. The two histograms will lead to different results when you fit the normal distribution's density to them - in particular, the resulting distribution's variance will be higher for the second histogram than it will be for the first.
So unless you have a very good reason to determine the distribution's parameters by fitting the density to the histogram, using some other estimator is usually better. For the normal distribution, using the sample average to estimate the distribution's mean, and the sample variance to estimate the distribution's variance is a maximum-likelyhood estimator, and probably a good choice.
Comment: thank you for your answer. the dependence on number of bins is a very good point. what if I wanted to determine how well the distribution represents normal distribution? would this be suitable than?
it's for physics lab report and one of the tasks was actually to fit the histogram, so i'm trying to find out what could be the reason
i'll probably mention this fact in the discussion section
Comment: @Tom83B A statistically sound way to test if data is distributed according to some known distribution is the one-sided [Kolmogorov-Smirnov-Test](http://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test).
Comment: @Tom83B Though if you determine the distribution's parameter from the same dataset that you use to do the test, as you seem to require, the test doesn't really work (though it might still be approximately correct, I dunno). The problem is that the test statistic the K-S-Test uses comes out too small in this case, because you moved the distributed closer to the actual data by estimating it's parameters. For the special case of the normal distribution, you can use the [Lilliefor-Test](http://en.wikipedia.org/wiki/Lilliefors_test), which accounts for that.


my submit buttons and select button shift all the words on that page to the left

Question: As you can see in picture 1, my "rights reserved" is centered. But in picture 2, the words are shifted to the left.

Here's my HTML code for picture 1:

<form action="Chapter 1.html" data-inline="true" style="float:right">
    <input type="submit" value="Next >">
  </form>
  </style>

    <select id="change" onchange="location = this.options[this.selectedIndex].value;">
      <option value="Introduction.html">1. Introduction</option>
      <option value="Chapter 1.html">2. Chapter 1</option>
    </select>

And my code for picture 2:

  <form action="Chapter 2.html" data-inline="true" style="float:right">
    <input type="submit" value="Next >">
  </form>
  </style>

  <select id="change" onchange="location = this.options[this.selectedIndex].value;" style="float:right">
    <option value="Introduction.html">1. Introduction</option>
    <option value="Chapter 1.html">2. Chapter 1</option>
  </select>

  <form action="Introduction.html" style="float:right">
    <input type="submit" value="< Prev" id="previous">
  </form>
  </style>

My css code for both pictures:

input[type=submit] {
    width: 5em;  height: 2em;
    border-radius: 5px;
    webkit-border-radius: 5px;
    background: webkit-linear-gradient(#fff, #ddd);
    background: linear-gradient(#fff, #ddd);
}
input[type=submit]:hover {
    background: #ddd;
}
#previous {
    width: 5em; height 2em;
    border-radius: 5px;
    webkit-border-radius: 5px;
}

#change{
    width: 9em; height: 2em;
    border-radius: 5px;
    webkit-border-radius: 5px;
}

As requested, here's my rights reserved code, html code is the 1st while the 2nd is the jScript code and the 3rd is the css code:

document.getElementById("foot01").innerHTML =
"
©  "+ new Date().getFullYear() + " Richard. All rights reserved.
";

footer#foot01 {
    color: #000;
    align:center;
}

What am I doing wrong here? :/
Comment: Please post the HTML and CSS code you are using in "rights reserved" section.
Answer: You are floating forms and select items to right. Then you need to apply a clear to the footer:
footer#foot01 {
    clear: right;
}

DEMO
Note: Also you have anothers errors, like </style> tags in HTML and align:center; that should be text-align: center;.
Comment: thank you! it worked! I would like to ask a question, what does "clear:right" mean?
Comment: Take a look at [this article](https://css-tricks.com/almanac/properties/c/clear/).


Should matching (without discarding units) be attempted before weighting?

Question: In ecology, we are often working with very small samples, i.e. I only have 13 sites of each of the two farming practices I am comparing. Thus, I really don't want to discard any of my sites and thus I am planning to do weighting rather than matching. However, should I first try to match my sites first (without discarding any sites) and only do weighting if it is not possible to match my sites?
What is the difference between using matching weights and weights from a weighing analyses per se (eg using the package WeighIt)?
If I have do do weighting, would this lower my ability to infer causality considerably?
Answer: Weighting and matching are two methods that aim to do exactly the same thing, which is to create two groups that have similar distributions of covariates. Matching works by pruning: any units that are not matched are discarded, and the rest for the matched sample. Weighting works by assigning a weight to each unit, which increases or decreases its priority in the estimation of the effect. There are methods of matching that don't drop units and instead reorganize the units into strata, and matching weights are computed from the strata. In this blog post, I explain how matching weights are propensity score weights.
Both methods have the exact same causal property, because causality comes from the assumption that the right covariates have been balanced, and both methods seek to balance covariates. You can only make a valid causal claim if you have eliminated confounding, i.e., closed all backdoor paths. This assumption is orthogonal to the method you use to do so.
Both matching and weighting decrease your precision in order to reduce bias. With a small sample, imprecision dominates bias in the error of the estimate, so you should not use methods that decrease precision. If anything, I would recommend adjusting for variables using regression, which may leave some bias but will increase your precision.
That said, if you think you can make a generalizable statement about causality using a sample of 26 units, you should rethink your design. That is way too small to make any useful inferences, let alone a causal inference. I would recommend you either abandon this question, collect more data, or take a different methodological approach (e.g., using a qualitative analysis) to answering your question.


wp_pagenavi não funciona em category.php

Question: Baixei e instalei o Plugin wp_pagenavi eu coloquei no fim do meu código, ele aparece só que não pagina, clicando, seja no 2... 3... ele não pagina, sempre repete os itens de 1 a 10.
Código
<?php get_header(); ?>

 <?php echo "Categoria "; single_cat_title(''); ?>

            <?php query_posts($query_strings . "&order=ASC"); ?>

            <?php if(have_posts()) : while(have_posts()) : the_post(); ?>

                        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                            <?php the_post_thumbnail(array(198, 198)); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                        Publicado por <?php the_author(); ?> em  <?php the_time('d/m/Y'); ?>

                    <?php the_excerpt(); ?>
                    <a href="<?php the_permalink(); ?>" id="read_more_link">
                        Continuar Lendo >>

            <?php
                endwhile;
                else:
            ?>

Nenhum post encontrado.

            <?php
                endif;
            ?>
        <?php wp_pagenavi(); ?>

<?php get_footer(); ?>

O que eu poderia fazer pra ele funcionar?
Obs.: Sou novato no Wordpress.
Answer: Veja se isso define o limite que você quer na linha 5:
<?php
 $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
 $args = array('posts_per_page' => '8');
 query_posts($args . $query_strings . '&order=ASC&paged=' . $paged);
?>

Answer: wp_pagenavi está falhando porque a sua query está sendo sobrescrita com query_posts(). A internet vai te dizer o contrário, mas nunca é uma boa ideia usar query_posts() porque essa função bagunça todas as variáveis globais do tema e causa esses tipos de problemas.
O plugin está implementado corretamente mas ao invés de chamar query_posts na linha 5 as alterações na consulta devem ser feitas no seu arquivo functions.php usando o filtro pre_get_posts.
Exemplo:
add_action('pre_get_posts', 'modifica_query_category');
function modifica_query_category( $query ) {
    // modifica apenas a query principal de arquivos de categoria
    if ( $query->is_main_query() && is_category() ) {
        // altera a ordem para ascendente
        $query->set('order', 'ASC');
    }
}

Com isso você elimina a consulta duplicada, melhora a performance do site e corrige os erros de paginação de uma vez só :)


Find the cardinality of $\{(x,y) \in \mathbb R \times \mathbb Q : x^2 - y = 0 \}$

Question:
Find the cardinality of $A =\{(x,y) \in \mathbb R \times \mathbb Q :
> x^2 - y = 0 \}\}$

This question may seem trivially easy but I have just started learning about cardinality and still find some things confusing.
My attempt: First of all, I rewrote the definition of the set in a simpler way, adding $y$ to both sides and making necessary assumptions
$$A =\{(x,x^2) : x \in \mathbb R \land x^2 \in \mathbb Q \} = \{(x,x^2) : x\in \mathbb Q \} \cup \{(\pm\sqrt q , q):q \in \mathbb Q \}$$
Now, the cardinality of both of these sets is $\aleph_0$, thus the cardinality of the set in question is $\aleph_o$
Is my solution correct? I not, where have I made a mistake?
Comment: You made a mistake rewriting $A$. For example $(2, \sqrt{2}) \in A$ but it's not in your set.
Comment: $A = \{(\pm \sqrt{y},y):y \in Q \land y \ge 0\}$.
Comment: @StefanMesken
Why $(2, \sqrt 2) \in A$? $2^2 \ne \sqrt 2$
Comment: I messed up the order. I meant $(\sqrt{2},2) \in A$.
Comment: Sorry, but I still can't see what's the problem with my definition of the set. $x^2 - y = 0 \iff y = x^2$
Comment: Why you say that $\sqrt{q}\in A$?
Comment: The ordered pair is backwards.  You want $A =\{(x^2,x) : x^2 \in \mathbb R \land x \in \mathbb Q \}$  You want the unsquared one to be rational.  Then Eric Towers' argument is spot on.
Answer: Yes $x^2 = y$, but since $\mathbb{R}$ contains all the square roots of elements of $\mathbb{Q}$, perhaps $\{(\pm\sqrt{y}, y) \in \mathbb{R} \times \mathbb{Q} \}$ would be a bit simpler.  Then this set has one element per element of $\mathbb{Q}$...
Comment: You should put a $\pm$ before $\sqrt y$ as the negative ones are in the set as well.
Comment: Thanks, this solution is in fact simpler. But what is the problem in mine?
Comment: @RossMillikan : What?  Not everyone uses the multivalued function $\sqrt{\cdot}$?  (Thanks.  Fixed.)
Comment: @Aemilius : While your equality of $A$ with a union of two sets is valid, it twice includes every element (the two sets on the right are identical).  This isn't fatal, but it is a longer/harder story to tell and to explain clearly.
Comment: They are not identiclal. For example, the first set does not include $(\sqrt 2, 2)$
Comment: @Aemilius : Even worse...  Your story has (not actually) misled at least one reader...
Answer: The  cardinality of the set  $$A =\{(x,y) \in \mathbb R \times \mathbb Q :
> x^2 - y = 0 \}\}$$ is $\aleph_0$.
Note that for any  positive rational number $y$, you get two elements of $A$ , namely,( $\sqrt y ,y)$ and $ (-\sqrt y , y)$.
Therefore your set is infinitely countable.
You also have $(0,0)$ in your set which does not change the cardinality.
Thus the  cardinality of $A$ is  $\aleph_0$.


How can I apply independent CSS styles to each styled component?

Question: I wanted to make Header component
So, I made two components (Logo.jsx , Links.jsx) and those two files are styled-components.
Logo.jsx
After that, I made a Header.jsx file like this.
Header.jsx
I want to put some margin 10px between  and .
But I can't handle the components in NH that Styled-Component.
I tried the following various attemps.

Give a className attribute to
Used the Logo component directly in NH's css.
Tried to get the 'dynamic' className of Logo component, but I didn't know how to get it.

So, my point is that. How can I handle the styled-components in another styled-components?
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Two questions as far as I can see - how to access another styled-component and how to add a gap between your children components.
To answer the first one, you can refer another styled-component by using ${Component} given its already declared before. For example,
const NH = styled.div`
  ...
  ${Logo} {
    margin: 10px;
  }
`;

To access another component in css regardless whether it's a styled component or not, you can use class name or id.
Regarding second question, if you want to add a gap between your two flex items, you could use gap css property. It applies gap between the items in your flex container.
const NH = styled.div`
  display: flex;
  gap: 10px;
  ...
`;

Hope this helps.


Oozie Re-run the workflow from the node, where it was last killed

Question: I am using the MR action in oozie. And want to use the suspend/resume functionality provided by oozie on MR.
The problem - However, when we call 'suspend' on Oozie that doesn't kill the hadoop job instead it only updates the oozie state, while the hadoop job continues to run to completion. I want the hadoop job to be killed immediately when the oozie workflow is suspended. Guess that's not possible right ?
So, I figured I can kill the oozie workflow and re-run it.
But now the problem is , if there are 3 action nodes in my workflow, I don't want to re-run all of them.
Am I smoking here or is it possible to access the last successful oozie node ( which is most likely stored in the mysql database) ?
Is there a better approach to my connived use-case ?
Appreciate your help in advance,
P.S. I am not posting my workflow because it's a simple workflow with several map-reduce actions, no rocket science here.
Answer: The oozie command line interface allows for the flag "-rerun" to be used in the following context:
<code>oozie job -oozie http://localhost:11000/oozie -config job.properties -rerun 14-20090525161321-oozie-joe
</code>
There is one issue in the automation of reruns, and this is that you must supply a list of action nodes to skip inside of the job.properties file using the oozie.wf.rerun.skip.nodes variable.
This following is taken from source

Only one of following two configurations is mandatory. Both should not be defined at the same time
  oozie.wf.rerun.skip.nodes
  oozie.wf.rerun.failnodes
  Skip nodes are comma separated list of action names. They can be any action nodes including decision node.
  The valid value of oozie.wf.rerun.failnodes is true or false.
  If secured hadoop version is used, the following two properties needs to be specified as well
  mapreduce.jobtracker.kerberos.principal
  dfs.namenode.kerberos.principal.

In order to get the automation, it might be worth you time to try appending to the properties file on completion of an action using either a shell script or implementing it directly into your MR jobs.


In Drupal 7 how to expose TID (term id) as a selectable field on the manage display section of the taxonomy page?

Question: How can I expose the TID of a the term as a field via the manage display section of the taxonomy page?
Comment: [Create a custom field formatter in Drupal 7](http://www.whenwhowhere.com/tech-blog/create-custom-field-formatter-drupal-7)
Comment: Also see the comment at the bottom of that article referring to the [Custom Formatters](https://drupal.org/project/custom_formatters) module.
Comment: Custom formatter is kinda wrong for this, since it would have to hijack an existing field.
Answer: You can use Display suite, and create a custom field.

Install ds and ds_extras.
Configure ds_extras to enable custom fields.
Activate a display suite layout for your taxonomy term display.
Create a custom field, where you can put the tid as a token.
Comment: i dont see an options for "cutsom fields". I think you mean "code field" or "dynamic fields" in the fields tab. But what do I put there?
Comment: Check "Use tokens", and then try sth like [tid] or [taxonomy_term:tid]. There should be a list of available tokens.
Comment: You need to enable token module first, this could be a thing.


Infer new Document using Mahout 0.9 LDA

Question: I am able to build a LDA model using Mahout 0.9 CVB implementation. I now need to infer a new document using this model.
I was wondering if there is any already existing method/implementation to do the same?
Any help will be highly appreciated. Thanks.
Answer: There's not yet a command line mahout algorithm for inferring a single new document with existing lda topic model. Fortunately there are some nice but not-so-well documented tools in mahout library.
I found this blog post that seems to have a working Java example.
Inferring should also be quite straight forward to implement with CVB0DocInferenceMapper.

Infer new Document using Mahout 0.9 LDA


Migrations Asp Net MVC

Question: Fiz um projeto primeiramente alimentando minha aplicação ASP.Net MVC por um banco de dados SQL Server que setei no arquivo web.config (connectionString).
Depois, seguindo com alguns cursos que fiz, comecei a usar o Migrations para atualizar as tabelas do banco de dados.
Problema é que estou verificando que ele não está mais olhando a tabela e banco que estão setados no meu web.config.
Fiz um teste, apaguei minha connectionstring do meu arquivo web.config e a aplicação continua funcionando e conectando com o banco sem problemas.
Não estou entendendo aonde está setado o banco e tabelas que ele está olhando, percebi que não é mais no meu arquivo web.config. Precisa saber para fazer umas verificações nos dados no banco SQL Server.
Answer: Quando você não especifica uma string de conexão, o Entity Framework cria uma internamente apontada para seu LocalDB e com o nome do banco igual ao seu DbContext
Procura no seu (localdb)\MSSQLLocalDB uma base com o nome nesse fomato MinhaSolucao.MinhaAplicacao.Contexts.MeuDbContext
Comment: Consegui localizar, obrigado.
Comment: Se a resposta o fez localizar, por favor a marque como correta

Migrations Asp Net MVC


Does anybody use star-schema databases to collect and organize their data?

Question: I've been reading about the star schema (or dimensional) database structure, which puts all measurements main in 'facts' table, and all context for those measurements in 'dimension' table linked to the facts table (I'm doing a horrible job explaining this), so that you can query any measurement by conditioning on the dimension.
When I read about this, it struck me as a perfect way to aggregate different csv files with different columns into one store... for example, stock, commodities, and options data in various files go be shoved into a star-schema db with a facts table containing the open/close/high/low/volume, with foreign-key links to dimensions such as time, company, exchange, and 'file pedigree' so that we know where each entry comes from.  That would allow you to query for, say, first quarter chinese mining companies with a single, fairly simple sql statement.
However, all of the literature on this topic seems to be for large scale 'enterprise' deployments and not small data analysis or research jobs.  Does anyone have any experience organizing their data this way?  Is there are simpler way?
Comment: +1 Seems like this question could go on Stack Overflow (for example here's good coverage of the star schema for data warehousing http://stackoverflow.com/questions/110032/star-schema-design). But statisticians have their own data management concerns and needs so nice to see it discussed here.
Comment: Yes, I didn't want to put it in the main SO because there only 'enterprise' dba's would've answered, not statisticians.  I did look for a more generic 'data analysis' stack exchange, though.
Comment: Most examples of the Star Schema use one fact table supported by dimension tables in their examples, but the number of fact tables is usually dictated by the ETL (Extract Transform Load) process in practice. If you are importing data at different times or from different sources, it is common to have different fact tables.
Answer: From the simplest to the most complex,
there are several ways
of designing the schema of a database.
With the "single table schema", you just put everything
in a single table. It is the easiest to use.  The
main drawback is that there is no guarantee that
the data is consistent: for instance, I once had a
table with a "country" column and different
spellings for the same country.
Another problem, caused by those redundancies,
is the waste of disk or memory space,
but if your database is a
column store,
it will notice those redundancies
and compress the data accordingly --
for that type of data, the performance
can be one or two orders of magnitude better
than standard (row-based) databases.
The "star schema" is almost the same thing,
but with the redundancies moved to other tables.
The main table ("fact table") remains the largest,
and is linked to the new tables ("dimension tables":
client, product, country, date, etc.)
Since there are no links between the dimension tables
the structure of the database remains simple and manageable
(if you draw it, it looks like a star).
There may still be some redundancies
(the database is not in normal form),
if they cannot be removed without complexifying the schema.
The most complex type of schema would be a
normalized database,
i.e., intuitively, a database with no redundancies whatsoever
(there are various levels of normalization,
but if you only use data, those distinctions do not really matter).
The links ("foreign key constraints") between the tables
can be arbitrarily complex -- if you draw them, this looks like spaghetti.
For data analysis, I usually try to stick to the 1-table model:
you do not have to think about the structure of the data.
In some cases, this poses problems, and a star schema may be preferable.
This is the case, for instance, if the data comes from different sources,
each source corresponding to a dimension table.
Unless you have a database administrator to manage the data for you
and build views to hide the complexity,
you should stay away from more complicated schemas:
they are cleaner, but more difficult to maintain and use --
they would quickly fall into disuse.
Comment: Thank you, this is exactly what I was looking for.  I also did not know about column store db's.
Answer: This sounds close to the normal forms of relational databases, which I have heard of, and used, but I haven't heard of the star schema before. Having worked with multiple terrabyte size data warehouses in the past, the fourth normal form is awful for data analysis as one spends half one's time trying to work out what tables one needs data from, and then having to merge parts of lots of tables.
They work so long as

the business users set how they want the tables, not the database administrator, and
when you have lots of transactional data that repeats over time, e.g. claims, police offences, welfare histories, personnel histories, and
there are schema that show how the tables relate together, along with detailed table and field descriptions in documentation, and
there are business rule definitions for data use (e.g. when a welfare benefit spell restarts within 2 weeks, count as one benefit spell rather than two).

If you're doing one-off studies, or you have relatively small amounts of data, these are overkill. These types of databases are stored in huge data warehouses, such as that offered by IBM, SAS, Oracle, and SAP. These require dedicated resources to develop and maintain, and the staff require specialist qualifications. There is no point going to this level of cost and effort for simple databases, and possibly no point even going to a relatively simple option like MS Access, because of the sunk cost of getting one up and running combined with the analyst time costs of then having to extract the information in usable format.
Comment: It actually seems to be the opposite of normal form... for example, the dimensions are supposed to nonnormalized so that it is trivial to navigate and create conditions.  And the table structure is also extremely simple-- one central table, bunch of dimensions, but no connections between the dimensions and nothing else.
Comment: @biofreezer I get stuck on the normal forms, it looks like a type of second normal form to me: https://en.wikipedia.org/wiki/Second_normal_form


Vertical Alignment on JQuery Mobile Grid

Question: I am attempting to set up a page using JQuery Mobile, where I have a 3 column grid, with a label, a text input and a set of horizonally-aligned radio-buttons.  For some reason Grid-element c sets it's height larger than the other 2, and I can't seem to force the first 2 cells to align with it.
An example of the code is at: http://jsfiddle.net/5WSj4/1/
Here is the code in question

        <fieldset class="ui-grid-b">

                League Name:

                <input type="text" style="vertical-align:top" data-mini="true" name="leagueNameInput" id="leagueNameInput" maxlength="4" value="" data-mini="true" />

                    <fieldset data-role="controlgroup" data-mini="true" data-type="horizontal">

                        <input type="radio" name="difficulty" id="difficultyEasy" value="choice-1" />
                        Easy
                        <input type="radio" name="difficulty" id="difficultyMedium" value="choice-2" checked="checked" />
                        Medium
                        <input type="radio" name="difficulty" id="difficultyHard" value="choice-2" />
                        Hard
                    </fieldset>

        </fieldset>

Any help with this would be greatly appreciated.
Answer: For some bizarre reason, ui-controlgroup has a top margin of 0.5em. Overriding it in the fieldset element solves the problem, i.e.
style="margin-top: 0px;"


socket.error: [Errno 13] Permission denied --- neutron agent-list

Question: First of all, in the compute node, neutron-linuxbridge-agent.service status is active, normal.
[root@compute1 neutron]# systemctl status neutron-linuxbridge-agent.service  -l
● neutron-linuxbridge-agent.service - OpenStack Neutron Linux Bridge Agent
   Loaded: loaded (/usr/lib/systemd/system/neutron-linuxbridge-agent.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2017-07-14 13:48:38 CST; 113ms ago
  Process: 116170 ExecStartPre=/usr/bin/neutron-enable-bridge-firewall.sh (code=exited, status=0/SUCCESS)
 Main PID: 116177 (neutron-linuxbr)
   CGroup: /system.slice/neutron-linuxbridge-agent.service
           └─116177 /usr/bin/python2 /usr/bin/neutron-linuxbridge-agent --config-file /usr/share/neutron/neutron-dist.conf --config-file /etc/neutron/neutron.conf --config-file /etc/neutron/plugins/ml2/linuxbridge_agent.ini --config-dir /etc/neutron/conf.d/common --config-dir /etc/neutron/conf.d/neutron-linuxbridge-agent --log-file /var/log/neutron/linuxbridge-agent.log

Jul 14 13:48:38 compute1 systemd[1]: Starting OpenStack Neutron Linux Bridge Agent...
Jul 14 13:48:38 compute1 neutron-enable-bridge-firewall.sh[116170]: net.bridge.bridge-nf-call-arptables = 1
Jul 14 13:48:38 compute1 neutron-enable-bridge-firewall.sh[116170]: net.bridge.bridge-nf-call-iptables = 1
Jul 14 13:48:38 compute1 neutron-enable-bridge-firewall.sh[116170]: net.bridge.bridge-nf-call-ip6tables = 1
Jul 14 13:48:38 compute1 systemd[1]: Started OpenStack Neutron Linux Bridge Agent.

But I can not list the neutron agent:
[root@compute1 neutron]# neutron agent-list
neutron CLI is deprecated and will be removed in the future. Use openstack CLI instead.
An auth plugin is required to fetch a token

And in the compute node I can also find the logs of the /var/log/neutron/linuxbridge-agent.log:
2017-07-14 13:44:58.106 114191 CRITICAL neutron [-] Exception: Failed to spawn rootwrap process.
stderr:
Traceback (most recent call last):
  File "/usr/bin/neutron-rootwrap-daemon", line 10, in <module>
    sys.exit(daemon())
  File "/usr/lib/python2.7/site-packages/oslo_rootwrap/cmd.py", line 57, in daemon
    return main(run_daemon=True)
  File "/usr/lib/python2.7/site-packages/oslo_rootwrap/cmd.py", line 98, in main
    daemon_mod.daemon_start(config, filters)
  File "/usr/lib/python2.7/site-packages/oslo_rootwrap/daemon.py", line 110, in daemon_start
    server = manager.get_server()
  File "/usr/lib64/python2.7/multiprocessing/managers.py", line 493, in get_server
    self._authkey, self._serializer)
  File "/usr/lib64/python2.7/multiprocessing/managers.py", line 162, in __init__
    self.listener = Listener(address=address, backlog=16)
  File "/usr/lib/python2.7/site-packages/oslo_rootwrap/jsonrpc.py", line 66, in __init__
    self._socket.bind(address)
  File "/usr/lib64/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 13] Permission denied

2017-07-14 13:44:58.106 114191 ERROR neutron Traceback (most recent call last):
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/bin/neutron-linuxbridge-agent", line 10, in <module>
2017-07-14 13:44:58.106 114191 ERROR neutron     sys.exit(main())
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/lib/python2.7/site-
packages/neutron/cmd/eventlet/plugins/linuxbridge_neutron_agent.py", line 21
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/bin/neutron-linuxbridge-agent", line 10, in <module>
2017-07-14 13:44:58.106 114191 ERROR neutron     sys.exit(main())
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/lib/python2.7/site-packages/neutron/cmd/eventlet/plugins/linuxbridge_neutron_agent.py", line 21, in main
2017-07-14 13:44:58.106 114191 ERROR neutron     agent_main.main()
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/lib/python2.7/site-packages/neutron/plugins/ml2/drivers/linuxbridge/agent/linuxbridge_neutron_agent.py", line 921, in main
2017-07-14 13:44:58.106 114191 ERROR neutron     manager = LinuxBridgeManager(bridge_mappings, interface_mappings)
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/lib/python2.7/site-packages/neutron/plugins/ml2/drivers/linuxbridge/agent/linuxbridge_neutron_agent.py", line 81, in __init__
2017-07-14 13:44:58.106 114191 ERROR neutron     self.check_vxlan_support()
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/lib/python2.7/site-packages/neutron/plugins/ml2/drivers/linuxbridge/agent/linuxbridge_neutron_agent.py", line 659, in check_vxlan_support
2017-07-14 13:44:58.106 114191 ERROR neutron     if self.vxlan_ucast_supported():
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/lib/python2.7/site-packages/neutron/plugins/ml2/drivers/linuxbridge/agent/linuxbridge_neutron_agent.py", line 623, in vxlan_ucast_supported
2017-07-14 13:44:58.106 114191 ERROR neutron     test_iface = self.ensure_vxlan(seg_id)
2017-07-14 13:44:58.106 114191 ERROR neutron   File "/usr/lib/python2.7/site-packages/neutron/plugins/ml2/drivers/linuxbridge/agent/linuxbridge_neutron_agent.py", line 300, in ensure_vxlan

My configuration of /etc/neutron/plugins/ml2/linuxbridge_agent.ini:
[securitygroup]
enable_security_group = True
firewall_driver = neutron.agent.linux.iptables_firewall.IptablesFirewallDriver

[vxlan]
enable_vxlan = True
local_ip = 10.2.2.121
l2_population = True

And in my controller node, I can not see the neutron agent of the compute:
[root@controller neutron]# neutron agent-list
neutron CLI is deprecated and will be removed in the future. Use openstack CLI instead.
+--------------------------------------+--------------------+------------+-------------------+-------+----------------+---------------------------+
| id                                   | agent_type         | host       | availability_zone | alive | admin_state_up | binary                    |
+--------------------------------------+--------------------+------------+-------------------+-------+----------------+---------------------------+
| 18535c11-49ee-4e9e-a889-623a1d324c82 | L3 agent           | controller | nova              | :-)   | True           | neutron-l3-agent          |
| 1c2c3b41-a678-4645-be0d-7d885e4dce7a | DHCP agent         | controller | nova              | :-)   | True           | neutron-dhcp-agent        |
| 7e401de6-f501-447b-aa7a-11f0f74f770a | Linux bridge agent | controller |                   | :-)   | True           | neutron-linuxbridge-agent |
| c9c25e82-11fd-4fce-8bef-91915615620a | Metadata agent     | controller |                   | :-)   | True           | neutron-metadata-agent    |
+--------------------------------------+--------------------+------------+-------------------+-------+----------------+---------------------------+

Answer: In the end I solved this issue.
First at all, make sure the compute node installed the openstack-selinux, if no:
yum install -y openstack-selinux

If this is still not working, disable the selinux:
setenforce 0


Difference between synchronization of field reads and volatile

Question: In a nice article with some concurrency tips, an example was optimized to the following lines:
double getBalance() {
    Account acct = verify(name, password);
    synchronized(acct) { return acct.balance; }
}

If I understand that correctly, the point of the synchronization is to ensure that the value of acct.balance that are read by this thread is current and that any pending writes to the fields of the object in acct.balance are also written to main memory.
The example made me think a little: wouldn't it be more efficient to just declare acct.balance (i.e. the field balance of class Account) as volatile? It should be more efficient, save you all the synchronize on accesses to acct.balance and would not lock the whole acct object. Am I missing something?
Comment: You are correct, but the article is really about something completely different - reducing lock scope.
Answer: You are correct.  volatile provides a visibility guarantee.  synchronized provides both a visibility guarantee AND serialisation of protected code sections.  For VERY simple situations volatile is enough, however it is easy to get into trouble using volatile instead of synchronisation.
If you were to assume that Account has a way of adjusting its balance then volatile is not good enough
public void add(double amount)
{
   balance = balance + amount;
}

Then we have a problem if balance is volatile with no other synchronization.  If two threads were to try and call add() together you could have a "missed" update where the following happens
Thread1 - Calls add(100)
Thread2 - Calls add(200)
Thread1 - Read balance (0)
Thread2 - Read balance (0)
Thread1 - Compute new balance (0+100=100)
Thread2 - Compute new balance (0+200=200)
Thread1 - Write balance = 100
Thread2 - Write balance = 200 (WRONG!)

Obviously this is wrong because both threads read the current value and updated independently and then wrote it back (read, compute, write).  volatile does not help here so you would need synchronized to ensure one thread completed the entire update before the other thread began.
I general find that if when writing some code I think "can I use volatile instead of synchronized" the answer might well be "yes" but the time/effort of figuring it out for sure and the danger of getting it wrong is not worth the benefit (minor performance).
As an aside a well written Account class would handle all the synch logic internally so callers don't have to worry about it.
Answer: Declaring  Account as volatile is subjected to following issues and restrictions
1."Since other threads cannot see local variables, declaring local variables volatile is futile." Moreover If you try to declare a volatile variable in a method, you'll get a compiler error in some cases.
double getBalance() {
   volatile Account acct = verify(name, password); //Incorrect ..
    }

Declaring Account as volatile warns the compiler to fetch them fresh each time, rather than caching them in registers. This also inhibits certain optimizations that assume no other thread will change the values unexpectedly.
If you need synchronized to co-ordinate changes to variables from different threads,
volatile does not guarantee you atomic access,because accessing a volatile variable never holds a lock, it is not   suitable for cases where we want to read-update-write as an atomic operation. Unless you are sure that   acct = verify(name, password); is single atomic operation, you cannot guarantee  excepted results
If variable acct  is an object reference, then chances are it may be null .Attempting to synchronize on a null object will throw a NullPointerException using synchronized.
(because you're effectively synchronizing on the reference, not the actual object)
Where as volatile does not complain
Instead you could declare  a boolean variable as volatile like here
private volatile boolean someAccountflag;
public void getBalance() {
Account acct;
while (!someAccountflag) {
 acct  = verify(name, password);
}
}

Note you cannot declare someAccountflag as synchronized, as
you can't synchronize on a primitive with synchronized, synchronized only works with object variables, where as primitive or object variable may be declared volatile
6.Class final static fields doesn't need to be volatile, JVM takes care of this problem. So the someAccountflag need not be even declared volatile if it is a final static
or you could use lazy singleton initialization making Account as a singleton object
and declare it as follows:
private final static AccountSingleton acc_singleton = new AccountSingleton ();
Comment: Thank you for the answer, but I actually suggested not to declare acct as volatile, but acct.balance - that is, the field balance of class Account. That modifies some of your comments. I tried to clarify the question a little in that respect.
Answer: If multiple threads are modifying and accessing the data, synchronized guarantees data consistency among multiple threads .
if single thread is modifying the data and multiple threads try to read the latest value of data, use volatile construct.
But for above code, volatile does not guaranty memory consistency if multiple threds modify balance.  AtomicReference with Double type serves your purpose.
Related SE question:
Difference between volatile and synchronized in Java


RDP error while trying to establish connection

Question: I get this message while trying to connect to a remote host through RDP
(I'd like to point out the fact that until yesterday things went smoothly)
This computer can't connect to the remote computer.
Try connecting again. If the problem continues,
contact the owner of the remote computer
or your network administrator

Further details:

host is reachable through LogMeIn
ping is enabled
Terminal Service is set to automatic (started)
Windows firewall disabled
netstat -a -o command shows that another application is using port 3389

Can that be something related to the hardware firewall (Fortinet).. I don't think so, since
the host can connect to the internet
Any clue?
Thanks in advance.
Comment: `netstat -ano` to show the PID. Then `tasklist.exe /fi "PID eq ###"` to see what it is.
Comment: So you're saying I should kill the process holding port 3389? But I get PID 942 which is "svchost.exe" ...if I kill it, Windows starts shutting down
Comment: Run `tasklist /svc` and see what's in that svchost.
Comment: `netstat -a -o command shows that another application is using port 3389` - The server is listening for incoming connections to port 3389. There's always an RDP listener waiting for new connections. This is not your problem.
Comment: After that should I use taskkill?
Comment: @joeqwerty You said.."This is not your problem"..So I was wrong in saying that another application is listening port 3389..right?
Comment: Yes. You were wrong in that assessment. The server is listening for incoming connections to port 3389. There's always an available RDP listener waiting for incoming connections. This isn't the cause of your problem.
Comment: Right..my assessment was wrong ..how would you go about it?
Comment: Try connecting from another system in the same local area network. That will either confirm or eliminate a network firewall issue.
Comment: in your netstat output did the connection show up as 0.0.0.0:3389?
Answer: I wanted to write it as a comment but it was too long...
There's one troubleshooting step you can take which I believe will help you identify the source of your issue.
Use another computer on your network (in the same LAN) to connect the remote problematic computer using telnet, like so:
telnet remote_computer_ip 3389
If the response looks like that:
Trying 10.13.0.2...
Connected to 10.13.0.2.
Escape character is '^]'.

Then it means that the remote computer listens on port 3389 (RDP's default port) and it also means that there's no network / firewall issue and that a connection can be established between these two computers on port 3389.
If your remote host doesn't respond to telnet then I'd try the following things:

Check that you are trying to connect to the right IP, if it's a dynamic connection and the router disconnects and then redials it could be that your route will get a new IP lease from the ISP's DHCP server.
Double check (even if it worked yesterday and you didn't change anything since then) that remote desktop is enabled:
Right click My Computer and choose Properties, click Advanced System Settings, select the Remote tab and it's in the lower bottom of the screen, also, just for the test, make sure that the second option is selected, which says that any version of RDP client can connect to the host.
Check in the Windows Firewall settings that firewall is disabled for all profiles: Domain, Private, Public.
Hold Windows key + R and type: eventvwr, under Windows Logs, choose Application and use the filter in the right panel to display only errors, then look for errors regarding RDP.

There's one more thing I'd check, and that's the router, it usually comes with a built-in firewall which you can configure to allow traffic to the local network through specific ports, it's called NAT and if that would be the case I will help you configure the correct rule.
By the way, in regard to your question, the fact that the computer has access to the internet doesn't mean it has access from the internet toward your private network which is what you need.
Most if not all firewalls, by default block all incoming traffic and allow all outgoing traffic.
When configuring a new firewall for example, you start from the basic rule which is "Deny All" and then you continue adding "Allow" rules.
Please let me know if any of these steps help you find the issue.
Answer: Go to 'RDP-Tcp Properties' Administrative Tools\Remote Desktop Services\Remote Desktop Session Host Configuration
In Remote Desktop Session Host Configuration.
Set Security Layer to 'RDP Security Layer'
Make sure that box unchecked  'Allow connectors only from computers using Rem. Desk. with Network Level Authentication'.


custom module folder

Question: In Pro Drupal 7 Development: Third Edition, the authors suggest moving custom modules inside subfolders of /sites/all/modules/custom/, i.e.

/sites/all/modules/custom/mymodule1
/sites/all/modules/custom/mymodule2
/sites/all/modules/custom/mymodule3

Does this have any special meaning for Drupal core? For example, is this folder omitted when checking for new versions of modules? I haven't checked this so far so I'm just curious.
Before I read the book I put my custom modules like this:

/sites/all/modules/mymodule1
/sites/all/modules/mymodule2
/sites/all/modules/mymodule3
Answer: It shouldn't break anything, and it has no special meaning to core: as long as it's in a modules directory, it will be searched recursively (which is why larger projects often have submodules in a subdirectory).
However, it does allow site-builders to organize their modules more neatly than just lumping everything together. You'll often see modules/ directories structured in a way similar to this:

/path/to/modules/contrib: Modules downloaded from contrib
/path/to/modules/custom: Custom modules that you write for this site
/path/to/modules/devel: Modules not meant to be enabled on live
/path/to/modules/features: Modules created by Features

This organizational setup is often used when building installation profiles and distributions as well, so if you download a few you'll probably see more examples of this sort of organization put into practice.
Comment: On your existing site, if you just move, e.g. the modules in `sites/all/modules/` to `sites/all/modules/contrib/` then you may encounter errors, perhaps fatal (seen in the browser on your site and at the command line when using drush) as myself and other folks have seen--that they describe here: https://drupal.org/node/1423374 For me, none of the remedies worked and I still got the PHP fatal error complaining about a file within one of the modules, geofield, so I had to revert back to original path. Comments?
Comment: You may also find this answer helpful if you have errors due to the original paths needing modifying in the database: http://stackoverflow.com/a/13985139/227926
Answer: In regards to errors after moving modules around in folders:
Configuration > Development > Performance > Flush All Caches
If Errors persist:
http://example.com/update.php then follow through steps.
Try the Administration Menu module.

Download Administration Menu.
from admin/modules enable Administration Menu along with Administration Menu Toolbar Style (at same time, disable core Toolbar module).
Move your modules and/or module folders as you like
Now, from Home (top left) dropdown, Flush All Caches > Class (or Theme) Registry

Lookup "Drupal Registry" or see the Drupal API description.
Alternately, the PHP is:

        <?php
        function registry_rebuild() {
        system_rebuild_module_data();
        registry_update();
        }
        ?>

Answer: Remember that when you can always use drupal_get_path() in your custom code if you need to use the path to your module. It will continue to work when you have multiple subdirectories inside sites/all/modules.
drupal_get_path('module', 'my_module_name');

On large sites, I split up modules into three folders, but you can use more:
sites/all/modules/custom
sites/all/modules/contrib
sites/all/modules/features

If you are building your site with Profiler, you can also specify which folder the module code is placed in. For example, to add File Entity to your installation profile inside the contrib folder:
projects[file_entity][version] = "2.0-alpha3"
projects[file_entity][subdir] = "contrib"

custom module folder


Apache reverse proxy rewrite get url

Question: I have a intranet server which isnt reachable from the public. Also i have a Server where a Apache reverse proxy is running.
Intranet: intranet.domain.com
Reverse Proxy: external.domain.com
This is my Config
<VirtualHost *:443>
    ServerName       external.domain.com
    ErrorLog /var/log/apache2/reverseproxy-error-log
    CustomLog /var/log/apache2/reverseproxy-access-_log combined
    LogLevel          warn
    AddDefaultCharset utf-8

      SSLEngine On
      SSLProxyEngine On
      SSLProxyVerify none
      SSLProxyCheckPeerCN off
      SSLProxyCheckPeerName off
      ProxyRequests Off
      ProxyPreserveHost On

       <Proxy *>
         Require all granted
       </Proxy>

    Forwarding Intranet to external
          ProxyPass / https://intranet.domain.com/
          ProxyPassReverse / https://intranet.domain.com/

       ProxyErrorOverride Off
  </VirtualHost>

I have deleted the part where i set the SSL certificate etc. as thats not the problem
When i now load external.domain.com the site is loading but all of the pictures and css isnt loaded because its loaded from intranet.domain.com and so i get 404.
As an example this is a GET request i see.
scheme
    https
host
    intranet.domain.com
filename
    /fileadmin/user_upload/Admin/Header/Header_Telefon.jpg

So my question is now how can i rewrite that request so the host is external.domain.com instead of intranet.domain.com
Because when i try this url https://external.domain.com/fileadmin/user_upload/Admin/Header/Header_Telefon.jpg i can see that image without any problem.
Answer: You need to configure the application that runs on internal.domain.com, to that it produces either only relative URL's, or URL's using the domain external.domain.com.  Apach's proxypassreverse can't change URL's inside response bodies.
Comment: Found the solution like 2 hours ago. Youre completly right !

The server is running Typo3 and it had
`config.baseURL= http:///` activated.

I changed it to
`config.absRefPrefix = /`.

Now everything is working just fine :) Thank you very much !

Apache reverse proxy rewrite get url


Solana Anchor: How to make #[account(seeds)] for/ read associated accounts?

Question: in the Basic-5 tutorial of the  project-serum/anchor repo
How can I replace #[associated]
with something like this:
#[account(seeds = [user_data.deposit_last.as_ref(), &[user_data.__nonce]])]

There is something not correct above, then Anchor fails to read the associated account's values
const userData = await program.account.userData.associated(wallet1, usdcMint);

So what is the correct way to replace this soon-to-be-deprecated #[associated] above the associated account struct?
#[associated]
#[derive(Default)]
pub struct UserData {
  pub authority: Pubkey,
  pub deposit_last: i64,
  pub shares: u64,
  pub reward_debt: u64,
}

//UserData is initialized here first
#[derive(Accounts)]
pub struct Initialize<'info> {
  #[account(init, associated = authority, with = usdc_mint)]
  pub user_data: ProgramAccount<'info, UserData>,
...
}

Answer: So the seed approach is a PDA, which is actually what #associated was using underneath the hood
You will need a function that initializes the seed with the below init and payer trait. payer should also be the same user who is actually paying the for transaction.
Please note that #[instruction(bump: u8] is matching the signature of the function here, hence you will need to pass in the bump in the signature as the first argument.
#[instruction(bump: u8)]
pub struct Ctx<'info> {
  #[account(init, seeds = [user_data.deposit_last.as_ref(), &[bump]], payer = payer)]
  pub user_data = ProgramAccount<'info, UserData>,
}

Later on for other functions if you want just want to read the account, you can just use
#[account(seeds = [user_data.deposit_last.as_ref(), &[user_data.__nonce]])]
pub user_data = ProgramAccount<'info, UserData>,

Change your account data to use #[account] instead of #[associated]
#[account]
#[derive(Default)]
pub struct UserData {
  pub authority: Pubkey,
  pub deposit_last: i64,
  pub shares: u64,
  pub reward_debt: u64,
}

Here is an example https://github.com/project-serum/anchor/blob/master/examples/misc/programs/misc/src/context.rs#L10
Comment: @yangli-io Your example link gives me a 404 error.  Perhaps it would be helpful to copy the page content into your answer?
Comment: It's not a shortcut, the `#[instruction(bump: u8)]` is for when you want to be able to access your method parameters
Comment: As @RobertOschler mentioned, the example is 404.  This link should last as long as the repo: https://github.com/project-serum/anchor/blob/v0.14.0/examples/misc/programs/misc/src/context.rs
Comment: yangli-io, thank you! I tried that and I got anchor test working by just replacing #[associated] with #[account], then adding "pub __nonce: u8," to the UserData struct! Is that a shortcut to your function #[instruction(bump: u8] ?


Arduino leds acendendo sem apertar o botão

Question: Eu não sei o motivo, mas os leds acendem mesmo se eu não apertar o botão.
    int button = 12;
    int led1 = 2;
    int led2  = 3;
    int led3  = 4;
    int led4 = 5;
    int led5 = 6;
    int led6 = 7;

    int buttonState = 0;
    long randNumber;

    void setup(){
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);

      pinMode(button, INPUT);
      Serial.begin(9600);
      randomSeed(analogRead(0));
    }

     void loop(){
      if (digitalRead(button) == HIGH){
            buttonState = 1;
            randNumber = random(1, 7);
            delay(100);
            Serial.println(randNumber);

            if (randNumber == 6){
              seis();
            }
            if (randNumber == 5){
              cinco();
            }
            if (randNumber == 4){
              quatro();
            }
            if (randNumber == 3){
              tres();
            }
            if (randNumber == 2){
              dois();
            }
            if (randNumber == 1){
              um();
            }
              delay(5000);
              zero();
              buttonState = 0;
          }
      else{
          zero();
          buttonState = 0;
      }
     }
     void seis()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
      digitalWrite(led4, HIGH);
      digitalWrite(led5, HIGH);
      digitalWrite(led6, HIGH);
    }

    void cinco()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
      digitalWrite(led4, HIGH);
      digitalWrite(led5, HIGH);
    }

    void quatro()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
      digitalWrite(led4, HIGH);
    }

    void tres()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
    }

    void dois()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
    }

    void um(){
      digitalWrite(led1, HIGH);
    }

    void zero(){
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
      digitalWrite(led6, LOW);
    }

Answer: @freddoggo, a linha abaixo
if(digitalRead(button) == HIGH)

tem que ser
if(digitalRead(button) == LOW)

pois qualquer oscilação na corrente de entrada acaba gerando um falso positivo para o processador do arduino.
Por isso, uma boa prática é manter a porta sempre energizada e o botão aterra a porta, desse modo, vc lê sempre o LOW.
Pesquise a respeito de resistor de pull-up interno do arduino (abaixo)
pinMode(button, INPUT_PULLUP);

Um bom artigo de referência é: https://www.hackster.io/SMM2/you-ve-been-using-a-button-wrong-this-whole-time-fcd5c6


How to plot binary vs. categorical (nominal) data?

Question: I am building a machine learning model for a binary classification task in Python/ Jupyter Notebook. I am currently in the "Exploratory data analysis" phase and try to create multiple plots/ graphs for my data set.
My data set consists of 20 columns (19 features and 1 labeled target). Each row in my data set represents a person. There are many categorical/ nominal features in my data set and only few numerical/ continuous ones. Unfortunately I cannot upload the real data set, so I will create a dummy one.

personID
age
car
TARGET_happiness

1
27
ford
0

2
41
tesla
1

3
55
bmw
0

4
34
tesla
1

5
62
ford
1

6
38
ford
1

7
51
bmw
0

8
46
tesla
1

9
72
bmw
0

10
59
tesla
0

11
48
ford
0

12
51
bmw
1

My aim is to create a plot/ graph to visualize the relationship between the binary variable TARGET_happiness (meaning "is the person happy?") and the categorical variable car (meaning "which car does this person own").
The plot I've used for binary TARGET_happiness vs. continuous age is a box plot, see:

This seems fine. Now I also try to use a box plot for binary TARGET_happiness vs. categorical car:

I'm not sure if this plot is useful / appropriate. Sure, you can see that Tesla owners seem to be happier than BMW owners. But the box for Ford owners looks strange.
Which type of plot/ graph can I use to better visualize the relationship between binary and categorical data?
Comment: Despite the different title, just about every idea in the above thread carries over to this case.
Comment: Box plots are generally useless for binary data or ordered data with only a few distinct values. If more than 25% of values are equal to the lowest value recorded then that value is both the minimum and the lower quartile and any whisker collapses to a line of zero length you can't see. A similar story applies at the other end of the distribution with the maximum and upper quartile. If less than 25% are values equal to the minimum or to the maximum, you may see a point symbol for each but the box plot alone won't tell you if that represents one data point or (almost) a quarter of them.
Comment: Thinking through the definitions shows that other weird-looking box plots can arise. For example, suppose 20% of values are 1 or 2, 60% of values are 3 and 20% of values are 4 or 5. Then 3 is at once the median and both quartiles and the box collapses to a line of zero length and it's a moot point whether your software will show it. Simple bar charts will work better.
Answer: It makes more sense to count your 0/1 in each of the categories, for example:
import pandas as pd
import seaborn as sns

df = pd.DataFrame({'car':['ford','tesla','bmw','tesla','ford','ford','bmw','tesla','bmw','tesla','ford','bmw'],
                  'TARGET_happiness':[0,1,0,1,1,1,0,1,0,0,0,1]})

sns.catplot(x='car',hue='TARGET_happiness',data=df,kind="count")

Or directly using the plot method in pandas:
pd.crosstab(df['car'],df['TARGET_happiness']).plot.bar(stacked=True)

Comment: This is clear and straightforward. It should be the accepted answer.


Active Directory & Group Policy - Standard User Permissions

Question: As I'm experimenting with a vanilla Active Directory domain, I notice that a standard user can go into Active Directory Users and Computers (dsa.msc) and Group Policy Management Console (gpmc.msc) and view the configuration in both of those respective services (AD and Group Policy).
Additionally, I also notice that a user can search for AD objects on the domain. Out of pure curiosity, how would I go about disabling user access to these if I were going to for security purposes while not breaking any other functionality?
I'm running Server 2016 with a Server 2016 functional forest and domain level. All hosts are either Server 2016 member servers or Windows 10 clients.
Comment: Viewing some domain objects is not likely your main concern; I would focus on other aspects of securing your environment - like restricting your administrative accounts - that is far far more troublesome that some users reading directory information.  The other step would be not prohibit dsa.msc and gpmc.msc from running on user workstations.  probably should also block dsac.exe and ldp.exe
Answer: From this explanation of restricting rights in Active Directory:

By default, typical domain users have Read access to almost everything in AD domains—including users, groups, organizational units (OUs), and Group Policy Objects (GPOs).
...
The only way to restrict users is to restrict Read permissions on objects that you don't want users to be able to read. However, be judicious when restricting Read access to AD objects, or you might run into problems. For instance, if users don't have Read access to other user objects, they might not be able to use Microsoft Exchange Server to find mail recipients. And if you deny users Read access to GPOs, settings that you configure under User Configuration in those GPOs won't be applied.


Does an implied tie exist

Question: Is there such a thing as an implied tie? Like some kind of symbol or notation that would specify to hold a note through the duration of all the notes on a pitch as if they were tied together.
Edit: I am asking because I am wondering if there is a way to specify that instruments hold one tone (like a choir that is humming) instead of playing each note separately. The reason I am wondering is because I am using a notation program to write out some music, and then you can listen to it, and I want to hear it like a choir humming. I know about ties, but I just thought I'd check if there is such a thing in music.
Edit: By implied, I mean it isn't written in the music. In other words it is specified at the beginning of the part or something like that.
Edit: I am using Noteworthy Composer.
Comment: Out of curiosity, why do you ask?
Comment: Yes, what's wrong with just using a tie?  **Edit:** "a way to specify that instruments hold one tone instead of playing each note separately" sounds like legato.  I don't see how this relates to a choir humming?
Comment: What instrument?  Clarinet? Harp? Pipe organ?
Comment: it would be pipe organ type of sound rather than piano. IOW, sustained for the duration of the "key press".
Comment: Also, it relates to a chior humming, in that if the next note is the same, they won't release and then attack it, they'll just keep on humming. For that matter, they usually don't even release except for a breath (well, I don't really know what the pros do, but I don't).
Answer: If you want a long, sustained note, you could notate it in quite a few different ways. Below are some suggestions. Not all will actually save you time, by cutting notation, though! Each of these is only five bars long, so, obviously, you would only get any time benefit from using these techniques with longer notes.
BTW, I haven't used Noteworthy Composer before, so have no idea if they would work with that software. I used Sibelius7 for these, and all played back exactly the same (apart from the second line), i.e. with one sustained note per bar.

Standard Notation.
Similar notation using ties into rests; even though this doesn't require notes to be written, it would actually take more time to put in as the placement of the ties is fiddly. For instruments where the sound decays (eg. piano, guitar) you would usually use l.v. too.
Using repeat-bar marks can save a lot of time.
This notation is effectively the same, and plays back the same, but is less clear; it's not clear whether you attack the second note…
And of course, if in doubt, use text to make the intention clear in the score.

With this answer I've tried to show different kinds of notation for sustained notes that would be valid within a score. Not all of them would save time if all you actually want is to hear the music (or to create a MIDI file of it, for instance). If all you want is to create a long held pitch, as quickly and easily as possible, the notation below will create the necessary effect (well, again, it works in Sibelius7, but might not in other software). But it is certainly not correct notation!
Comment: How about using a whole note in the first, second, and last measures, repeat-measure marks in the interim, and a single long slur mark that extends uninterrupted from the first measure to the last under all of the repeated measures?
Comment: @Bob, the style of the last example (__Ped__ through rests) _is_ frequently used... for piano.
Comment: Example 5 is ambiguious. You instruct to hold for 5 bars, but clearly notate a seperate note in bar 5.

If you want playback from a notation program, just write the tied notes and don't try to concoct a shortcut.
Answer: As I understand your question, no there is not. A tie is always written out with a curved line connecting two or more notes of the same pitch.
The only thing that I can think of that comes close is a dotted note. However, a dotted note is viewed as one note, not multiple notes tied together.
Comment: Hopefully my edit explains it.
Comment: I see. A tied note should work for your purposes. If it makes it any easier, a tie can cover more than two notes.
Comment: Yeah, it does, I just wish I wouldn't have to add all those ties, but I guess it's not like I'm working with beethovan or something like that, it's just hymns.
Comment: If the notes are changing pitch, though, make sure it's a slur. Plenty of music programs get confused if you start adding ties to notes that don't have the same note next.
Comment: Yeah, this program (Noteworthy Composer) indicates exactly what it will do.
Answer: It depends on the instrument.  The abbreviation "l.v." is used.  It stands for "lasciare vibrare" in Italian, or "let vibrate" or as luser droog says, "let ring".  It is used for percussion instruments like the tam-tam and timpani, and also for harp and similar instruments.
For piano music Beethoven uses "senza sordini" which means "without dampers", i.e. hold the damper pedal down.  See the first movement of the Moonlight Sonata (Sonata number 14).
Your best bet is to just write instructions at the beginning telling the musician what to do.
Answer: In guitar music you occasionally find the remark "Let Ring." This means tones are held as long as possible, until that finger is required elsewhere. A somewhat similar effect is produced by holding the sostenuto pedal on a piano.
[Perhaps my terminology implies more expertise than I actually possess. I learned on an antique player-piano with the player mechanism discarded. It had a pedal that moved all the hammers closer to the strings thus curbing the range of accelleration, the 'piano' pedal. And it had a pedal to raise all the dampers so every tone rang until it had diminished below the threshold of perception. It is this pedal that I mean by 'sostenuto'. To use it musically, you have to clear the memory while sounding a new chord, so as to have no gap in the sound. There are some fancy "modern" pianos that can sustain only the notes currently being played, allowing staccatto on the other keys. The player-pianos of yore did not have this ability.]
While the staff notation would be no different than not doing this, it does seem to require explicit instructions (e.g., "Hold pedal until a chord can hide the pedal change."). Instructing software to do this would be somewhat different than instructing musicians.
Comment: There are other instances in musical notation with implied notation such as an accidental carrying over to other notes in the same measure. As to *let ring* and *sostenuto*, this is not `hold[ing] a note through the duration of all the notes`. There is but pone lengthy note being played in these instances.
Comment: I tried to capture that distinction with my weaselly 'somewhat similar'.
Comment: In the same sense, you could call a fermata 'somewhat similar'.
Comment: I think I get what you're saying now. It's not like a tie because you still have the attack of the second note. But it *is* like a slur, which looks pretty much the same.
Answer: Now, just a moment... Hymns, Choir, Implicit Ties...
Could you be talking about like Gregorian Chant kind of stuff? AFIK, Gregorian Chant is distinguished in notation by having only four lines, with or without a clef, which may be any letter a-h ("No B♭, that's a Bad B♭!").
Older than that is notation based on 'neumes' which I never really understood. But neume comes from 'pneuma', greek for spirit or breath; so with both of these, the notes comprising one word of the text are to be sung as if tied together.
For software, I'd search for something with a Chant mode, or a plugin or something. This has got to be already-explored territory. 2¢
Comment: This is not standard, modern notation.

Does an implied tie exist


How to identify if a given Hasse diagram is a lattice

Question: How to identify if a given Hasse diagram is a lattice?
Comment: The first step is knowing what a lattice is. Do you know what a lattice is? Then: do you know what a Hasse diagram is depicting with its lines and points?
Answer: For a partial order to be a lattice, it needs a join (a minimal upper bound) for any two of its elements. In your diagram, $2,3$ don't have an upper bound at all -- hence this is not a lattice.


Solaris: information on sparc hardware

Question: I'm having 2 solaris machines to manage, So i want to write my own scripts for getting various information. I'm able to get most of the information but not able to retrieve following:

Chassis type
Mother Board S/N
OS Language

I have no physical access to the machine. I'hv already tried dmi_cmd but it just got stuck at connecting. I'm not able to find sneep package. locale does not provide language information. Even if i try to set it, the command exits with error saying unable to set locale.
smbios would not work hence its a sparc machine.
Comment: You can only get the S/N if you've installed sneep and set the serial manually. There's no other way to get it other than a physical check.
Comment: @James can you please share a location where i can download sneep i couldn't find this package?
Comment: Log in to My Oracle Support and look for the Service Tools Bundle.
Answer: Little rusty on sparc/solaris, but these might help ...

Chassis type : As far as I remember one of the uname switches will give you a model, e.g. v240.  If you just run uname -a it should be in there somewhere.
S/N : try prtconf -v or lsconf
echo $LOCALE ?
Comment: `echo $LOCALE` should be `echo $LANG` or `/usr/bin/locale` - but that reports the locale/language settings you use, which aren't necessarily the system defaults (users can choose their own language).   `locale -a` lists all the locales installed on the system.
Comment: uname does not tells whether its a desktop/laptop/server
prtconf does not revels S/N in my case
echo $LOCALE ? does not return anything i tried without ? also
Comment: However i was thinking of that chassis can be derived from the model name given by uname -i and use some look ups to decide laptop/desktop/server that would be requiring look up table it will not be consistent if the machine changes
Comment: @alanc I want something like "locale -ck LC_IDENTIFICATION" in RHEL it specifies english etc
Answer: The command prtdiag will give you as much HW info as I have seen on Solaris machines look at /etc/default/init for default language settings
Comment: It does not gives chassis type (laptop/Desktop/server) and mother board S/N
Comment: Thats the best I have found on Solaris if it isn't contained there as far as HW info you will be pressed to find it from software :(
Comment: There is no parameter in that file for language. however on RHEL it can be retrieved by locale -ck LC_IDENTIFICATION
Comment: Any way thankx trent for your time

Solaris: information on sparc hardware


Angular 7 - Recarregar datatables após deletar um item da tabela

Question: A datatable apresenta um erro após eu deletar um item da tabela, a mensagem inclui um site que eh este: Cannot reinitialise Datatable
Pensei em alguma maneira de "sair e voltar" da página para atualizar a tabela, mas não tive sucesso. O teste que não deu certo foi com o "this.router.navigate(['modulos']);"
Cheguei a conclusão de que eu devo inserir algum comando na função "getList()" ou "delete()".
Modulos.component.ts
import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { Router } from "@angular/router";
import { Subject } from 'rxjs';

import { Modulos } from '../../interface/modulos';
import { ModulosService } from '../../services/modulos.service';

@Component({
  selector: 'app-modulo',
  templateUrl: './modulos.component.html',
  styleUrls: ['./modulos.component.css']
})
export class ModulosComponent implements OnDestroy, OnInit {

  public modulos: Modulos[];
  deleteModalRef: BsModalRef;
  deleteId: number;
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();

  @ViewChild('deleteModal') deleteModal;

  constructor(private modulosService: ModulosService,
              private bsModalService: BsModalService,
              private router: Router) { }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10
    };

    this.getList();
  }

  getList() {
    this.modulosService.getList().subscribe(
      (modulos: Modulos[]) => {this.modulos = modulos; this.dtTrigger.next();}, //this.dtTrigger.next();
      (error) => {console.log(error); }
    );
  }
  ngOnDestroy(): void {
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();

  }
  onDelete(id: number) {
    this.deleteId = id;
    this.deleteModalRef = this.bsModalService.show(this.deleteModal, {class: 'modal-sm'});
  }
  onConfirmDelete() {
    this.delete(this.deleteId);
    this.deleteModalRef.hide();
  }
  onDeclineDelete() {
    this.deleteModalRef.hide();
  }
  private delete(id: number) {
    this.modulosService.delete(id).subscribe(
      (response) => {console.log(response); this.router.navigate(['modulos']); },
      (error) => {console.log(error); }
    );
  }
}

Modulos.component.html

 Modulos

    <button class="btn btn-success m-3" [routerLink]="['new']">Criar Módulo</button>

      ID
      Nome
      Descrição
      Sistema
      Setor
      Modulo Pai
      Ações

      {{ m.id_modulo }}
      {{ m.nome_modulo }}
      {{ m.descricao }}
      {{ m.nome_sistema }}
      {{ m.nome_setor }}
      {{ m.nome_modulo_pai }}
      <button class="btn btn-sm btn-info mr-2" [routerLink]="[m.id_modulo, 'edit']">Editar</button>
        <button class="btn btn-sm btn-danger mr-2" (click)="onDelete(m.id_modulo)">Deletar</button>
        <button class="btn btn-sm btn-secondary" [routerLink]="[m.id_modulo, 'add']">Criar Formulário</button>

<ng-template #deleteModal>

Tem certeza que quer deletar?

    <button type="button" class="btn btn-default" (click)="onConfirmDelete()">Sim</button>
    <button type="button" class="btn btn-primary" (click)="onDeclineDelete()">Não</button>

</ng-template>

Modulos-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ModulosComponent } from './modulos.component';
import { ModulosFormComponent } from './modulos-form/modulos-form.component';
import { ModulosShortcutComponent } from './modulos-shortcut/modulos-shortcut.component';

const routes: Routes = [
  { path: '', component: ModulosComponent},
  { path: 'new', component: ModulosFormComponent},
  { path: ':id/edit', component: ModulosFormComponent},
  { path: ':id/add', component: ModulosShortcutComponent},
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ModulosRoutingModule { }

Comment: Eu pesquisei, editei, testei e não funcionou a atualização da datatables. Se alguém souber, por favor, deixe um comentário ou uma resposta para ajudar a solucionar esse problema.
Answer: Olá, você pode tentar atualizar a tabela utilizando o setTimeout(), utilize um *ngIf="show" (na table) e uma variável boolean, onde ela vai fazer com que a tabela apareça e desapareça do DOM.
Por exemplo:
att() {
thiS.getList() // para atualizar o dados do array
  this.show = false // tirar tabela do DOM
    setTimeout(() => {
      this.show = true // retorna com tabela para o DOM e os dados atualizados do
                          this.getList()
    }, 50);
}

Comment: Funcionou, muito obrigado pela ajuda!
Comment: Valeu, amigo. Eu estava com o mesmo problema esses dias, só consegui resolver desta maneira. Poderia marcar a resposta como útil?
Comment: Da um Up na postagem pra ajudar tbm! Valeu!
Answer: Olá, a resposta do Edson funcionou mas eu reservei e pesquisei por outras soluções por conta do "piscado na tela", quando some a tabela e mostra novamente.
Então eu fui testando e essa solução funcionou pra mim, sem "piscar" a tabela:
excluir(id: number) {
   this.listaQuePopulaATabela = this.listaQuePopulaATabela.filter(item => item.id != id);
}

Comment: @cassiooliveira depois de muitos anos, eu também cheguei nessa solução, mas nem lembrava mais dessa pergunta


Generating a Cyclic Spectrum

Question: I'm trying to generate a spectrum of all the cyclic combinations from my peptide.
Here's my the code for the linear spectrum:
#For example: LEQN
#L:113 E:129 Q:128 N:114
    peptide = [113,129,128,114]
        for a in peptide:
            for i in peptide[b:]:
                s+= i
                spectrum.append(s)
            s=0
            b += 1

spectrum.sort()
print spectrum

Outputs: [113, 114, 128, 129, 242, 242, 257, 370, 371, 484]
My code successful adds these sums L(113), E(129), Q(128), N(114), LE(113+129), LEQ(113+129+128), LEQN(113+129+128+114), EQ(129+128), EQN(129+128+114), QN(128+114)
BUT is missing QNL(128+113+114), NL(114+113), NLE(114+113+129)
Ex. QNL should be 128+114+113 which is the summation of elements 2, 3, and 1.
NL is 114+133 which is the summation of elements 3 and 0. And NLE is 113+114+129 which is the summation of elements 3, 0, 1.
*I wouldn't need to add EQNL or QNLE because they are exact same thing as LEQN.
*However LE=242 and QN=242 have the same mass but are NOT the same thing.
Expected Output: 113, 114, 128, 129, 227(N+L), 242, 242, 257, 355(Q+N+L), 356(N+L+E), 370, 371, 484
Comment: It's a bit unclear what you're trying to do, could you specify the expected output and what a cyclic combination is?
Comment: Can't you just duplicate the peptide in tandem and loop through peptide[0:4], peptide[2:6], peptide[3:6], peptide[3:7], etc?
Comment: What do you mean @heathobrien? Ok I added more details along with my expected output.
Comment: See my answer for what I meant
Answer: If I understand your question correctly, you want all the possible sublists, for each length up to the length of the peptide list and for each starting position in that list, wrapping around at the end of the list. One way to do this would be using cycle and islice from itertools.
from itertools import cycle, islice

peptide = [113, 129, 128, 114]
spectrum = []
for num in range(1, len(peptide)):
    for start in range(len(peptide)):
        group = islice(cycle(peptide), start, start + num)
        spectrum.append(sum(group))
spectrum.append(sum(peptide)) # add the entire list only once

This way, sorted(spectrum) ends up as [113, 114, 128, 129, 227, 242, 242, 257, 355, 356, 370, 371, 484], which seems to be what you wanted.
Not sure, though, how this scales to much longer lists of peptides (I'd assume in practice those lists have more than four elements).
Answer: peptide = [113,129,128,114]
peptide *= 2
spectrum = []
for i in range(len(peptide)/2):
    for j in range(i+1,i+4):
       s = 0
       for a in peptide[i:j]:
           s+= a
       spectrum.append(s)
spectrum.sort()
print spectrum

Comment: Admitedly, that doesn't include the sum for the entire peptide
Comment: This code would be more useful it there was additional comments and explanation.

Generating a Cyclic Spectrum


Manually syncing comp clock with DC works, but after a minute - clock incorrect by 5 minutes

Question: The problem:

DC1 Clock: 17:23
AD joined client clock: 17:28

After client> w32tm /resync time is in sync, but the clock again jumps forward for 5 minutes for client. It always happens in less than a minute.
Ok, maybe syncing from somwhere else. I did manually set peer list to domain controllers
:
client>w32tm /config /manualpeerlist:"DC1 DC2 DC3" /syncfromflags:manual
The command completed successfully.

client>w32tm /resync
Sending resync command to local computer
The command completed successfully.

The result? Doesn't help, because behaviour is the same. I should note that the DC and client is in different subnets, but can communicate.
What should I check to further troubleshoot the situation, please?

Posting requested information:
client> w32tm /query /configuration
[Configuration]

EventLogFlags: 2 (Local)
AnnounceFlags: 10 (Local)
TimeJumpAuditOffset: 28800 (Local)
MinPollInterval: 10 (Local)
MaxPollInterval: 15 (Local)
MaxNegPhaseCorrection: 4294967295 (Local)
MaxPosPhaseCorrection: 4294967295 (Local)
MaxAllowedPhaseOffset: 300 (Local)

FrequencyCorrectRate: 4 (Local)
PollAdjustFactor: 5 (Local)
LargePhaseOffset: 50000000 (Local)
SpikeWatchPeriod: 900 (Local)
LocalClockDispersion: 10 (Local)
HoldPeriod: 5 (Local)
PhaseCorrectRate: 1 (Local)
UpdateInterval: 30000 (Local)

[TimeProviders]

NtpClient (Local)
DllName: C:\Windows\system32\w32time.dll (Local)
Enabled: 1 (Local)
InputProvider: 1 (Local)
CrossSiteSyncFlags: 2 (Policy)
AllowNonstandardModeCombinations: 1 (Local)
ResolvePeerBackoffMinutes: 15 (Policy)
ResolvePeerBackoffMaxTimes: 7 (Policy)
CompatibilityFlags: 2147483648 (Local)
EventLogFlags: 0 (Policy)
LargeSampleSkew: 3 (Local)
SpecialPollInterval: 3600 (Policy)
Type: NT5DS (Policy)

VMICTimeProvider (Local)
DllName: C:\Windows\System32\vmictimeprovider.dll (Local)
Enabled: 1 (Local)
InputProvider: 1 (Local)
NtpServer (Local)
DllName: C:\Windows\system32\w32time.dll (Local)
Enabled: 0 (Local)
InputProvider: 0 (Local)

client> get-date -format "yyyy.MM.dd hh:mm:ss"

2013.05.27 10:53:12 (Time WRONG)

client> w32tm /resync
Sending resync command to local computer
The command completed successfully.
client> get-date -format "yyyy.MM.dd hh:mm:ss"

2013.05.27 10:48:03 (Time OK)

client> w32tm /query /status
Leap Indicator: 3(last minute has 61 seconds)
Stratum: 0 (unspecified)
Precision: -6 (15.625ms per tick)
Root Delay: 0.0804749s
Root Dispersion: 7.8843410s
ReferenceId: 0x00000000 (unspecified)
Last Successful Sync Time: 2013.05.27. 10:53:17
Source: DC1
Poll Interval: 10 (1024s)

client> get-date -format "yyyy.MM.dd hh:mm:ss"

2013.05.27 10:53:44 (Time WRONG)

client> w32tm /query /status
Leap Indicator: 0(no warning)
Stratum: 4 (secondary reference - syncd by (S)NTP)
Precision: -6 (15.625ms per tick)
Root Delay: 0.0804749s
Root Dispersion: 7.8845136s
ReferenceId: 0x0A0A0109 (source IP:  10.10.1.9)
Last Successful Sync Time: 2013.05.27. 10:48:17
Source: DC1
Poll Interval: 10 (1024s)

Comment: Is the client a virtual machine?
Comment: If it *is* a virtual machine, check if it is set to synchronize to the hypervisor's host clock. You very likely will find this to be the root of the problem.
Comment: when it goes off by 5 minutes do a w32tm /query /status and post results.  Also, if you can post w32tm /query /configuration (from an admin cmd) that might help others.
Comment: @syneticon-dj o the OS is on a bare hardware.
Comment: @TheCleaner look at the edited question, I did post the results.
Comment: Had the same issue with a virtual machine. Turned off the VM time sync setting (and fixed the clock) and the issue went away.
Answer: net stop w32time

w32tm /unregister

w32tm /register

net start w32time

You do not need to set manual peers in an Active Directory environment, with the sole exception of the forest root PDCe.  Re-registering the w32tm service as shown above on the domain member will reset it to use the NT5DS or "domhier" setting, which is what it should be.
Afterwards, give the client a few minutes to organically locate a suitable DC for time sync. You can use w32tm /query /peers and verify that you are synchronizing with a domain controller.
Comment: Today, when I looked at the clocks, they looked okay. But I did these steps so everything is Ok. Thank you.


Strict convexity of a norm on $C[0,1]$

Question: Why the following norm of $C[0,1]$ is strictly convex
$||| f|||= ||f||_\infty + ||f||_{L^2 [0,1]}$
where $||f||_{L^2 [0,1]}$ refers to $p$-norm of $L^p[0,1]$ when $p=2$.
I'm not sure if this relevant but I did prove that $||f||_\infty$ isn't strictly convex and $||f||_{L^2 [0,1]}$ is strictly convex.
Thanks
( A norm || || is strictly convex if when ||x||=||y||=1 and ||x+y||=2 so x=y )
Comment: If one of the norms is stricly convex then their sum is stricly convex as well, isn't it?
Comment: the problem is that strictly convexity deals with vectors that have the same norm, but in that case the fact that ||f||(L^2 [0,1])= ||g||(L^2 [0,1]) doesn't mean that |||f|||=|||g|||
Comment: Just to make sure we are talking about the same thing, could you add the definition of a strictly convex norm to your question?
Comment: In convex analysis/optimization, strict convexity means $x \ne y, \theta \in (0,1)$ implies $f(\theta x + (1-\theta)y) < \theta f(x) + (1-\theta)f(y)$, so norms aren't strictly convex, due to homogeneity. Rasmus may have been thinking of that definition.
Answer: Hint: if $f$ is not (a.e.) a scalar multiple of $g$, $|(f,g)| < \|f\|_2 \|g\|_2$
(where $(f,g)$ is the $L^2$ inner product), so $\|f+g\|_2 < \|f\|_2 + \|g\|_2$.

Strict convexity of a norm on $C[0,1]$


How do I test the methods or hooks implemented in .module file using PHPUnit?

Question: PHPUnit testing in Drupal 8 works for functionality which are written in class files.
How do I test the methods or hooks implemented in a .module file using PHPUnit in Drupal 8?
Answer: No, PHPUnit is not for testing functionalities written in class files. Quite the opposite, PHPUnit in Drupal can be used to test hooks, functions, and classes implemented from modules.
Drupal core itself has tests for hooks, for example the InfoAlterTest class that tests hook_system_info_alter().
How to write tests is described in Automated tests. Without a specific use-case, I cannot give more details on testing hooks, except saying that functional tests that do not test web output, which is the case for most of the hook tests, the test class needs to extend \Drupal\KernelTests\KernelTestBase.
References

Types of tests in Drupal 8
An Overview of Testing in Drupal 8


How to derive Mean of Truncated Normal Distribution

Question: How to derive Mean of Truncated Normal Distribution which is equation 17 below ?

Note: Image screenshot is taken from L1-Norm Batch Normalization for Efficient Training of Deep Neural Networks
Answer: Expectation of $Y=|X-\mu|$ doesn't depend on $\mu$, because the expression inside the absolute parentheses has zero mean. Direct derivation of $\mu_Y$ follows as below:
Let $f(x)=ce^{\frac{-(x-\mu)^2}{2\sigma^2}}$, where $c=\frac{1}{\sqrt{2\pi}\sigma}$; then,
$$\begin{align}\mu_Y&=\int_{-\infty}^\infty|x-\mu|f(x)dx=2\int_{\mu}^{\infty}(x-\mu)f(x)dx\\&=2c\int_\mu^\infty (x-\mu) e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}dx\underbrace{=}_{u={\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}}2c\int_0^\infty e^{-u}\sigma^2du\\&=2c\sigma^2=\sqrt{\frac{2}{\pi}}\sigma\end{align}$$
If you're interested in the expected value for the PDF $f_Z(z)=2ce^\frac{-(z-\mu)^2}{2\sigma^2}, z\in [\mu,\infty)$, (i.e. half normal folded over $\mu$, not $0$) it also can be found very similarly by just variable changes.
Comment: In R: `set.seed(822); mean(abs(rnorm(10^7, 0, 10)))` returns 7.978422 and `10*sqrt(2/pi)` returns 7.978846, about the expected number of places of agreement.
Comment: you have a typo in the variable u during change of variable, where it should not have the negative sign. Otherwise, everything else looks correct to me...
Comment: @kevin, yes I removed the minus sign; thank you.
Comment: Wait, I need to clarify how is [Half-normal distribution](https://en.wikipedia.org/wiki/Half-normal_distribution) different compared to [folded normal distribution](https://en.wikipedia.org/wiki/Folded_normal_distribution) as mentioned in the document screenshot ?
Comment: half-normal is a special case of folded normal, where the RV inside the absolute value is zero mean.