Appropriate function for two Gaussians

Question: I'm searching for a $y(x)$ function that will produce normalized two Gaussians with a distance, something that looks like:

The picture is a bit-misleading, I need one that they do not cross each other at all.
Any ideas ?
Thank you !
Comment: A single function cannot "cross each other". What about taking the sum ?
Comment: the sum will not be normalized
Comment: divide the sum by two.
Answer: Take something like $$f(x)=\frac1{\color{red}2\sqrt{2\pi}}\left(\exp\{-\frac{x^2}{2}\}\times I_{\{x\leq5\}}+\exp\{-\frac{(x-10)^2}{2}\}\times I_{\{x>5\}}\right)$$
Comment: Thanks, what is I though?
Comment: You are welcome! $I$ is an indicator function which takes a value of $1$ if its argument is TRUE, and zeor otherwise.
Comment: The normalization is approximate. The smaller the distance, the more this will become apparent.
Comment: @YvesDaoust thanks for bringing up the issue: that was the reason I used a red color for the normalization $\color{red}{2}$. All in all OP seems not to care much about technical issues, he simply needed a function and I tried to give him an idea ...
Comment: @Math-fun: no, read the comments to the OP.
Comment: @YvesDaoust I don't see the point you are trying to make :-) It though seems that OP is happy with the simple mix with an indicator function.
Comment: @Math-fun: the OP clearly insists to have a normalized function.He accepted the answer unknowingly.
Comment: @YvesDaoust Do you think then that the problem is the normalization? Or the "connecting" point? Feel free to correct of course :-)
Comment: @Math-fun: hem, should I quote "the sum will not be normalized" ??? By the way, the OP never said "not to care much about technical issues".

Appropriate function for two Gaussians


iOS : UITableView - Adding columns to your table

Question: I'm looking to change the number of columns my tableview has without subclassing it. Any suggestions?
Answer: I think you can find your happiness here: http://usxue.is-programmer.com/posts/14176.html
With that you can create a Grid and have multiples columns
Answer: If you don't need to select individual columns the you could just subclass UITableViewCell to make it LOOK like it has more than one column.
Answer: Doing this without subclassing anything would need to be done as follows:
1) Place a UIScrollView in the view.
2) Put n amount of UITableViews embedded in the UIScrollView where n is the amount of columns desired.
3) Turn scrolling off in all of the UITableViews.
4) Make all of the UITableView frames equal to that UITableView's contentSize.
5) Set the UIScrollView's content size equal to the largest UITableView's frame.
I have not tested this because I would definitely recommend subclassing either UITableView or UITableViewCell, but this would be one way of doing it.


Python, Django Unit testing. RequestFactory test doesnt work

Question: I have this view that I want to test
def change_item(request):
    name_change = request.POST.get('name_change')
    cost_change = request.POST.get('cost_change')
    category_change = request.POST.get('category_change')
    product_id = request.POST.get('product_id')
    category_name = Category.objects.get(name = category_change)
    product = Product.objects.get(id__exact = product_id)
    product.name = name_change
    product.category = category_name
    product.price = cost_change
    product.save()
    return HttpResponse()

And I wrote a test for It,but it doesn't work (I want to test request)
from django.test import RequestFactory
from django.test import TestCase
from views import change_item
from models import Product
from django.utils import unittest

class TestChange_item(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def change_item_test(self):
        # Create an instance of a GET request.
        request = self.factory.get('main/views')
        # Test my_view() as if it were deployed at /customer/details
        response = change_item(request)
        self.assertEqual(response.status_code, 200)

When I run it I get this in console
ERROR: change_item_test (src.main.tests.TestChange_item)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/volodia/work/shopping-helper/src/main/tests.py", line 19, in change_item_test
response = change_item(request)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 24, in _wrapped_view
if test_func(request.user):
AttributeError: 'WSGIRequest' object has no attribute 'user'

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

What can I do with it ? Or there is some different way of testing requests ?
Answer: If you look at the documentation you will see that you need to manually add a user to the request. It doesn't do this for you automatically.
def change_item_test(self):
    request = self.factory.get('main/views')
    request.user = User.objects.create_user(username="bobalong")

Adding a user like this simulates making a logged in request. If this is NOT what you want then you should create an AnonymousUser instead. In general the error you were getting should provide you with everything you need to know. It is explicitly telling you that the test is failing because the request doesn't have a user. Adding a real user or adding a mock user object to the request is the answer.
Also, you seem to be testing a view that will only work with a POST request. It's going to fail because request.POST does not have the correct dictionary keys. You can create a POST request by doing
factory.post('main/views', {'name_change': 'some name'})`


Why is the softmax on the dot product of the word embedding is the probability of context given word?

Question: I was learning about the Word2Vec model, and the following equation was shown:
$\huge{p(o|c) = \frac{exp(u^T_ov_c)}{\sum_{w\in{V}}exp(u^T_wv_c)}}$
in words, the probability of the context word given the center words is equal to the right hand side, where:
$u^T_o$ is the word vector for the context word
$v_c$ is the word vector for the center word
$w\in{V}$ is any word in the dictionary $V$.
I get the intuition for some of it. by using softmax on $u^T_ov_c$, we get a probability distribution that highlights the higher values while still applies some probability to the lower values (as opposes to hard max).
what I don't get - is what is the proof that the probability distribution on the right hand side it the same probability distribution as the left hand side?
in other words, what justifies the equality sign in the equation?
I could not find the answer in the original Word2Vec paper.
Answer: This question arises from a misunderstanding of what a statistical model is.
Word2vec is a model which means that it's using a statistical procedure to estimate the probabilities given the learning procedure and the data. The equality sign is valid because the RHS is the estimated probability and this quantity is estimated using the values on the LHS.
If you used a different model, or even used a word2vec model with a different data set, you would estimate different probabilities.


-bash: chmod +x: command not found . Using the chmod +x command on MacOS gives error

Question: On my MAC, I'm typing in the chmod +x command, and getting the following error -
-bash: chmod +x: command not found

What should be done here?
echo $PATH
/Applications/apache-maven-3.8.4

Comment: Seems like you've overwritten (as opposed to appended) the `PATH` variable, so that explains it. If you've done it manually in the current shell, just start a new shell, but if you have set it in a config file (e.g., `.zshrc`), revert the change and restart the shell.
Comment: Could be an issue with `PATH`. Could you update your question with the output of `echo $PATH`? I don't have a Mac to confirm it on at the moment, but on Linux `chmod` is located at `/usr/bin/chmod`
Comment: done the same..
Comment: My bash profile looks like -
Comment: Sorry, I just assumed that you were using `zsh` since you're on macOS, hehe, but I see now that it's bash, so replace `.zshrc` with any of `~/.bash_profile`, `~/.bash_login` or `~/.profile` for per-user config (since it seems like you're running a login shell).
Comment: What should I do?
Comment: I don't really follow what your `~/.bash_profile` looks like and you haven't told us whether you're modifying the `PATH` environment variable in any shell startup script or if you only set it manually in the current shell. See my second comment of this thread.
Comment: changed the path variable to /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/apache-maven
Answer: When you want to use terminal commands normally, your $PATH value should be something like this: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin.
If you want to keep /Applications/apache-maven-3.8.4 as $PATH for some reason
, then you should use
/bin/chmod +x /Users/someone/Documents/some_file

instead of
chmod +x /Users/someone/Documents/some_file

Edit:
The error message included the +x as part of the name of the command that wasn't found
I figured out, that you can recreate the error by entering this command in the terminal: "chmod +x" test.txt
--> zsh: command not found: chmod +x To fix it you should do "chmod" +x test.txt.
Comment: The error message included the `+x` as part of the name of the command that wasn't found. That implies a different error than the one you're describing how to fix here. (It should be `bash: chmod: command not found`, not `bash: chmod +x: command not found`)
Comment: I figured out, that you can recreate the error by entering this command in the terminal: "chmod +x" test.txt

--> zsh: command not found: chmod +x

to fix it you should do "chmod" +x test.txt


Ring homomorphism question.

Question: If $R$ is a ring, show that there is exactly one ring homomorphism $\phi: \mathbb{Z} \to R$.
I can't grasp the idea that there can be only one ring homomorphism. Aren't there many (at least more than 1) ring homomorphism between any two rings? Thank you!
Comment: take $R=\mathbb{Z}$ and let $\phi_1(n)=0$ and $\phi_2(n)=n$.
Answer: Hint:
Look at $\,\phi(1)\,$ . What is its role in Im$(\phi)\,$ ? What if there was other homomorphism $\,\psi:\Bbb Z\to R\,$ ? ...
Answer: Hint $\rm\ \ \phi(1) = r\:\Rightarrow\: \phi(k) = \phi(1+\cdots +1) = \phi(1)+\cdots+\phi(1) = r+\cdots+ r = kr$
Remark $\ $ Generally homomorphisms are completely determined by their action on generators. Thus if you are working with rings with $\,1,\,$ where, by definition, ring hom's must map $1$ to $1$, then, as we saw above, $\,\phi\,$ is completely determined by that constraint. Then $\rm\ Im\: \phi \cong \Bbb Z/ker\:\phi = \Bbb Z/n\:$ is called the characteristic subring of $\rm\:R,\:$ and $\rm\:n\:$ is called the characteristic of $\rm\:R.\:$ Therefore the integer $\rm\:n\:$ characterizes the image of $\,\Bbb Z\,$ in $\rm\:R,\:$ i.e. the subring of $\rm\:R\:$ generated by $\rm\:1\in R.$
Answer: It's normal to require that ring homomorphisms map the one-element of the domain to the one-element of the codomain. In this situation it means that $1 \in \mathbb Z$ is forced to be mapped to $1_R \in R$.
Because the additive group $(\mathbb Z,+)$ is generated by $1$ and the map $\phi$ in particular is a group homomorphism from $(\mathbb Z,+)$ to $(R,+)$, this forces $\phi$ to be unique.
Comment: Thanks. I'll just delete that whole business about rngs then. I don't know what I was thinking there.
Comment: Don't worry, it happens to everyone. Deleting my comments.

Ring homomorphism question.


When did drop voicings (e.g. drop, 2 drop 3 etc.) become codified for guitar?

Question: Nowadays the Drop 2 and Drop 3 7th chord voicings for guitar are well-known, especially in Jazz circles.  I don't remember hearing about these when I was reading Metal Solo You Can't Play Monthly back in the 80's.  I have Chuck Wayne's "Guitar Studies - Chords" book wherein he basically claims to have invented or at least independently developed this system decades ago (50's?) without ever calling it that (but he didn't publish until the 90's).  I have also heard that the "Drop __" nomenclature comes from arranging but can't substantiate this.
So my question is what were the first books / schools / artists to introduce Drop 2 and Drop 3 (etc.) voicings by that name as a thing to be learned and where did the concept originate?
Answer: I don't know when it was first described but in Mel Bay's Complete Johnny Smith Approach to Guitar on page 92 there is description of Drop 2 voicing vis-a-vis dominant 7 inversions.  My copy says it was published in 1980.


Replace list using dictionary

Question: Biological RNA:
rna = AGCACGUAGCUGACUGACUGA

protein_chart = {"UUU":"F", "UUC":"F", "UUA":"L", "UUG":"L",
    "UCU":"S", "UCC":"s", "UCA":"S", "UCG":"S",
    "UAU":"Y", "UAC":"Y", "UAA":"STOP", "UAG":"STOP",
    "UGU":"C", "UGC":"C", "UGA":"STOP", "UGG":"W",
    "CUU":"L", "CUC":"L", "CUA":"L", "CUG":"L",
    "CCU":"P", "CCC":"P", "CCA":"P", "CCG":"P",
    "CAU":"H", "CAC":"H", "CAA":"Q", "CAG":"Q",
    "CGU":"R", "CGC":"R", "CGA":"R", "CGG":"R",
    "AUU":"I", "AUC":"I", "AUA":"I", "AUG":"M",
    "ACU":"T", "ACC":"T", "ACA":"T", "ACG":"T",
    "AAU":"N", "AAC":"N", "AAA":"K", "AAG":"K",
    "AGU":"S", "AGC":"S", "AGA":"R", "AGG":"R",
    "GUU":"V", "GUC":"V", "GUA":"V", "GUG":"V",
    "GCU":"A", "GCC":"A", "GCA":"A", "GCG":"A",
    "GAU":"D", "GAC":"D", "GAA":"E", "GAG":"E",
    "GGU":"G", "GGC":"G", "GGA":"G", "GGG":"G",}

I want to split the rna into groups of 3 and replace all of those items with their representative components from the "protein_chart" dictionary, but I can't seem to get it to work using other examples I found.
Help?
Comment: Please show your code. It will really help us start troubleshooting your problem. Also, please make sure you have read this: http://stackoverflow.com/help/how-to-ask :)
Answer: You can do it using join and slicing:
print(''.join(protein_chart[x] for x in [rna[y:y+3] for y in range(0, len(rna), 3)]))

Answer: You could use:
# Split the rna vector into chunks of three
rna = 'AGCACGUAGCUGACUGACUGA'
n = 3
rna_split = [rna[i:i+n] for i in range(0, len(rna), n)]

# Go through dictionary looking for entries and printing them
for dna_el in rna_split:
    print(protein_chart[dna_el])

Comment: Great answer! But, you should make `rna` a `string` first.

Replace list using dictionary


Cálculo para dias dos meses (calendário)

Question: Tenho um array que contém todos os meses do ano. Quero criar um calendário.
var meses= new Array("Janeiro","Fevereiro","Marco","Abril","Maio","Junho","Julho","Agosto","Septembro","Outubro","Novembro","Dezembro");

Com este array, como fazer para os diferentes dias dos meses, e para o mês de fevereiro.
Comment: Ainda não entendi, mas você quer um *array* com o total de dias de cada mês? Algo assim? `var ultimoDiaMeses= new Array(31,28,31,30,31,30,31,31,30,31,30,31);`. Teria que fazer uma verificação de bissexto para usar 28 ou 29 dias para fevereiro. Não consigo imaginar o que seja esses 27 dias que você falou.
Comment: Não entendi onde você quer chegar.
Comment: Distingir os meses com os seus dias, para poder apresentar numa tabela. No caso de fevereiro, ou 28 ou 29 dias.
Comment: Sim tenho um ciclo for para mostar todos os meses até o fim do array (meses.length). Agora que condiçao para mostrar os dias de casa.
Answer: Aqui fica uma sugestão:

var meses = new Array("Janeiro", "Fevereiro", "Marco", "Abril", "Maio", "Junho", "Julho", "Agosto", "Septembro", "Outubro", "Novembro", "Dezembro");

function diasDoAno() {
    var ano = $('#ano').val();
    var dias = [];
    for (var x = 0; x < 12; x++) {
        var diasNoMes = new Date(ano, x + 1, 0).getDate();
        dias[x] = [];
        for (var i = 1; i <= diasNoMes; i++) {
            dias[x].push(i);
        }
    }
    var resultado = $('#resultado');
    dias.forEach(function (mes, i) {
        var div = $('
').addClass('mes');
        div.append(meses[i]);
        var subDiv = $('
').addClass('dias');
        mes.forEach(function (dia) {
            subDiv.append(dia);
        });
        div.append(subDiv);
        resultado.append(div);
    });
}

$('button').on('click', diasDoAno);

Insira ano: <input type="text" id="ano"/>
<button>Mostrar dias</button>

Esta função tem duas partes. A primeira cria uma array com 12 meses, cada elemento da array com os dias desse mês.
Para saber quantos dias cada mês tem usei var diasNoMes = new Date(ano, x + 1, 0).getDate(); e depois usei esse valor para fazer um loop interno que insere cada dia na array dos dias.
A segunda parte é para mostrar no HTML. No fundo é a mesma coisa, 2 loops para iterar os dias todos.
Deixo a parte de usar a array que a primeira parte cria para você.
Comment: Estou tentar usar a sua funçao, dos dias dos meses. Quero mostar numa tabela todos os meses com os seus dias. http://jsfiddle.net/h4Lc723t/
Comment: @akm http://jsfiddle.net/h4Lc723t/1/ - faltava só no jsFiddle mudar para `no-wrap` no menu.
Comment: Certo, mas os meses aparecem todos ate ao dia 31.
Comment: @akm não vejo o meu código no seu jsfiddle.
Comment: http://jsfiddle.net/h4Lc723t/2/ adicionei o ciclo for dos dias dos meses


How do you integrate a wordpress blog into an existing website

Question: So I have a client that has a website customized in PHP that does not use an actual Content Management System. The website presently has a Blog and News section, also coded in PHP without a CMS.
My client now wants to have only the Blog and News Sections created with Wordpress, but seamlessly go with the existing site. The benefits in their mind is that they only need to hire bloggers and give them access to the Wordpress aspect of the site, while leaving the other parts of the site administered by his staff.
I think that this will require obviously a Wordpress installation, and perhaps some shared database resources.
If anyone has ever done or seen this, please let me know.
Comment: In the easiest scenario Wordpress can live in a separate  web-accessible folder on the site. Say '/blog'.  It sounds like they just want clear separation, so this approach may be possible.  It's a bit more difficult if design elements (common headers/footers, etc) need to be shared between the two systems.
Comment: What if they want a /news too? Can I use the same WP installation to pull this off?
Comment: Sure, you might use some symlinks to pull it off in the directory structure.  There are a lot of ways. If you want to get tricky you can setup an RSS feed on Wordpress and have portions of the existing site consume it for fuller integration.  There are probably plugins that allow you to build widgets in a similar fashion.  It's all possible, just may be more effort than it's worth.
Answer: Check this out from wordpress codex itself -
http://codex.wordpress.org/Integrating_WordPress_with_Your_Website
The easiest way to have both news & blog would be to " create 2 different categories within the blog" and display them differently using "The Loop"
http://codex.wordpress.org/The_Loop#Style_Posts_From_Some_Category_Differently
Comment: Could you please add a small description to accompany the links you provide?


Manage multiple app config files during development

Question: I'm building an application that is used by several different customers.  Each customer has a fair amount of custom business logic, which I have cleverly refactored out into an assembly that gets loaded at runtime.  The name of that assembly, along with a number of other customer-specific settings, are stored in the application's configuration file.
Right now, here's what I have to do in order to debug the application for customer foo:

Go to the filesystem in my project directory and delete app.config
Copy app.config.foo to app.config.foo - Copy.
Rename app.config.foo - Copy as app.config.
Tell Windows that yes, I want to change the file's extension.
Switch back to Visual Studio.
Open the Settings.settings item in my project.
Click "Yes" 13 or 14 times as VS asks me if I want to use the new settings that have been changed in app.config.
Close Settings.settings.

Okay!  Now I'm ready to debug!
It seems to me that the rigamarole of opening Settings.settings is, or ought to be, unnecessary:  I don't need the default values in Settings.cs to be regenerated, because I don't use them.  But it's the only way I know of to make VS aware of the fact that the app.config file has changed, so that the build will copy it to the output directory.
There's got to be an easier way of doing this.  What is it?
Answer: You can also let Visual Studio automate Robert`s approach by:

Define a Build Configuration for each client
In the post build event, simply xcopy app.config.xxx to your bin folder. Where XXX is the name of a Build Config accessible in VS. Something like: xcopy app.config.$(ConfigurationName)  $(OutDir)/app.config

VS will drop a distinct build for your clients in separate folders, aolong with the proper config file.
bin/Client1/
bin/Client2/
Answer: You can refer this post for some good practices : Managing Multiple Configuration File Environments with Pre-Build Events
Comment: This works, although it's a lengthy work around for functionality that should really be in the IDE.
Comment: It also requires me to create two configurations (debug and release) for each customer.  That smells like the wrong answer to me.
Comment: This works like a charm. Each location (QA/DEV1/Production) has their own config file. ZERO HASSLE. This just works. you are a genius!! I did this for app.config that works with a WCF service per client per location. Works like a charm. you are my hero!
Answer: Thinking about the mess of managing multiple configuration files I made this tool: http://envride.codeplex.com/
Its purpose its exactly to make it easier to manage multiple configuration files in an automated way. I would be very pleased if you would take a look at it.
Answer: A couple of people suggested using multiple VS configurations, which I think would have worked, except that it would require me to rebuild the solution every time I switched between configurations.
What I did instead seemed a little stupid while I was doing it, but I've been using it for nearly a year now and it works extremely smoothly.  In my project directly, I create a separate app.config.XXX file for each customer.  The actual app.config file is used solely to generate Settings.cs - it has all of the correct setting names and their default values.  It doesn't get copied to the build directories, ever.
Then I wrote a little program that lets me select a customer, and that simply goes through the directories for each project and, if I selected customer XXX, copies app.config.XXX to bin\debug\myprogram.exe.config and bin\release\myprogram.exe.config.  As long as this program knows where the root of the solution is (I have to be a little careful whenever I branch the code), it works like a charm.
Answer: This thread is too old to represent current tools in VS.

You can use an addon that acts similar to web.debug.config but for app.config.

https://marketplace.visualstudio.com/items?itemName=GolanAvraham.ConfigurationTransform

And for the same app.config transformations without addon.

https://www.linkedin.com/pulse/multi-appconfig-visual-studio-2017-benjamin-davis/
Answer: You may opt to define multiple Visual Studio solution configurations, one for each customer, and have customised MSBuild targets for your Windows app project.
I have documented the steps of how I handled this here. Multiple app.config files for deploying to different environments
Answer: After a little digging and work around I got my Test project working with multiple configurations,

In the Configuration Manager, create the configurations you need
Copy paste your app.config and add the name of the configuration, in my case is AHI, FIV, MGC, so my config files look like: App.AHI.config, App.MGC.config, App.FIV.Config. You can name it how ever you wanted, but keep the same convention
Add a Post-Build event. In my case it would look like:  xcopy $(ProjectDir)app.$(ConfigurationName).config $(TargetDir)$(TargetName).dll.config /y

here is my post, so you can read it with more details
Running a Test Project with Multiple Configurations


Learning to free-form harmonise when singing

Question: Recently I've started trying to harmonise when singing in church, as the only place I regularly sing with a large group of people. I'm finding it really hard and I wondered if anyone can suggest how one might approach learning how to do this.
It sounds beautiful (to me) when you here people throwing harmonies in ad-hoc and it's specifically this kind of improvisational harmonising I'm interested in, not preparing/learning harmonies.
Congregational songs typically are pretty narrow and easy in range which means there is often scope to go down as well as up from the melody.
Comment: You might also find some useful answers here (http://music.stackexchange.com/q/26936/16897)
Comment: Please mark a solution or specify your problem.
Comment: I think I need to try these approaches out before saying which one is 'correct'. I'll issue up-votes now though
Answer: As a guitarist, you will be aware that at any given moment, a chord fits under what is being sung. The melody line may contain several notes, but for starters, if you sing one of the notes from that chord, it'll fit the melody line, just as the rest of the notes from that chord will. Basically, there will be a root, 3 and 5 in that chord, so initially, get used to just singing each in turn against the melody line. It will sound a little uninspiring, but it's a good start to harmony.
Often, the 3rd above is easiest to find, although it may be too high to reach. Listen to a lot of two part harmony songs - the Everly Bros. comes to mind, this will give you ideas as to how it works. Try singing along to each voice, to start to understand how sometimes the voices are moving in a parallel way, and sometimes they move contrapuntally. This should be a good intro. for you. Then record yourself singing simple melodies and sing harmonies to the playback.
Answer: As mentioned by others, it really depends on the music you're singing.  I have sung a lot of music in church and worked on this, and I've found that it's easiest with old hymns like you would find in a Baptist or Methodist hymnal.  It's definitely harder with some contemporary songs.
The harmonizations in hymnals are usually pretty simple and easy to pick up on, so one thing you could do to practice is make recordings of yourself singing the melody of a song like "Rock of Ages" (usually the top line in the treble clef in the hymnal) and then try singing some of the other lines while listening to the recording.  Or, if you don't have recording equipment easily available, play one line on piano or guitar and sing the other one.
Yes, this just teaches you the "prepared" harmony, but I have found that it exercises my "harmony muscles" so that I'm able to predict what will sound good and sing it without a book.  Once you've learned a few harmony lines like this, I would be willing to bet you could even improvise on the learned lines in places, and from there it's a much shorter step to what you really want to do.
Answer: I can do this. I started it about almost 13 years ago. It takes about 3 to 4 years until you can do it. Then you will be a rookie. To be really good at it takes approximately 6 to 8 years. Of course it depends on how often you sing.
There are songs, that are easy to sing to (Taize songs, balad style modern worship songs) and some that are less easy (hillsong).
If you sing below or above is in my opinion not much difference. If you can do one, you can do the other.
You shouldnt think too much. You should rather feel the music.
If you sing a new song, it takes about 3 strophes to find your voice. After that you normally change it not so much any more.
It is very important (!) that you have people right around you, who sing stable and correct. If you get better, this gets less important, but you enjoy it every time.
Everything I mentioned works for me. I can not guaranty, that this applies also for you.


INT 13h - Extended Read - DAPS fault

Question: Dear Stackoverflowers,
I wrote some assembly code which is ultimatly supposed to read the root directory. The problem however is that the Extended Read function doesn't place the readed data on the correct location. Or there is something wrong with my segment and offsets.
The Result I get out of this code is: A| |, Which means the Print Function found a 0, while expecting some random values of the first sector.
I really don't know what I've done wrong anymore
BIOS_ReadFile.inc
<code>;*************************************************
;   Name: BIOS_ReadFile.inc
;   Description: Reads File from the FAT32 System
;*************************************************
[bits 16]

%ifndef BIOS_READFILE.INC
%define BIOS_READFILE.INC

%include "Constants.inc"

;-----------------------------------------------------------------
; BIOS_ReadSectors function
;-----------------------------------------------------------------
ReadStatus: db UNKNOWN              ; 0 - Not Supported, 1 - Supported,     255 - Not known at given time

BIOS_ReadSectors:
mov si, DAPS                    ; Load DAPS Struct to DS:SI
mov ah, 0x42                    ; Read Functions
int 0x13                        ; Call the interrupt
jc .Failure                     ; If the read fails.
mov byte [ReadStatus], TRUE     ; Set the ReadStatus to True
ret                             ; Return

.Failure:
mov byte [ReadStatus], FALSE    ; Set the ReadStatus to False

mov ah, 0x0E                ; Print Letter B, Gives Indication of Failure
mov bh, 0x00
mov bl, 0x07
mov al, 'B'
int 0x10

ret
; Return

;-----------------------------------------------------------------
; BIOS_ReadFile function
;-----------------------------------------------------------------
FirstDataSector:     dw 0x0
RootDirectorySector: dw 0x0

BIOS_ReadFile:
; Calculating the First Data Sector
xor ax, ax
mov byte al, [Bios_Parameter_Block.FATS]
mul word [Extended_Bios_Parameter_Block.LargeSectorsPerFAT]
add word ax, [Bios_Parameter_Block.ReservedSectors]
mov word [FirstDataSector], ax

; Calculating the Root Directory Sector
mov word ax, [Extended_Bios_Parameter_Block.RootDirectory]
sub word ax, 2
mul byte [Bios_Parameter_Block.SectorsPerCluster]
add word ax, [FirstDataSector]
mov word [RootDirectorySector], ax

; Load Directory
;mov word [DAPS.SectorsToRead], 1

;mov word ax, [RootDirectorySector]
;mov word [DAPS.SectorStart], ax

call BIOS_ReadSectors

mov ah, 0x0E                ; Print Letter A, Gives Indication of Failure
mov bh, 0x00
mov bl, 0x07
mov al, 'A'
int 0x10

ret

;-----------------------------------------------------------------
; Memory Data Structures and Other Variables
;-----------------------------------------------------------------
; Disk Address Packet Structure (Used For Loading Rest of OS)
DAPS:            db 0x10               ; Size of Structure (16 bytes)
                 db 0                  ; Always 0
.SectorsToRead   dw 1                  ; Number of Sectors to Read (1x512)
.Offset          dw 0x7E00             ; Offset to load to.
.Segment         dw 0x0000             ; Segment to load to.
.SectorStart     dq 0                  ; Read from Second Block

;----------------------------------------------------------------------------------------------------

%endif
</code>
Bootloader.asm
<code>[bits 16]
[org 0x0]

jmp Start

%include "BIOS_Parameter_Block.inc"
%include "BIOS_Extensions.inc"
%include "BIOS_ReadFile.inc"
%include "Print.inc"

; Prepare stack segment
;-----------------------------------------------------------------
Start:
cli
mov ax, 0x07C0
mov ds, ax                  ; Load segments with 0
mov fs, ax
mov es, ax
mov gs, ax

mov     ax, 0x0000              ; set the stack
mov     ss, ax
mov     sp, 0xFFFF
mov     bp, 0xFFFF
sti

; Check support for extensions
;-----------------------------------------------------------------
call CheckExtensions
cmp byte [ExtensionsSupported], FALSE
jz short unsupported

; Read from the device.
;-----------------------------------------------------------------
call BIOS_ReadFile

mov ah, 0x0E                ; Print Letter B, Gives Indication of Failure
mov bh, 0x00
mov bl, 0x07
mov al, '|'
int 0x10

mov si, 0x200
call PrintString

mov ah, 0x0E                ; Print Letter B, Gives Indication of Failure
mov bh, 0x00
mov bl, 0x07
mov al, '|'
int 0x10

cli
hlt

jmp 0x0:0x7E00                  ; Jump to main

; Errors
;-----------------------------------------------------------------
unsupported:
mov ah, 0x0E                ; Print Letter F, Gives Indication of Failure
mov bh, 0x00
mov bl, 0x07
mov al, 'F'
int 0x10

clc
hlt

; Fill Out Rest of Bootloader
;-----------------------------------------------------------------
times 510-($-$$) db 0

db 0x55, 0xAA               ; Add Boot Record Signature
</code>
Print.inc
<code>;*************************************************
;   Name: Print.inc
;   Description: Printing on console using INT 10h
;   Function: PrintString(DS::SI nullTerminatedString)
;*************************************************
[bits 16]

%ifndef PRINT.INC
%define PRINT.INC

;---------------------------------------------------------------------------------
PrintString:
lodsb               ; Load next byte from DI::SI to AL and increment SI by one
or  al, al          ; Null-Terminator check
jz  .Done           ; If found jump to end
mov ah, 0Eh         ; Move Function number in AH
int 10h             ; Else print character
jmp PrintString     ; Repeat until null terminator found

.Done:
mov ah, 0x0E                ; Print Letter B, Gives Indication of Failure
mov bh, 0x00
mov bl, 0x07
int 0x10

ret                 ; Return
;---------------------------------------------------------------------------------
</code>
%endif
Comment: The segment and offset in `DAPS` don't match the segment and offset in the rest of your bootsector. Refer to the same memory, so I don't think that's your problem (you get back to segment 0 with the final jump, anyway) - but that's all that jumps out at me...
Comment: Eventually it turned out I had to put "mov dl, 0x80" before the read function
Answer: Eventually it turned out I had to put "mov dl, 0x80" before the read function.
Still I don't really know why since at the start of the booting process the DL should have the correct drive number according to most specifications.
Comment: `dl` is indeed set to the correct value when bootloader starts. However, before `int 0x13` you are using `mul` instruction which stores result in `dx:ax` overwriting the value BIOS put there.

INT 13h - Extended Read - DAPS fault


Remove specific row in r in a dataframe

Question: So, my dataframe named d and it has 5 rows and 7 columns.
One column is called DELTA_ICER
I need to remove the rows that have a DELTA_ICER <0
I tried this but doesn't work..
dom <-Delta_ICER<0
d <- d[!dom, ]

Some help please.
Thanks
Comment: d=d[d[,"DELTA_ICER"]>0,]
Answer: You need to refer to variables within dataframes using extraction notation (e.g., with $). You can also do your subsetting in one line.
Here's an example:
set.seed(1)
d <- data.frame(Delta_ICER = rnorm(10), X = rnorm(10))
d[d$Delta_ICER >= 0,]

Result:
  Delta_ICER           X
2  0.1836433  0.38984324
4  1.5952808 -2.21469989
5  0.3295078  1.12493092
7  0.4874291 -0.01619026
8  0.7383247  0.94383621
9  0.5757814  0.82122120

And the original dataframe:
> d
   Delta_ICER           X
1  -0.6264538  1.51178117
2   0.1836433  0.38984324
3  -0.8356286 -0.62124058
4   1.5952808 -2.21469989
5   0.3295078  1.12493092
6  -0.8204684 -0.04493361
7   0.4874291 -0.01619026
8   0.7383247  0.94383621
9   0.5757814  0.82122120
10 -0.3053884  0.59390132

Remove specific row in r in a dataframe


Aligning image on multiple H1 tag lines

Question: I have an image in an h1 tag which is vertically aligned in the middle. It works well with a short sentence. However, when the sentence is on multiple lines, I'd like the image to be aligned in the middle of the entire sentence rather than just the first line. Is there anyway to do this without creating two columns?

Hello, how are you?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Answer: You can achieve this with flex
https://jsfiddle.net/yc9umsop/
h1 {
  display: flex;
  align-items: center;
}

HTML

   Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

Note I wrapped your text with a span
Learn how to use flex here https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Answer: Well if you absolutely don't want to create multiple columns then you could go with this pure css approach :
h1{
  position:relative;
  padding-left:80px;
}

h1 img{
  position:absolute;
  left:5px;
  top:50%;
  margin-top:-17.5px; /* IMAGE HEIGHT DIVIDED BY 2 */
}

https://jsfiddle.net/cndj27q3/4/
My suggestion would be to go with an additional html element instead using a multi column approach if at all possible in your scenario.
Hope that helps.

Aligning image on multiple H1 tag lines


In rails, how to select one specific column's data from a table? (there is only 1 row so I want only a specific result but not an array)

Question: The table's name is Plan and it has only one row, since users are not allowed to create new data or deleted existed data. They can only edit it.
For the table, the structure is like this:
<Plan id: 1, breakfast: 100, lunch: 240, dinner: 200, ...

which means it has three different columns: breakfast, lunch, and dinner.
In a controller file, I want to access one specific column's data which user inputs, for example, the breakfast. How can I do that? Since I am quite new to rails and assume that it would be similar to:
Plan.select("breakfast")

However, I do not want the result to be an array! I want just a number so that I could use it directly in my code:
if xxxx > 90
...
end

Thank you very much!
Comment: Does this data in the table ever change? If it does not, and since you are guaranteed to only ever have a single element in the DB, it would be better to not have the model tied to the database. Just define your model and have helper methods that return the various pieces of data that you want.
Comment: Yes sir, the data will be changed frequently by users, your suggestion is quite useful to me and I will keep an eye on it while studying rails :) Thank you very much.
Answer: Since there is guaranteed to be only one row, you can grab it directly via .first or .last. While you may wish to limit the selected column only to the desired breakfast with the .select() method, it probably isn't necessary and you can just retrieve breakfast from the resultant object:
Plan.last.breakfast
=> 100
# Generates this query:
Plan Load (0.4ms)  SELECT "plans".* FROM "plans" ORDER BY "plans"."id" DESC LIMIT 1

Using .select() to cause the SQL query to retrieve only the breakfast column is possible, but won't give you that much benefit other than a very tiny memory increase.
Plan.select(:breakfast).last.breakfast
=> 100
# Generates this query:
Plan Load (0.4ms)  SELECT breakfast FROM "plans" ORDER BY "plans"."id" DESC LIMIT 1

Of course, you can store it to a variable, or use it right in your expression:
if Plan.last.breakfast > 90
  # whatever
end


Real benefits of serial console servers (with modern server hardware)?

Question: I'm working in a new environment that makes heavy use of serial console servers for server management. They are augmented with switched PDUs for power management. They are not using the DRAC capabilities of the existing servers.
I'm adding new HP ProLiant equipment to the site, and am curious as to the benefits of serial consoles versus the ILO/ILOM/DRAC technologies available on modern servers. This is a Linux environment that will grow to include more Windows systems. I'll be running a mixture of blades and DL380's. Assume fully-licensed/enabled versions of ILO/DRAC on any future equipment.
I've configured serial consoles in the past, and have found them particularly useful for network gear. I'm confused as to their advantage or usefulness in an environment where the servers will have onboard lights-out management.
Comment: I'd like to point out that most if not all management units out there allow access to the serial port via the IMU's command line interface accessible via ssh or telnet. Often if there's an "advanced" license required for a graphics console via the IMU, it's not necessary for serial port access this way. Thus, what you usually want to be asking is, "why do I want to use a separate box connected to the physical serial port connector rather than using the IMU's access to the serial port?
Answer:
I've configured serial consoles in the past, and have found them particularly useful for network gear.

In the case of network gear. sometimes a serial console is the only way to remotely manage the appliance.

am curious as to the benefits of serial consoles versus the ILO/ILOM/DRAC technologies available on modern servers.

I'm having this exact debate with my coworkers. I'm leaning towards the iLO/DRAC technologies, while others want to stick with the older Serial Consoles.
Here are some advantages of Serial Consoles vs the newer iLO/DRAC/IPMI technologies.

It's true that iLO, DRAC and some IPMI implementations support KVM-over-LAN. However in every case that I've seen, the KVM-over-lan requires that download a Java software package through my browser, which then opens up a VNC-like client to the remote server. This software tends to be buggy, slow and is unreliable. Some of this software ignores my browser and system network settings (like the PROXY setting).
a. Some vendors may use one of several different IPMI implementations for different models of hardware, and each has it's own funky quirks (I'm talking about YOU, Supermicro). So you might have 100 servers all from the same vendor, but there are 3-4 different IPMI/BMC chips.
Some people like the simplicity of Serial Consoles. Learning how to configure the serial consoles can be a steep learning curve, but once you get them working they are generally pretty solid and consistant.
If your organization already has an existing serial console infrastructure (e.g. with all the cables, DB9 adapters with the correct pinouts, etc.) then using serial consoles on new hardware may be simpler then configuring the iLO/DRAC on new servers.
FreeBSD and Linux can only have one primary console, and will only print certain messages (Like the FSCK prompt) to the primary console. You must chose either the Serial Console or on the VGA console (e.g. the attached keyboard/video/mouse, and by extension the KVM-over-LAN); not both.
IPMI exposes some powerful information to the network, so placing IPMI on your network should be done carefully. Many shops put IPMI on a separate, non-routable, secure network. A VPN or SSH tunnel can be used to securely access the IPMI services, but just look at some of the wonky solutions that some of us need to do just to access the IPMI console.
Comment: One additional benefit:  consistency of access.  Having worked in an environment where we had ILO, Drac, ILOM, and IPMI, plus real serial console access servers, there was something to be said about being able to use one tool to access every system the same way, every time, no matter what the system actually was.
Answer: I'm contracting for a company right now that uses DRAC in conjunction with serial consoles.
The company in question did not expend the money to get Enterprise-level DRAC hardware with remote console, but iDRAC6 Express still offers some benefits, the strongest being the ability to remotely monitor the status of the hardware and to perform firmware installation.
As I understand it, the iDRAC Express uses a shared ethernet port (eth0 on the motherboard). If you're in the situation where you need this for production use, you have no chance of moving your DRAC access to an Out of Band (OOB) network, which is best-practice. With the aid of a console server, you can at least have access in an OOB network, even though there are still security implications from having that shared port on the common network.
Comment: All other things being equal, probably so. Aside from the benefits I mentioned, the ability to remotely powercycle is great. Remote KVM is very handy as well, plus a lot of the DRACs support remote virtual media presentation (presenting the remote server an ISO as a CD-ROM). You can't get that with a serial connection.
Comment: Most of these cards also give good status reports of the server they live in, which is also quite nice. I even scripted up something to SSH into all of our Dell chassis management controllers and dump the status (to find dead drives in RAID arrays, bad PS, etc), until we get a real central management tool.
Comment: I usually purchase hardware with full ILO or DRAC licenses, so I can get the necessary separation between networks by leveraging the dedicated management NIC. All else equal, would you choose a dedicated DRAC NIC over a serial console?
Comment: mfinni: Have you looked into OpenManage?
Comment: @MattSimmons - Dell Management Console looks like an immature ungainly beast right now, and overlaps too much with SCOM and the Dell VMware plugin, both of which are in our near future. I'm investigating OME as a decent stopgap for firmware patching and light management.
Answer: Belt and suspenders? The iLo/DRAC/SupII card (as useful as they are!) is still another bloody computing device with its own firmware and bugs; it can crap out on you. Serial access, especially for console-oriented OSes like U*x, can still be useful especially in an emergency.
Now for Windows though, it's almost useless for most sysadmin purposes.
Comment: And Core is *STILL* a GUI - it's a graphical desktop with nothing but two CMD windows. It's not like you can connect to Core over serial and do shit - so my point stands, AFAIK.
Comment: Although according to one of my Windows Consultant friends, it is possible to run Windows without a GUI interface and have only a command line interface.  I haven't seen this in person so it's just hearsay to me, but I think it if wasn't for the the ubiquity of Linux this would have never happened.
Comment: It's called Windows Server Core. It probably is a response to Linux; but because so few Windows components can be configured using plain text files, it's a PITA to get a lot of things done. It encourages remote config and management (generally a good thing) but it reduces the number of things you can do easily at the console (not a great thing, to my mind.) It reminds me of old Netware, in some ways.
Comment: Seriously?  Wow, that's a fail...
Answer: For me the primary benefit would be capturing of oops/crash logs. With the likes of ILO you are loosing whatever rolls out of the screen. Serial console allows you to collect the whole thing and record it without using a camera.
Comment: The ILO can perform console replay, I believe. Or if it's an ugly crash that doesn't trigger the watchdog timer reboot, the remnants are usually displayed on-screen when you connect.
Comment: Okay, that's one situation. Are you suggesting serial consoles used in conjunction with ILO technology? I guess I'm not used to crashes that leave traces that can only be retrieved by console output (versus an IML log, system logs, etc.)
Comment: You are right, ewwhite, but I think that you have to specifically configure it that way.
Comment: @ewwhite That's my point "the remnants" :). And I did not know about the replay functionality, thanks for the information.
Comment: I am not used to systems crashing at all, but I like to be prepared. I like bell & suspenders approach. Of course, if a single solution works and you are comfortable with it, and there are so many systems, that shaving 20 minutes of configuration off one is a tangible benefit, then it can be reasonable to choose one. Otherwise I would go for both. For some people/uses one approach/tool will be more convenient than the other.
Answer: I think your need to evaluate the problme you're trying to solve with eaither a serial console, KVM over IP, or the iLO.

Serial Console: basically good if you need out of band access to the iLO's command line.  In my six years as a sys engineer, I've never needed it.  To a degree this is even less useful in a virtual environment.  Since you can SSH into the iLO device, this is only useful in a situation where you need access to the iLO and the network connection might be down, or the iLO is not responding.
KVM over IP: basically good if you don't have the iLO advanced, or if you don't want to proxy through a KVMoIP to access your servers.  I like the idea of having one place where i can go to have console access to all my servers, as opposed to needing to make individual connections to each server.  This solution is great when you have a ton of physical servers.  Another bonus is you don't have to pay for an advanced iLO everytime you get a new server.
iLO Avanced: Provides all the features you need to access your server remotely.  The real disadvantage is simply the lack of central managment (at least by its self).  You of course get access to things like failed HW as well.

With that said, all of these can be combined into a massive solution, or you can pick and choose.  Most modern KVMoIP or Serial console are actually combined as one unit now, so you could in theory have a KVMoIP and Serial console hooked into the same switch.  It will eat two console ports though (one for the serial port and the other for the KVM).  IMHO, tapping in to the serial port isn't a huge win.  You'd be better off with eaither the iLO advanced, KVMoIP or both
Comment: Okay, so use the serial functionality for your network devices and the IP-KVM functionality for the servers? Is there any need to still use serial for the server side of things?
Comment: I'm sorry, are you saying that the serial port on your iLO is plugged into the serial console?  I was sort of assuming you had a slightly newer serial console / KVM.  Meaning avocent for example, makes a serial console and KVM in the same switch.
Comment: The company is using serial-only console devices that use the serial ports on the server. There's no GUI or ILO functionality.
Comment: For HP users: the serial console can be used after boot even if you don't have iLO Advanced, which may be useful in certain situations. Of course, you have to set it up in advance.
Answer: One thing not mentioned by anyone so far but rather implied is the ability to directly SSH from one system into the console of a host without the need for a special application (often written in Java) to show the remote console.  Thus it is easier to put a system in a colo behind an ssh jump box and ssh into the system via the serial console.  This is done because often various TCP ports on the serial console server can be associated with physical serial ports on the box.  In addition some serial console servers allow for you to install SSH keys and only allow connections using those pre-installed ssh keys.  This is most useful when you need to place an ssh console server on the Internet directly for situations where you need an external (to your network) way to gain access to edge routers and other equipment/systems.
SSH-Serial console servers are not the final word in systems administration just as iDRAC and other similar tools are not the final word, rather they are tools which address a specific need and often can compliment each other.
Comment: All ILO systems that I'm aware of provide access to the serial port over the network; you can simply ssh into a system on the management network and from there ssh/telnet/whatever in to the management unit and type something along the lines of "console 1" to get access to the serial port.


How to double ssh in bash using a private key and different users

Question: In order for me to ssh to B, I need to go through A.
<code>Host A
  HostName x.x.x.x
  User user
  IdentityFile ~/pathto/file.pem

Host B
  ProxyCommand ssh A -A nc x.x.x.x 22
</code>
I just tried ProxyCommand and nc based from searches I made but nc fails. The reason for that one is in order to ssh to B I need to set the user which is different from the user in A. nc only accepts host and port. Is there a way to do it using nc or i need to use another command? If its another command can you tell me what command i need to use?
Comment: Using `nc` for this has not been necessary for many years. You can just write `ProxyCommand -W %h:%p A`. And if you have a recent `ssh` version it will be even simpler to just write `ProxyJump A`. Moreover using `-A` like that is a security risk.
Answer: Sorry it was a stupid mistake, I did not add the User field in the Host B. I thought i need to specify the User in the command not in the Host.


Excluir elemento de um array de objeto dinâmico

Question: Eu preciso excluir uma coluna de um array de objeto dinâmico.
Exemplo:
export interface ObjetoTeste {
  primeiraColuna: string;
  segundaColuna: string;
}

let teste: Array<ObjetoTeste> = [
  {
    primeiraColuna: 'teste1',
    segundaColuna: 'teste1'
  },
  {
    primeiraColuna: 'teste2',
    segundaColuna: 'teste2'
  }
  {
    primeiraColuna: 'teste2',
    segundaColuna: 'teste2'
  }
]

//O header definirá qual coluna será excluída com base no valor XXX
var header: ObjetoTeste = {
  primeiraColuna: 'Juninho',
  segundaColuna: 'XXX',
}

// Com base no header, não terá mais a segundaColuna
var semSegundaColuna: Array<ObjetoTeste> = [
  {
    primeiraColuna: 'teste1',
  },
  {
    primeiraColuna: 'teste2',
  }
  {
    primeiraColuna: 'teste2',
  }
];

O header é o objeto que define quem será excluído com base no valor XXX recebido na coluna.
Outro Exemplo:
export interface ObjetoTeste2 {
   primeiraColuna: string;
   segundaColuna: string;
   terceiraColuna: string;
}

let header: ObjetoTeste2 = {
  primeiraColuna: 'XXX',
  segundaColuna: 'Teste',
  terceiraColuna: 'XXX'
}

//Primeiro irá receber os valores inteiros para então ser tratatos
let teste2: Array<ObjetoTeste2> = [
  {
    primeiraColuna: 'teste1',
    segundaColuna: 'teste1',
    terceiraColuna: 'teste1'
  },
  {
    primeiraColuna: 'teste2',
    segundaColuna: 'teste2',
    terceiraColuna: 'teste2'
  }
]

//resultado do tratamento do objeto com base nos valores do header
let resultado: Array<ObjetoTeste2> = [
      {
        segundaColuna: 'teste1',
      },
      {
        segundaColuna: 'teste2',
      }
    ];

Comment: *"Com base no header, não terá mais a segundaColuna"* e como o header definiu que não deve ter a segunda coluna? não tem nenhum valor que diga pra remover, precisa esclarecer o critério
Answer: não sei qual é o contexto do sua necessidade de remover as colunas pelo valor "XXX", isso só valeria a pena se esse valor "XXX" fosse algum retorno de uma API, mas vamos separar o seu problema em dois.

primeiro recuperar a lista de colunas a remover.
remover a coluna da lista de objeto

Vou apresentar duas soluções um com delete e outro sem, o delete tem um problema que ele acaba mutando o objeto e por muitas vezes isso pode gerar problemas, o ideal seria criar um método para clonar cada objeto da lista, mas não vou incluir nessa solução já que não é pertinente a pergunta.
Solução sem delete:
Primeiro vamos recuperar a lista de colunas a remover, assim ficará mais claro para futuras manutenções:

/*
 * Primeiro vamos recuperar a lista de colunas a remover,
 * assim ficará mais claro para futuras manutenções:
 */

var header = {
  primeiraColuna: 'XXX',
  segundaColuna: 'Teste',
  terceiraColuna: 'XXX'
}

var colunasParaRemover = Object.entries(header).filter(item => item[1] === "XXX").map(n => n[0]);
console.log(colunasParaRemover);

/*
 * Segundo vamos criar uma função para fazer a remoção,
 * separando a lógica você obtém algo de fácil manutenção e funções
 * mais genéricas para utilização no sistema, primeiro vamos criar
 * uma função que  retorna a lista com as colunas selecionadas
 */

var teste2 = [
  {
    primeiraColuna: 'teste1',
    segundaColuna: 'teste1',
    terceiraColuna: 'teste1'
  },
  {
    primeiraColuna: 'teste2',
    segundaColuna: 'teste2',
    terceiraColuna: 'teste2'
  }
]

var removeColunadaLista = (listaObjetos, colunasRemover) => {
  colunas = Object.keys(listaObjetos[0]).filter(n => ! colunasRemover.includes(n)); // invetemos montamos uma lista somente das Keys que queremos;
    return listaObjetos.map(objeto => Object.fromEntries(colunas.map(k => [k, objeto[k]]))); // retorna a lista sem a coluna desejada
}

console.log(teste2);
console.log(removeColunadaLista(teste2, colunasParaRemover)); // retorna uma lista de objetos formatado
console.log(teste2); // não altera o a lista principal.

Solução Com Delete:
Cuidado com essa solução pois ele altera o Objeto em si, lembrando que o array guarda a referência do objeto

var o = {opa: "x", neh: "y", vixi: "z"};
var o2 = {opa: "a", neh: "b", vixi: "c"};
var os = [o, o2];
var dc = ["opa", "vixi"];

os.forEach(n => dc.forEach(c => delete n[c]));

console.log(o); // {neh: "y"}
console.log(o2); // {neh: "b"}
console.log(os); // [{neh: "y"},{neh: "b"} ];
Comment: O problema de utilizar `delete` é que, além de modificar o objeto (o que pode ser um problema em algumas situações), cria buracos no array, o que pode ser de fato um problema na ampla maioria dos casos. Teste no console: `let arr = [1, 2, 3]; delete arr[1]; arr;`.
Answer: Consegui resolver dessa maneira, onde teste é a variável do array e header o objeto de filtro:
let teste3 = teste.map((data) => {
    Object.keys(header).forEach((headerData) => {
      if (header[headerData] == "XXX") {
        delete data[headerData];
      }
    });
});


Averages of averages (of averages, of averages...)

Question: Consider the following cell biology experiment.  We are comparing $T$ different treatments of cultured cells.  Each treatment $t$ is replicated in several (microtiter) wells, indexed by the variable $w \in \{1, 2, \cdots, W\}$.  To measure the response to the treatment in well $w$, a total of $F_w$ non-overlapping micrographs, or fields, are recorded.  Then, for each field $f$ in well $w$, a total of $C_{wf}$ cells are identified computationally, whereby each cell $c$ (in well $w$, field $f$) is represented by a set of $P_{wfc}$ pixels.  Finally, associated with each pixel $p$ is a measurement $x_{wfcp}$ (derived from the intensities of various fluorescence signals recorded at that pixel).

The problem is to aggregate all the pixel measurements $x_{wfcp}$ to produce a "reasonable measure" $X_t$ of the effect of the treatment $t$ on the cells treated with it, as well as some measure of the "spread" of $X_t$.

The standard approach to such problems is to use the mean as "the measure" and the variance (or standard deviation) as "the spread".  In this case, however, there are multiple, non-equivalent ways in which means and variances could be computed.
Focusing for now on the means, at one extreme, one could simply add up the $x_{wfcp}$ over all the pixels (disregarding their distribution over cells, fields, and wells), and divide this sum by the total number of pixels $P$ (for treatment $t$):
$$
\frac{1}{P}\sum_{w=1}^W\sum_{f=1}^{F_w}\sum_{c=1}^{C_{wf}}\sum_{p=1}^{P_{wfc}} x_{wfcp}
$$
At the opposite extreme, we could average at each level: first compute the average $x_{wfc}$ of $x_{wfcp}$ for each cell, then compute average $x_{wf}$ of the $x_{wfc}$ for each field, and so on:
$$
\frac{1}{W}\sum_{w=1}^W
\left[\frac{1}{F_w} \sum_{f=1}^{F_w}
\left[\frac{1}{C_{wf}}\sum_{c=1}^{C_{wf}}
\left[\frac{1}{P_{wfc}} \sum_{p=1}^{P_{wfc}} x_{wfcp}\right]\right]\right]
$$
In general, these two expressions will not be equal.  Plus there are several variations in-between.  By my count, there are 8 ways of doing this (including the two above); I've listed all in their full glory at the end of this post.  For example, one could compute this (number 6 in the list below):
$$
\frac{1}{W}\sum_{w=1}^W
\left[\frac{1}{C_w} \sum_{f=1}^{F_w} \sum_{c=1}^{C_{wf}}
\left[\frac{1}{P_{wfc}} \sum_{p=1}^{P_{wfc}} x_{wfcp}\right]\right]
$$
...where $C_w = \sum_f \sum_c \; 1$ is the total number of cells (summed over all fields of) well $w$.  (The recipe encoded by this expression says: "compute the average value of $x_{wfcp}$ for each cell, namely $x_{wfc} = \left[\sum_p x_{wfcp}\right]/P_{wfcp}$; then, for each well $w$, compute the average of these $x_{wfc}$ averages over all the $C_w$ cells in well $w$—disregarding their distribution over fields—, namely $x_w = \left[ \sum_f \sum_c x_{wfc}\right]/C_w$; and, finally, average the $x_w$ over all $W$ wells, $\left[\sum_w x_w\right]/W$.")
Faced with all these different ways to "use averages" to measure the effect of treatment $t$, the immediate question is, of course, which one to choose?  A sharper version of the question would be: how can I determine under which scenarios a given variant would be appropriate/informative/useful?
And, more generally: are there any pitfalls in computing averages of averages (of averages... )?
Thanks!

(corrections welcome)
$$
\small
\begin{array}{lrl}
1. \;\; \frac{1}{P}\sum_{w=1}^W\sum_{f=1}^{F_w}\sum_{c=1}^{C_{wf}}\sum_{p=1}^{P_{wfc}} x_{wfcp} && && \\

2. \;\; \frac{1}{W}\sum_{w=1}^W
\left[\frac{1}{P_w} \sum_{f=1}^{F_w}
\sum_{c=1}^{C_{wf}}
\sum_{p=1}^{P_{wfc}} x_{wfcp}\right]
&& \mathrm{where} && P_w = \sum_{f=1}^{F_w}\sum_{c=1}^{C_{wf}}\sum_{p=1}^{P_{wfc}} \; 1 \\

3. \;\; \frac{1}{F}\sum_{w=1}^W
\sum_{f=1}^{F_w}
\left[\frac{1}{P_{wf}}\sum_{c=1}^{C_{wf}}
\sum_{p=1}^{P_{wfc}} x_{wfcp}\right]
&& \mathrm{where} &&
F = \sum_{w=1}^W \sum_{f=1}^{F_w} \; 1 \, , \,
P_{wf} = \sum_{c=1}^{C_{wf}}\sum_{p=1}^{P_{wfc}} \; 1 \\

4. \;\; \frac{1}{C}\sum_{w=1}^W
\sum_{f=1}^{F_w}
\sum_{c=1}^{C_{wf}}
\left[\frac{1}{P_{wfc}} \sum_{p=1}^{P_{wfc}} x_{wfcp}\right]
&& \mathrm{where} && C = \sum_{w=1}^W \sum_{f=1}^{F_w} \sum_{c=1}^{C_{wf}} \; 1 \\

5. \;\; \frac{1}{W}\sum_{w=1}^W
\left[\frac{1}{F_w} \sum_{f=1}^{F_w}
\left[\frac{1}{P_{wf}}\sum_{c=1}^{C_{wf}}\sum_{p=1}^{P_{wfc}} x_{wfcp}\right]\right]
&& && \\

6. \;\; \frac{1}{W}\sum_{w=1}^W
\left[\frac{1}{C_w} \sum_{f=1}^{F_w} \sum_{c=1}^{C_{wf}}
\left[\frac{1}{P_{wfc}} \sum_{p=1}^{P_{wfc}} x_{wfcp}
\right]\right]
&& \mathrm{where} && C_w = \sum_{f=1}^{F_w} \sum_{c=1}^{C_{wf}} \; 1 \\

7. \;\; \frac{1}{F}\sum_{w=1}^W \sum_{f=1}^{F_w}
\left[\frac{1}{C_{wf}}\sum_{c=1}^{C_{wf}}
\left[\frac{1}{P_{wfc}} \sum_{p=1}^{P_{wfc}} x_{wfcp}\right]\right] && && \\

8. \;\; \frac{1}{W}\sum_{w=1}^W
\left[\frac{1}{F_w} \sum_{f=1}^{F_w}
\left[\frac{1}{C_{wf}}\sum_{c=1}^{C_{wf}}
\left[\frac{1}{P_{wfc}} \sum_{p=1}^{P_{wfc}} x_{wfcp}\right]\right]\right]
&&  && \hspace{3in}

\end{array}
$$
Comment: You could do a nested anova to identify whether any of the treatment effects are significant. A good reference is _Biometry_ by Sokal and Rholf.
Comment: All of the equations at the bottom of the question are equal, because the arithmetic mean is a linear function. The fraction is scalar, so can be moved outside the sum in each case. The order of the sums is not important. All are equivalent to $$\frac{1}{WFCP}\sum^{W,F,C,P}_{w,f,c,p}x_{wfcp}$$.
Comment: @naught101: I completely disagree.  To begin with, the expression in your comment is not even consistent with the notation I've used in my question.
Comment: Have you tried calculating them? Note that there is one point I missed: you mention variance, and in that case (means of variance vs. variance of means) certainly is different, because variance isn't a linear operator (it has a sum of squares in it).
Answer: This is not a direct answer to your question ('Which type of averaging to choose'), but rather a recommendation to avoid calculating averages at all:
Your scenario seems to look like a case for hierarchical/ multilevel models (MLM), as data are perfectly nested. You have three levels of random effects: pixels (Level 1) nested in cells (L2), nested in fields (L3), nested in wells (L4). Treatments should be treated as fixed effects.
You are only interested in the effect of treatment; the MLM method takes care of the different variances of each level and gives you also an estimate of how much variance is explained by which level. So you do not 'lose' any variance by treating an averaged value as 'the measurement', but you estimate the model on the level of raw data.
This method, however, calls for a sufficient number of groups for each random effect (i.e., enough pixels, enough cells, enough fields, enough wells). As you are not interested in cross level interactions, general recommendations say something like 10 to 30 units minimum (of course, depending on the specific scenario, etc.; see, e.g., here).
Comment: The first link you provided (hierarchical/multilevel models) seems broken now.


Is there a way to enumerate Public Folder permissions on Exchange 2003?

Question: My organisation is about to start the process of migrating from Exchange 2003 to 2010. However we have a large number of public folders and in order to maintain functionality for users need to somehow enumerate the permissions of each public folder so that we can identify public folders that can be migrated in conjunction with their associated users.
So does anyone know of some way to get a list of public folders and their associated permissions from exchange 2003?
Is there a way to get the info using the WMI Public Folders class?
I've already had a quick look at PFDAVAdmin tool and will be testing this as soon as possible but if someone has experience with it can you tell me if it will do what I need?
Thanks.
Answer: Yes, you want to install PFDAVDadmin from Microsoft.  It allows all kinds of access/insight into the murky depths of Exchange.  Among other things, it will allow you to export permissions of your public folders (but it does so much more...)
It's ugly and a little obtuse.  Read the instructions (link to the FM on the linked download page.)
Comment: Thanks, I've had a chance to try it out and it works a treat!


Adicionar admob após uma ListView em um RelativeLayout

Question: Boa Noite!
Estou tentando adicionar um admob ao final de uma ListView em um RelativeLayout e o banner não aparece de jeito nenhum! Já tentei mexer de diversas maneiras no layout para ver se a ListView não estava cobrindo o admob, mas não resolveu em nada. Alguém poderia me ajudar?
Segue o xml abaixo:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="16dp"
    android:background="@drawable/background"
    xmlns:ads="http://schemas.android.com/apk/res-auto">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Suas Faltas"
        android:textColor="@color/white"
        android:textStyle="bold"
        android:textSize="25sp"
        android:layout_alignParentTop="true"
        android:id="@+id/textView2" />

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true"
        android:layout_marginTop="15dp" />

    <TextView android:id="@+id/vazio"
        android:text="Nenhuma matéria inserida"
        android:textColor="@color/white"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:ems="10"
        android:layout_width="244dp"
        android:layout_height="42dp"/>

</RelativeLayout>

Answer: Tente usar um LinearLayout, veja se está solução te ajuda.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:orientation="vertical"
    android:paddingBottom="16dp"
    android:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="16dp">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="5dp"
        android:text="Suas Faltas"
        android:textColor="#ffffff"
        android:textSize="25sp"
        android:textStyle="bold" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:gravity="center"
        android:layout_weight="1">

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp" />

        <TextView
            android:id="@+id/vazio"
            android:layout_width="244dp"
            android:layout_height="42dp"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp"
            android:ems="10"
            android:gravity="center"
            android:text="Nenhuma matéria inserida"
            android:textColor="#ffffff" />

    </RelativeLayout>

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"/>

</LinearLayout>

Comment: Não funcionou, além de não aparecer o adview, desorganizou a apresentacao da listView :(


"no route to host" with static IP. Able to ping

Question: I just configured a new server from DigitalOcean. I don't think I changed anything on the server's networking configuration other than changing the ssh port from 22 to 2202, but all of a sudden I am unable to ssh into the server. I was able to intially login a couple times with ssh on port 2202
Please let me know if there is a better StackExchange for this question
$ ssh -p 2202 firstname.lastname@example.com
ssh: connect to host 159.89.x.x port 2202: No route to host

I am able to ping the server
$ ping 159.89.x.x
PING 159.89.x.x (159.89.x.x) 56(84) bytes of data.
64 bytes from 159.89.x.x: icmp_seq=1 ttl=56 time=30.0 ms
64 bytes from 159.89.x.x: icmp_seq=2 ttl=56 time=29.7 ms
64 bytes from 159.89.x.x: icmp_seq=3 ttl=56 time=29.9 ms

--- 159.89.x.x ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 29.756/29.932/30.083/0.134 ms

I turned off all network configurations except my ethernet connections
$ ifconfig

eth0      Link encap:Ethernet  HWaddr 90:2b:34:d6:e1:d5
          inet addr:192.168.0.8  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::737e:c4b0:f37c:ab45/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:7449 errors:0 dropped:0 overruns:0 frame:0
          TX packets:139088 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:6762469 (6.7 MB)  TX bytes:9333612 (9.3 MB)
          Interrupt:18

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:1180 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1180 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:109431 (109.4 KB)  TX bytes:109431 (109.4 KB)

Here is the traceroute
$ traceroute 159.89.x.x
traceroute to 159.89.x.x (159.89.x.x), 30 hops max, 60 byte packets
 1  192.168.0.1 (192.168.0.1)  0.455 ms  0.613 ms  0.802 ms
 2  hlrn-dsl-gw09.hlrn.qwest.net (207.225.x.x)  3.641 ms  3.833 ms  4.532 ms
 3  hlrn-agw1.inet.qwest.net (71.217.x.x)  4.763 ms  4.733 ms  4.734 ms
 4  dvr3-brdr-01.inet.qwest.net (208.168.x.x)  4.911 ms  5.347 ms  5.131 ms
 5  den-b1-link.telia.net (22.214.171.124)  5.336 ms  5.327 ms  5.764 ms
 6  sjo-b21-link.telia.net (22.214.171.124)  33.313 ms  29.887 ms  29.980 ms
 7  digitalocean-ic-318773-sjo-b21.c.telia.net (188.8.131.52)  29.570 ms digitalocean-ic-306499-sjo-b21.c.telia.net (22.214.171.124)  30.931 ms  30.938 ms
 8  159.89.x.x (159.89.x.x)  29.617 ms !X  29.838 ms !X  29.614 ms !X

Here is what nmap says (I am pretty unfamiliar with how to effectively use nmap)
$ nmap 159.89.x.x

Starting Nmap 7.01 ( https://nmap.org ) at 2018-03-20 09:34 MDT
Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn
Nmap done: 1 IP address (0 hosts up) scanned in 0.08 seconds

and
$ nmap -Pn 159.89.x.x

Starting Nmap 7.01 ( https://nmap.org ) at 2018-03-20 09:35 MDT
Nmap scan report for 159.89.x.x
Host is up (0.59s latency).
Not shown: 999 filtered ports
PORT   STATE  SERVICE
22/tcp closed ssh

and
$ nmap -Pn 159.89.x.x -p 2202

Starting Nmap 7.01 ( https://nmap.org ) at 2018-03-20 12:56 MDT
Nmap scan report for 159.89.x.x
Host is up (0.036s latency).
PORT     STATE    SERVICE
2202/tcp filtered unknown

Nmap done: 1 IP address (1 host up) scanned in 0.08 seconds

From the DigitalOcean console (only way to currently access the machine), I am able to ping 126.96.36.199 as well as curl -vL google.com successfully
Also from the DO console,
(myserver)$ ip route

default via 22.214.171.124 dev eth0
10.46.0.0/16 dev eth0 proto kernel scope link src 10.46.0.5
220.127.116.11/20 dev eth0 proto kernel scope link src 159.89.x.x

Since I am unable to copy / paste from the DO console, here is an image of sudo iptables -nvL INPUT
Comment: You can try `nmap -Pn 159.89.x.x -p 2202` to specifically check the SSH port remotely. Also, access the DO droplet via their Web Console and make sure it has proper connectivity to the internet. Can you `ping 188.8.131.52`? Can you `curl -vL google.com`? Also post your route table with `ip route`. Also, check `iptables -nL` on the DO droplet too, it might be that it's being blocked at the firewall.
Comment: @Andrew I just updated the question with what you asked for, although the output from `iptables -nL` is long and there is no scroll on the DO console haha. Also, I am unable to copy / paste from that window. What could I `grep` for?
Comment: If possibly, the INPUT table is probably the most helpful now, but we need to see the complete rule-set in order to asses the configuration. `iptables -nvL INPUT` would capture just the INPUT table.
Comment: @Andrew added INPUT table config
Answer: You forgot to open the port in your firewall. You need to do that, e.g. since you are using firewalld:
firewall-cmd --add-port=2202/tcp

Once it is working, make it permanent.
Comment: I wish I could buy you a beer. Couple questions. First, since I am using ansible, why didn't this show up in my other servers? They were CentOS 7.0 and this one is CentOS 7.4. Second, how did you know that I am using `firewalld`? I hadn't heard of this yet
Comment: Did you change ports on the other servers? Or have a firewall active? Anyway, I saw that it was firewalld from your image.
Comment: I did change the ports and did not make any changes to the firewall. I used the same Ansible scripts to commission the server as before. The only difference could be that something changed between CentOS 7.0 and 7.4
Answer: It sounds like you might have an iptables conflict blocking port 2202. Try this process as a test to see if you can re-gain access:
iptables-save > ~/iptables.save
iptables -F

Then re-attempt SSH on port 2202. If this works, your firewall rules need adjusting, if it doesn't work, makes sure you don't have a conflict with the Digital Ocean firewall as well.
To restore the rules, run the following:
iptables-restore < ~/iptables.save

Comment: That worked, you are a champion! Any idea on how it got messed up in the first place? Is that a permanent change? What kind of changes to I need to make to the firewall rules?
Comment: @BrianLeach Don't do this, as you are using firewalld and this will conflict with your existing firewall. You'll most likely get locked out again, e.g. the next time you reboot. See the other answer with respect to firewalld.
Comment: Now that we know it's a firewall issue, you need to properly configure it to allow port 2202/tcp in. @MichaelHampton has the command on how to do that in his answer.


pie chart with angled/horizontal labels in dc.js

Question: I need to match the designs to have the label extruding out with a horizontal line attached to the slice ticks. Is this possible?
Answer: There is support for lines to slice labels as of dc.js 2.0 beta 20.
It's called drawPaths:
https://github.com/dc-js/dc.js/blob/develop/web/docs/api-latest.md#dc.pieChart+drawPaths
It could be improved, as noted in the PR, but it's a start.


Static Network configuration with bridge in CentOS 6.2

Question: I have a server with CentOS 6.2 installed, I want to use it as a VM host to run some windows installations for development purposes. I wanted to be able to directly RDP and serve websites from IIS on these windows server installations, so I figured I would set it up as bridged networking.
I have been struggling with this all morning, usually the result being that when I brought up the bridge interface all network connectivity to the CentOS would go away, however, I think I finally have that all figured out. However, here's what happens.
The eth0 and br0 interfaces are defined in /etc/sysconfig/network-scripts with ifcfg-eth0 and ifcfg-br0. I DO NOT have ifup or ifdown or any other files for these interfaces, I have not found if they are needed. I can login and use firefox to browse the web, however, running ifconfig reveals that my eth0 does not have an IPAddress, but the br0 does. I can actually RDP into the Windows installation, and browse the internet from there as well, but I cannot directly connect(via putty, vnc, nor viewing web pages) to the CentOS box. Any idea what's up?
ifcfg-eth0
DEVICE=eth0
BOOTPROTO=none
IPADDR=192.168.1.20
GATEWAY=192.168.1.1
NETMASK=255.255.255.0
NETWORK=192.168.1.0
ONBOOT=yes
BRIDGE=br0

ifcfg-br0
DEVICE=br0
TYPE=Bridge
BOOTPROTO=static
DNS1=192.168.1.1
DNS2=184.108.40.206
GATEWAY=192.168.1.1
IPADDR=192.168.1.2
NETMAS=255.255.255.0
ONBOOT=yes

I know some of the options are inconsistent (DNS and BOOTPROTO) because I tried changing those in the eth0 file to make it work, and the changes haven't adversly affected web browsing or the other functionality
Thank you!
Answer: remove the IP settings from the eth0, leave them only on the bridge. Also add DELAY=0 to the bridge's ifcfg script. This should make things work for you.
One additional thing - make sure you have the right HWADDR= line in the ifcfg for the eth.


Re-Expressing the Digamma

Question: I was reading some articles on the digamma function, and I was wondering if anyone knows how to express the digamma function $\psi^{(0)}(n)$ in terms of a trigonometric function or a logarithmic function. Does anyone know its Fourier Series representation?
Comment: The poles of the digamma function, as well as its not being periodic, preclude the Fourier series expression, unless you only want to consider some interval that does not contain a pole. At best, all you have is the reflection formula involving the cotangent.
Comment: $\psi_0(n+1)=H_n-\gamma.$
Answer: The following formulas may be inserted into the formula given by @Lucian
$$H_n=\sum_{k=1}^n\frac{1}{k}
$$
$$
H_n-log\left(n\right)=1-\sum_{k=1}^{\infty}\left(\sum_{i=nk+1}^{n(k+1)}\frac{1}{i}-\frac{1}{k+1}\right)
$$
https://math.stackexchange.com/a/1602945/134791
$$
\gamma= \sum_{n=1}^\infty \left(\frac{2}{n}-\sum_{j=n(n-1)+1}^{n(n+1)} \frac{1}{j}\right)=\sum_{k=1}^\infty \left(\frac{2}{k}-\sum_{j=k(k-1)+1}^{k(k+1)} \frac{1}{j}\right)
$$
https://math.stackexchange.com/a/1591256/134791
$$\psi_0\left(n+1\right)=H_n-\gamma$$
$$=\sum_{k=1}^n\frac{1}{k}-\sum_{k=1}^\infty \left(\frac{2}{k}-\sum_{j=k(k-1)+1}^{k(k+1)} \frac{1}{j}\right)$$
In the complex plane outside negative integers (http://people.math.sfu.ca/~cbm/aands/page_259.htm)
$$\psi(z+1)=-\gamma+\sum_{n=1}^\infty\frac{z}{n(n+z)}=-\gamma+\sum_{n=1}^\infty\left(\frac{1}{n}-\frac{1}{n+z}\right)$$
$$=-\sum_{n=1}^\infty \left(\frac{2}{n}-\sum_{j=n(n-1)+1}^{n(n+1)} \frac{1}{j}\right)+\sum_{n=1}^\infty\left(\frac{1}{n}-\frac{1}{n+z}\right)$$
Finally,
$$\psi(z+1)=\sum_{n=1}^\infty \left(-\frac{1}{n}-\frac{1}{n+z} +\sum_{j=n(n-1)+1}^{n(n+1)}\frac{1}{j} \right), z \neq -1,-2,-3,...$$
Answer: In umbral calculus,
$\psi(x)=\operatorname{eval}\ln(B+x)$
where $B$ is Bernoulli umbra and $\text{eval}$ is index-lowering operator.

Re-Expressing the Digamma


Change Tomcat Port on CentOS 5.3

Question: I installed Tomcat5 on CentOS 5.3, by default tomcat runs on port 8080 but i already have ISPConfig running on that port.
Port 80 is taken up by Apache
How do I know which port tomcat is listening on ? and if required change the port.
Comment: [Administration panels are off topic](http://serverfault.com/help/on-topic). [Even the presence of an administration panel on a system,](http://meta.serverfault.com/q/6538/118258) because they [take over the systems in strange and non-standard ways, making it difficult or even impossible for actual system administrators to manage the servers normally](http://meta.serverfault.com/a/3924/118258), and tend to indicate low-quality questions from *users* with insufficient knowledge for this site.
Answer: In server.xml (usually in /etc/tomcat), there's a block starting
<Server port="xxxx">

or similar, where xxxx is the port your server is listening on, this will tell you where the server is listening.
Changing the port is easy, just change this setting and restart tomcat.
Alternatively run netstat -anp and it will tell you which program is using which port.
Comment: That wasn't quite what i meant.. have a look at /etc/tomcat/server.xml, see what it's telling the tomcat server to run on as a port.  It might not be 8005, it'll probably be 8080.  If you've already got something using 8080, and it's bound, then there might be something in /var/log/tomcat/catalina.out (or catalina.log) about failed startup because the port is already used.
Comment: Change the connector to be something other than 8080, maybe 8090, restart tomcat, then test it by browsing to localhost:8090
Comment: Oh, and to get a pagewise list of anything, pipe it into less, eg, `netstat -anp | less`

Then you can use PgUp/PgDown and so on to scroll through it
Comment: When I do a
# netstat -lnp | grep 8005
I get
tcp        0      0 ::ffff:127.0.0.1:8005 :::*                        LISTEN      6598/java
But when I do localhost:8005 I dont get any web page, is the firewall blocking this port, if so how to enable access.
Comment: The  file is showing Server port="8005" and  <Connector port="8080" and the Catalina.out is showing java.net.BindException: Address already in use:8080, I think this is used by ISPConfig as when I enter localhost:8080 in a web browser it shows the ISPconfig page. So what do I do?
Comment: The netstat -anp command shows many lines, and I am probably missing the first few pages, how can I get a pagewise view of the ports list?
Comment: I changed the port to 8090 and now atleast I'm getting a blank page in my browser, on windows generally we get a Tomcat start page but on Centos I am not getting that. I checked the webapps folder and its empty probably that's the problem. Where as in windows the webapps folder has some root folders
Comment: On ubuntu, the root of webapps/ contains an index.html akin to the Apache "It Works!" page.  I think you can just put a html file into the webapp root and it'll serve it, or you can drop a .war file in, and tomcat will deploy it (depending on 'autoDeploy' setting in  server.xml)

Change Tomcat Port on CentOS 5.3


O que é deploy?

Question: Cada módulo do projeto possui um .war e um .war exploded, quais são as funções desse artifacts nesse processo de "deploy"? E qual a função do Jenkins nesse contexto? Entendo que deploy é um processo de "montar esse war" pois toda vez que algo está errado recebo um Build failed in Jenkins.
Answer: Em termos gerais, deploy significa colocar em posição.
Na prática, geralmente falamos de disponibilizar um sistema para uso, seja num ambiente de desenvolvimento, para testes ou em produção.
Sobrecarga do termo
Um termo deploy pode significar muitas coisas, dependendo do ambiente e da tecnologia. Um desenvolvedor pode fazer o deploy da aplicação web no seu Tomcat local. Pode também fazer o deploy no Weblogic de produção, usado pelos usuários reais.
Nível de automação
O deploy pode ser "manual", parcialmente automatizado ou completamente automatizado.
Um processo manual pode consistir em exportar um WAR no Eclipse, acessar a página de adminitração do Tomcat e fazer o upload do WAR.
Um processo automatizado pode consistir em comitar o código no repositório, sendo que esta ação dispara automaticamente o processo de construção (build) do "executável" da aplicação e possivelmente sua disponibilização em um servidor.
Personalização
Embora o ciclo de vida de uma aplicação possa estar 100% automatizado, não significa que um commit qualquer vai acabar em produção. O importante é que todos os passos mais trabalhosos estejam automatizados, disponíveis a um comando do desenvolvedor ou responsável.
Desenvolvedores e administradores devem configurar todo esse ambiente da forma que seja mais adequada ao projeto, minimizando retrabalho, tarefas repetitivas e erro humano em todo o ciclo de vida de uma aplicação, que vai desde a especificação até a aceitação do usuário final.
Por exemplo, nem sempre faz sentido um código comitado gerar uma versão do sistema em produção. Então vários critérios podem ser adotados para que novas funcionalidades implementadas sejam devidamente entregues ao usuário final. A principal estratégia aqui é o uso correto de ramificações (branches) de desenvolvimento.
Integração Contínua (CI - Continuous Integration)
Toda essa automatização não visa apenas evitar trabalho repetitivo. Ela na verdade permite aos desenvolvedores alcançaram um nível muito maior de produtividade e qualidade.
Um problema recorrente no desenvolvimento de software é que os erros ocultos nos programas que desenvolvemos são cada vez mais caros e difíceis de corrigir na medido em que o tempo passa.
Qualquer pessoa que trabalha com programação já deve ter passado pela situação de achar que um programa estava quase pronto e "só faltava testar", para então descobrir que, na verdade, muito coisa ainda estava errada ou mesmo faltando no código.
Outra situação recorrente é a "preguiça" de testar o software, ou pelo menos a prática de postergar os testes. Sem testes e deploy automatizados, o desenvolvedor tende a escrever uma grande quantidade de código antes de realmente colocar o programa para executar, afinal se o processo é trabalhoso e toma muito tempo, ele vai evitar de fazer isso ao máximo. Só que no final gasta-se muito tempo para corrigir todos os "detalhes" que não estava corretos.
Para mitigar todos esses problemas, surgiu o conceito de Integração Contínua. A ideia é justamente automatizar o processo para que com bastante frequência, uma ou mais vezes ao dia, seja possível integrar todas as alterações de todos os desenvolvedores envolvidos no projeto e realizar um teste geral.
Automação do ciclo de vida de uma aplicação
Fazer Integração Contínua nem sempre é uma tarefa simples e existem muitas formas de fazer isso.
Construção (Build)
O build é o processo que transforma seu código-fonte em um "executável", como um Jar ou War em Java. É claro que você pode usar um script próprio executando o javac, mas existem ferramentas mais avançadas como Ant ou Maven.
Um dos métodos mais comuns de fazer isso em Java é a utilização de alguma ferramenta como o Maven. O Maven gerencia a construção (build) dos projetos através do uso de convenções e padrões. Por exemplo, os projetos que usam Maven geralmente seguem a seguinte estrutura de diretórios:

Basicamente, você coloca os códigos-fonte da aplicação em src/main/java e os testes automatizados em src/test/java.
O Maven também define uma série de fases da construção do projeto. Veja a imagem abaixo:

Vamos analisar as fases principais:

Compile: faz a compilação do código dos diretórios src/*/java.
Test: executa os testes encontrados no diretório src/test/java
Package: empacota as classes e outros arquivos em um JAR ou WAR, por exemplo.

Há também uma fase de deploy que pode ser configurada para disponibilizar o "executável" gerado em um servidor. No entanto, cada tipo de servidor precisa de um plugin diferente do Maven.
Enfim, seguindo os padrões definidos, que podem também ser personalizados, o Maven permite automatizar todo o processo de build ou construção do projeto. Há também uma fase
Se quiser saber mais sobre o Maven, sugiro a leitura do artigo:

Instalando, configurando e usando o Maven para gerenciar suas dependências e seus projetos Java

Gerenciando em alto nível
Construir o projeto é o passo mais importante, mas a Integração Contínua precisa levar em conta todo o ambiente da empresa. Afinal, nem sempre o desenvolvedor pode ou deve ter acesso direto para fazer o deploy de sua máquina local.
Nesses casos, o ambiente de desenvolvimento de uma empresa pode dividir o trabalho entre diversos servidores contendo serviços especializados. Aqui entram aplicações omo o Jenkins para "colocar ordem na bagunça".
Considere a ilustração abaixo:

Em resumo, os passos ilustrados são:

Check in: é quando o desenvolvedor faz o commit ou merge do código na branch configurada para releases do projeto no sistema de versionamento (VCS - Version Control System). A branch principal geralmente é chamada de HEAD no CVS, Trunk no SVN e master no Git, mas pode ser qualquer outra arbitrariamente definida.
A alteração no seu VCS dispara então um processo no seu Servidor de Integração Contínua (CI Server), que pode ser o próprio Jenkins. O servidor irá disparar o build do projeto nos servidores de build (build servers).
Se o projeto usa Maven, por exemplo, o build server irá então compilar, testar e empacotar o projeto usando essa ferramenta. Primeiro ele recupera o código-fonte (check out) do VCS e depois, por exemplo, executa o comando mvn package.
Após o término do build o CI Server (nosso Jenkins) recupera o relatório da compilação e dos testes e verifica se tudo ocorreu bem.
O CI Server atualiza então o status do projeto.
O CI Server, de acordo com a configuração, notifica os interessados no resultado do processo.

Dentro do processo acima, opcionalmente, poderia haver um passo para fazer o deploy da aplicação em um servidor. Uma forma seria através do próprio build do Maven. Outra seria configurar o Jenkins para executar o deploy após o build (passo #4).
No entanto, considero mais interessante a abordagem de promover determinados builds concluídos com sucesso de forma manual. O processo ainda seria todo automatizado, mas ao final o responsável pelo projeto pode selecionar um determinado build que acabou de sair de desenvolvimento e, com um clique, promovê-lo para o ambiente de testes ou mesmo para produção.
Comment: "Terminei, agora só falta testar" é sensacional :P
Answer: Deploy quer dizer implantar. Por exemplo, depois que você gerou o seu programa e quer colocar ele no ar em seu servidor de aplicação, o que você está fazendo é implantando ele no servidor. Implantar significa colocar no ar, e o termo para isso em inglês é deploy. Também é importante não confundir implantar com implementar, são coisas bem diferentes e já vi muita gente fazendo confusão entre estes dois termos.
O Jenkins é apenas o programa que automatiza o processo de construção. Ele invoca o compilador, executa os testes, roda o javadoc e executa qualquer que seja o processo para fazer a implantação e ainda armazena o histórico de cada processo de construção do seu programa bem como os artefatos gerados. Esse erro apenas diz que o processo de construção (normalmente compilação) falhou e que quem estava rodando este processo era o Jenkins.
O WAR é a "coisa" que é de fato implantada em um servidor web. Nada mais é do que um arquivo JAR com algumas configurações especiais. No entanto, dentro deste WAR podem existir outros arquivos JAR aninhados. Para que tudo possa ser executado no servidor, ele precisa ser explodido - ou seja, todo o conteúdo dos JARs aninhados deve ser extraído para dentro do WAR, desfazendo-se o aninhamento e resultando em uma hierarquia mais plana que consista apenas do WAR contendo as classes da sua aplicação (incluindo os que estavam em JARs), eliminando então os JARs aninhados.
Por fim, para implantar a sua aplicação, o Jenkins vai fazer no mínimo o seguinte: Compilar ela, gerar um WAR a partir dele (talvez explodido, dependendo de como for configurado) e então implantar ele no seu servidor de aplicação (que no seu caso é o Tomcat).
Comment: Aqui está uma resposta bem resumida e concisa, excelente +1

O que é deploy?