Diferença entre closures e functions

Question: Closures é uma function em Groovy ? Existe alguma diferença entre eles?
Answer: Uma função é algo muito mais simples. A closure pressupõe mais coisas.
Ela certamente usa uma função, mas esta precisa ser de primeira ordem, ou seja, precisa poder ser usada como dados, pode ser usada em qualquer ponto onde faça sentido, incluindo armazenar em variáveis ou passar como argumento ou retorno de função.
Mas isto ainda só seria uma função anônima, possivelmente com uma sintaxe de lambda.
Ainda precisa capturar variáveis locais de onde ela foi definida e estas variáveis precisam fazer parte do escopo da função clausura, mesmo que ela seja usada fora do escopo onde foi declarada.
Mais pode ser visto em Qual a diferença entre uma expressão lambda, um closure e um delegate?, apesar de ser outra linguagem.

Diferença entre closures e functions


ZFS - setting physical disk start point of pool/filesystem

Question: I'm testing harddisk performance, and would like to test writing to the outer tracks of my harddisk with ZFS. One way of doing this would be to create a pool/filesystem with a start point just a few Gigs away from the end of my harddisk.
Is this possible? If so, how do I do it? I've looked in zfs man pages and googled, but couldn't find what I'm looking for.
Furthermore, I'd like to create a RAIDZ1 using only the last part (outer tracks) of my HDDs the same way - for performance testing purposes.
Answer: The term you're referring to is "short-stroking". You can do this by creating a pool of disk slices rather than the whole disks. Use some small percentage of the disk (10%-12%) capacity for the slices.
This may not be worth it, though. Use faster disks and SSDs since ZFS can leverage them well.
Comment: Ah, so I create disk slices in the OS first, and then a ZFS using these slices? I thought ZFS pools had to be placed on top of entire disks.
Comment: You can use disk slices in your ZFS pool. You just have to use the slice designation in your zpool create command.
Comment: You may actually end up with worse performance if you use slices instead of whole disks, due to the way ZFS handles the [disk write cache](http://www.solarisinternals.com/wiki/index.php/ZFS_Best_Practices_Guide#Storage_Pools)
Answer: In addition to slices already rightly suggested by ewwhite, you can also use plain primary partitions a ZFS low level device if you are running on x86 architecture, and even logical ones if on a recent OpenSolaris build, Solaris 11 Express or newer.
Comment: ZFS even accepts plain files, although not recommended for anything but testing purposes.
Comment: Yes, thank you. Once I understood that zfs accepts block devices other than just entire disks, it opened up a lot more flexibility to me :-)


Accounting for pretreatment differences (linear mixed effects model) using R/nlme

Question: I have an experiment that is as follows:

4 years of data (1 year pre-treatment, 3 years during treatment)
20 plots total
5 plots of each type (Control, Treatment A, Treatment B, Treatment A+B)
Each plots is divided into 4 quadrants in which measurements are recorded.

Initial stats revealed pretreatment differences between plot types.
The data I would like to use in a linear mixed-effects model include:

my response variable;
BA - before/after (as "1" or "2");
Treatment A (as "yes" or "no");
Treatment B (as "yes" or "no");
The interaction of treatments and Year;
Plot and quadrant as nested random effects.

I've created a linear mixed effects model using the nlme package in R that currently looks like this:
model<-lme(response variable ~ BA * treatmentA * treatmentB * year ,
           method= "REML", data=data, random=~1|plot/quad, na.action=na.omit)

I get the following error message:

Error in MEEM(object, conLin, control$niterEM) :
    Singularity in backsolve at level 0, block 1

I can run the model successfully without BA or without year but am unable to get results when I run it with both of them.
Any advice or suggestions on how to account for pretreatment differences and get my LME to work happily?
Answer: Hello Daniel and welcome to CV. What you are witnessing are most probably problems with collinearity between the columns of your design matrix. Drawing analogy with the solution of a weighted least squares regression you fail to compute $(X^TWX)^{-1}$. In your case I suspect that you are defining a complex interaction matrix between BA * treatmentA * treatmentB * year that ends up being collinear with the intercept.
So my immediate response would be to try fitting your model as:
model<-lme(response variable ~ -1 + BA * treatmentA * treatmentB * year ,  ... )

If this works take notice that you have done: There is no mean response in your model anymore; understand the implication this has to your modelling assumptions.
Assuming that this doesn't work the slightly nastier version will be to fit the standard OLS model and the feed the design matrix of that model to your LME model. (Dont' panic, I explain and provide code)
In R-terms, you'll be doing this:
OLSmodel <- lm(response variable ~ -1 + BA * treatmentA * treatmentB * year,...)
ModelMatrixOLS  <- model.matrix(OLSmodel)
NonApplicable   <- which(is.na(OLSmodel$coefficients))
X_Matrix  <- ModelMatrixOLS[,-NonApplicable]
model<-lme(response variable ~ -1 + X_Matrix , ...)

So what have you done here is the following:

Line 1 : You instructed R to fit a matrix that you know/suspect is rank deficient. R's work-horse lm() fitted it by taking care automatically of the collinearities
Line 2 : You get you model matrix X
Line 3 : You find which of the original coefficient of the model matrix you tried to fit, R deemed as collinear with some other and set them to NA (practically realized it couldn't estimate them)
Line 4 : You get a new model matrix X where you have omitted the columns that R found problematic.
Line 5 : You fit your LME model, without an intercept, using the model matrix that is not rank-deficient anymore.

Elegant? No. Works? Most probably. Under this scenario MAYBE you can run the original OLS model with intercept also but it wouldn't be my first choice. Take notice that if you want to provide you own model matrix you need to set a no-intercept model (by the -1 argument). If you do not do that, the lm, lmer, lme etc. will append a column of 1 in your model matrix (and essentially nullify all the work you did building up you design matrix).
In the general case, assuming that even this fails... Transform your variables. It doesn't seem that you can meaningfully do it here but I am just saying; that might also be an option.
I am not really well-versed with lme, I work exclusively with it's sibling function lmer but in any case I think this will probably work. What you are experiencing has to do with problems of computing the model you define, not with pretreatment differences specifically. Good luck!


Let $G$ be a group, $H, K \le G$. Under what conditions does $G/H \cong G/K \Rightarrow H \cong K$?

Question:
Let $G$ be a group, $H, K \le G$. Under what conditions does $G/H \cong G/K \Rightarrow H \cong K$?

I believe there was a condition that could be simply stated under which it was true. Maybe having to do something with split exact sequences?
Comment: One sufficient condition is that $H$ and $K$ are conjugate under $\mathrm{Aut}(G)$.
Answer: I'm not aware of any useful sufficient conditions other than extremely restrictive ones like that $G$ is finite elementary abelian (equivalently, a finite-dimensional $\mathbb{F}_p$-vector space) or cyclic (in which case a subgroup is determined by its index). Consider the following very simple counterexample: $G = C_2 \times C_4$ has two non-isomorphic subgroups $H = C_2 \times C_2, K = 1 \times C_4$ both of whom have quotient $C_2$. This is the smallest finite abelian group which is not elementary abelian or cyclic.
$G$ is also a counterexample to the analogous statement about whether $H \cong K$ implies $G/H \cong G/K$: this time if we take $H = C_2 \times 1$ and $K = 1 \times C_2$, the two subgroups are isomorphic but their quotients are $C_4$ and $C_2 \times C_2$ respectively. Actually this counterexample is Pontryagin dual to the previous one.
Comment: @Jos: consider the Prufer $2$-group $\mathbb{Z} \left[ \frac{1}{2} \right]/\mathbb{Z}$. It has two non-isomorphic characteristic subgroups of orders $2$ and $4$ generated by $\frac{1}{2}$ and $\frac{1}{4}$ (precisely the subgroups of second resp. fourth roots of unity) and the quotient by either of them is isomorphic to the Prufer $2$-group again.
Comment: Wait a second, how about characteristic subgroups?


How to compare between excel and word/pdf?

Question: I have excel file that I want to compare it with a bunch of pdf/word files,
for example the excel got those cells:
a   100
b   200
c   300

and in the pdf/word there is also table that look almost the same:
a   105
b   200
c   300

I want a way to check every cell in each pdf if it match the cell in the excel
so in this example it will show that row a is not equal 100 - 105.
How can I approach this kind of a problem?
Answer: The only way I can think of is to copy the word/pdf data into an Excel worksheet and give it exactly the same form as the data in your Excel file. Then, use standard Excel formulas to compare the data...


GhettoVCB snapshot failures on ESXI 4.0 - 4.1

Question: i got a problem today. A few hours ago, i updated my esxi to version 4.1 from 4.0. My aim was to get a backup from my vm's with ghettoVCB.sh even if there are snapshots of the vm. (at 4.0 that did not work at all)
For this, i downloaded the latest version of ghettoVCB(github) and unzipped it.
The important files (chmod 777) are now unpacked in the folder: ghettoVCB-master and i edited the line VM_BACKUP_VOLUME to the path where the backups should be after running the script.
When i run the script and there are no snapshots of a vm, the vm gets "backuped" in the folder: VM_BACKUP_VOLUME=/vmfs/volumes/datastore1/BACKUP
this works.. so far..
But as i said, when there is a snapshot of a vm, i just get the messages:
2013-06-13 15:21:54 -- info: ###### Final status: ERROR: No VMs backed up! ######

(if there is at least one vm that can get backuped without a snapshot)
and:
2013-06-13 15:19:46 -- info: ###### Final status: ERROR: All VMs failed! ######

(if all vm's have got snapshots.)
I read in the internet to configre in ghettoVCB.conf and ghettoVCB.sh following to 1 instead of 0:
ALLOW_VMS_WITH_SNAPSHOTS_TO_BE_BACKEDUP=1

but that won't change anything.
Comment: so i just don't know how to activate the function that ghettoVCB backups vm's even if there are snapshots of it ..
Answer: Have you read the documentation for this feature? It would not back up snapshots but consolidate them and back up the VM afterwards, so you probably do not want to use it anyway:

However, I decided to support this use case as it was recently brought to my attention that some of the commercial backup solutions that support VMs with existing snapshots just consolidate all snapshots prior to backup. If this feature is enabled, it will consolidate ALL existing snapshots on the VM prior to running a backup.

If this is really what you want to have, the VMWare communities have a thread which describes a problem looking similar to yours and proposes a code change to the script which is meant to fix the problem:
#        elif ls "${VMX_DIR}" | grep -q "\-delta\.vmdk" > /dev/null 2>&1; then
#            if [ ${ALLOW_VMS_WITH_SNAPSHOTS_TO_BE_BACKEDUP} -eq 0 ]; then
#                logger "info" "Snapshot found for ${VM_NAME}, backup will not take place\n"
#                VM_FAILED=1
#            fi
        elif [[ -f "${VMX_PATH}" ]] && [[ ! -z "${VMX_PATH}" ]]; then
            if ls "${VMX_DIR}" | grep -q "\-delta\.vmdk" > /dev/null 2>&1; then
                if [ ${ALLOW_VMS_WITH_SNAPSHOTS_TO_BE_BACKEDUP} -eq 1 ]; then
                    logger "info" "Snapshot found for ${VM_NAME}, consolidating ALL snapshots now (this can take awhile) ...\n"
                    $VMWARE_CMD vmsvc/snapshot.removeall ${VM_ID} > /dev/null 2>&1
                else
                   logger "info" "ERROR: Snapshot found for ${VM_NAME}, backup will not take place\n"
                   exit 1
                fi
            fi

Comment: I read the documentation and it just says nothing about backuping a vm when there are snapshots of it. The script just does not do a backup of that vm.. i have a look at the thread. problem is that when i active "ALLOW_VMS_WITH_SNAPSHOTS_TO_BE_BACKEDUP=1" nothing happens at all..
Comment: @NovaCP "nothing" is probably not what is happening. Run the script with debugging output enabled and see if your problem matches the one described in the thread. If so, try patching the shell script as recommended.
Comment: yes, it is the same problem. i edited the shell script and added the code of the other thread, i will tell you guys what happened, it's running atm.
Comment: it worked, but problem is that deleting the old snapshots and consolidating all snapshots is not what i want.. but probably the only thing i can get. Is there another way to backup a vm that has a snapshot without losing the snapshots that were there before? (on 4.1)
Comment: i could do the same thing with 4.0 too but i upgrated to 4.1 because i read somewhere that you could take a backup of the vm without losing the snapshot..but found no way.
Comment: if you *need* to preserve snapshots and have some kind of a SAN as backing storage for VMFS, you might create a writable snapshot of the entire VMFS volume, expose it to another ESXi host (or a Windows/Linux host with the [VMFS driver toolkit](http://code.google.com/p/vmfs/) installed), mount the store there and copy the files off. I am not aware of a solution which would work with local storage like ghettoVCB does.
Answer: What i understand from your post is you are trying to backup VM with ghettoVCB which can't recognize any VM's. So here your provided config is fine just need few modifications :
** How you are running ghetto script**
Solution:
Create a file and insert the vm name:
suppose VM name is
1. test1
 2. test2
Then, inside ghetto directory:
vi backup

test1
test2
Now run save and close file and run below command:
./ghettoVCB.sh -f backup -d dryrun

Here -f is for take a backup of specific vm's whose name is listed in backup file which we created earlier. And -d dryrun will look for those listed VM's, are they exists or not and can be able to backup. Output will be like

-- info: ###### Final status: OK, only a dryrun. ######

Now you can proceed for backup run below command:
./ghettoVCB.sh -f backup

Here your backup will start and save snapshot on given destination.


Pure Javascript end()

Question: How to recreate a jQuery end()
$('#id') .find('.class') .css('font',f) .end() .find('.seven') .css(b,'red')

What I Have
$('#id') = .getElementById()
.find('.class') = .querySelectorAll()
.css('font',f) = for loop change css

.end() --- Here lies my problem… I don't know how to return back to the first element in the chain

.find('.seven') = .querySelectorAll()
.css(b,'red') = for loop change css

Does Javascript have an .end() that's baked into it that I don't know about?
Comment: No, there's not a javascript `end()` function.  It's just a way to tell jQuery "I'm done with the selector results returned by `find`, go back to considering that I'm working on the previous object.  If you store a reference to whatever your `getElementById` returned, then `end` would set `this = myElem` (conceptually).  It's probably a bit more advanced under the hood, but it's not something that's directly analogous to some javascript behavior (though maybe you could get there with scope / function calls / closures?)
Comment: There is no end function baked into the DOM api. Have you tried looking through jQuery source to see how they solve the problem?
Comment: I'm not good at reading other peoples code… wish I could but… that's a little too advanced for me
Comment: The javascript way would be to use a drat simple *variable*. No chaining.
Comment: So if I put a var firstChainItem = document.getElementById('id')
Comment: create a .find() that updates previous item
Comment: No, you don't update the variable. Just just write `const item = document.getElementById('id'); for (const el of item.querySelectorAll('.class')) /* update css */; for (const el of item.querySelectorAll('.seven')) /* update css */;` where you use `item` multiple times.
Answer: When You check jQuery source code, You will see that they are pushing each element on stack. Then each use of end() function pop previous object from the stack. You would have to do simple version of this aproach.

Pure Javascript end()


Question on rhythmic interpretation of Chopin's Prelude Op 28 No 1 : Performance differs from score?

Question: most of the bars in this short prelude have a clear rhythmic marking: Its all sextuplets and the right hand is clearly aligned with the left as the score indicates, where the right hand melody starts at the second sextuplet (Bars A and B in the example image).
However there are some bars where this changes, shifting the right hand to the starting sextuplet, and the alignment with the left and is not so clear. The score a quintuplet, for which all notes except the first would not be lined up with the left hand. (Bars C and D in the example image).

Following the score, the last left hand note is never aligned with the third right hand note (green dotted line, in all bars A, B, C and D).
Listening to some interpretations though, it sounds as if the right hand in bars C and D is still interpreted as sextuplets starting on one, and leaving a rest at the end, with the consequence that the third right hand notes and left hand notes are suddenly played unisono (red dotted line on bars C and D, second image).

This happens both in Kissin's recording

as well as when played by Paul Barton where he explicitly talks about the rhythm of this piece

 at exactly 2:40
Am I reading the score wrong or is this just a common creative freedom of interpretation of this piece?
Comment: The quintuplet bars are marked with an "a)". That looks like there could be a variant somewhere in a footnote or in the back of the score. Have you tried to look at that note? Also your green lines in the quintuplet bars are incorrect since the third note of a quintuplet is slightly before its middle, so that note will be played only a tiny bit after the last note in the LH.
Comment: @Ramillies both good observations. The image is a screenshot from Kissin's video. My own score doesn't have the a) remark and no variants written. On the second point, yes, that is correct that the third quintuplet is not on a downbeat, but the important thing is that is not aligned with the left hand
Comment: @Ramillies but you have a good point there. Even if it was perfectly executed from the score, at the speed Kissin is playing it it would be really hard to hear. (Paul Barton's playing is a different story as he explicitly plays both hands unisono)
Answer: I'd say that many - if not all - performances differ from score, as each score is only an approximation of the musical intention of the composer.
Only a computer will play exactly what is written - because this machine is not a musician.
In the other way: If you want to notate exactly the performance of an artist the score would be unreadable because of all the fine differentiations of minimal note values.
Now this example of Chopin with sixtuplets and quintuplets  is intended by the composer. I'd play the 6 as 2x3 and the 5 as 2 and 3, whereby  I'd play 2 as hemioles so that the 2nd triplets are similar in all measures and the melody of the 2nd half of each bar remains rhythmically the same.
(When I've learnt this piece I probably ignored this little deviation and played all arpeggios as sixtuplets.)


How to use combinatorial proof instead of induction?

Question: Let k ≥ 1 be an integer and consider a sequence $n_1, n_2, . . . , n_k$ of positive
integers. Use a combinatorial proof to show that
$\binom{n_1}{2}$ + $\binom{n_2}{2}$ +...+ $\binom{n_k}{2}$ $\le$ $\binom{n_1 + n_2 + ...+ n_k}{2}$
Answer: Consider the disjoint union
$$
G=K_{n_1}+\dotsb+K_{n_k}.
$$
The LHS counts the number of edges in $G$. But $G$ is also a subgraph of
$$
H=K_{n_1+\dotsb+n_k}.
$$
The RHS counts the number of edges in $H$.
Answer: Urn approach
Lets say you got $k$ urns with $n_1,...,n_k$ marbles. The number
$${n_1\choose 2}+\cdots +{n_k\choose 2}$$
corresponds to the number of possible (unordered) pairs you can pick from all those marbles under the restriction that both marbles are from the same urn. The number
$${n_1+\cdots+n_k\choose 2}$$
corresponds to the number of pairs without this restriction. But it includes all the former cases, so it must be bigger.

Graph approach
Having $k$ complete graphs with nodes $n_1,...,n_k$ and forming their union will give you a graph $G$ with
$${n_1\choose 2}+\cdots +{n_k\choose 2}$$
edges. This graph is not connected, so certainly not complete. But add all the missing edges to make it complete and it now has
$${n_1+\cdots+n_k\choose 2}$$
edges. As we added edges to come here, this new number must be bigger.


How to set rootViewController for navigation view controller and tabbar controller in AppDelegate

Question: i have this problem. When i set rootViewController for TabbarController, it show correctly. But i set another rootViewController for navigation bar, TabbarController will not able to display. Any idea?
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    self.window.rootViewController = [[DCTabBarController alloc] init];
    DCTabBarController *tabBar = (DCTabBarController *)self.window.rootViewController;
    [tabBar setSelectedIndex:2];

    Map_ViewController *vc = [[Map_ViewController alloc] init];

    UINavigationController *rootNav = [[UINavigationController alloc] initWithRootViewController:vc];
    [rootNav.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbarBackImage"] forBarMetrics:UIBarMetricsDefault];
    rootNav.navigationBar.tintColor = [UIColor whiteColor];
    [rootNav.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, nil]];

    LeftViewController *leftVC = [[LeftViewController alloc] init];

    RightViewController *rightVC = [[RightViewController alloc] init];

    XLSlideMenu *slideMenu = [[XLSlideMenu alloc] initWithRootViewController:rootNav];

    slideMenu.leftViewController = leftVC;
    slideMenu.rightViewController = rightVC;
    self.window.rootViewController = slideMenu;

    [self.window makeKeyAndVisible];

    return YES;
}
</code>
After applied Adeel solution, here is the output.But items in tabbar will not display accordingly.
Comment: That's because in this line of code `self.window.rootViewController = slideMenu` you are setting `XLSideMenu` as the rootViewController of your application's window.
Comment: Hi Adeel, yeah, but how can i set it for both? Now only will show slidemenu and tabbar will not display accordingly.
Comment: I'm not sure but from your code it appears that you want to set the `XLSlideMenu` as application's rootViewController and `DCTabBarController` as the slide menu's rootViewController. Only the `Map_ViewController` doesn't make any sense. Can you share the screenshot of what you are trying to achieve?
Answer: One important thing to mention here is that an application's window can have only one rootViewController (of course). Like I said in my comment as well, you probably want to do something like this.
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    Map_ViewController *vc = [[Map_ViewController alloc] init];

    UINavigationController *rootNav = [[UINavigationController alloc] initWithRootViewController:vc];
    [rootNav.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbarBackImage"] forBarMetrics:UIBarMetricsDefault];
    rootNav.navigationBar.tintColor = [UIColor whiteColor];
    [rootNav.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, nil]];

    DCTabBarController *tabBar = [[DCTabBarController alloc] init];
    [tabBar setViewControllers:@[rootNav]];
    self.window.rootViewController = tabBar;

    LeftViewController *leftVC = [[LeftViewController alloc] init];

    RightViewController *rightVC = [[RightViewController alloc] init];

    XLSlideMenu *slideMenu = [[XLSlideMenu alloc] initWithRootViewController:tabBar];

    slideMenu.leftViewController = leftVC;
    slideMenu.rightViewController = rightVC;
    self.window.rootViewController = slideMenu;

    [self.window makeKeyAndVisible];

    return YES;
}
</code>
Comment: Hi Adeel, thx for your answer. However, i realise that my tabbar item does not display accordingly.Only can see the tabbar. Any idea?
Comment: This way I can't say anything. You need to show how it is displayed and what do you expect? You should update your question and provide more detail.
Comment: Hi adeel, screenshot as attached after i apply your suggestion. By right i have "Home", "category", "Map", and etc item in tabbar but now didnot display accordingly. And inside my navigation bar, i have other modules like merchant, setting and etc.
Comment: Hi adeel, i have solve my problem by using your solution with changed this code  DCTabBarController *tabBar = [[DCTabBarController alloc] init];
   [tabBar setViewControllers:@[rootNav]];
    self.window.rootViewController = tabBar; to self.window.rootViewController = [[DCTabBarController alloc] init];
    DCTabBarController *tabBar = (DCTabBarController *)self.window.rootViewController;
    [tabBar setSelectedIndex:2];. Thx
Comment: @Test87 that won't display. My suggestion was to resolve the `rootViewController` issue. The tab bar items do not display because they are not set. To fix this problem you need instantiate all the view controllers to be shown in the tab bar controller and set the tab bar item for each of these view controller.


Ansible replace all values with matching variable name

Question: I'm a noob to Ansible, and could be going the wrong way about this, but this is the only way I know how to deal with this problem.
I have an ini file that's 4000 someodd entries long.  In an attempt to do configuration as code, I have extracted out the values of each entry out into a variable file in the format of sectionheader--keyname: originalvalue and replaced them with a token pattern and the name of the variable that now contains their value.
I know Ansible can do regex replacement, but haven't been able to find a way that can do it as dynamically as this.
original file:
[sectionheader1]

keyname1=value1

[sectionheader2]

keyname1=value2

file with token replacements now kept in source and deployable:
[sectionheader1]

keyname1=%<sectionheader1--keyname1>

[sectionheader2]

keyname1=%<sectionheader2--keyname1>

variables:
testenvironment:
  sectionheader1--keyname1: value1
  sectionheader2--keyname1: value2
prodenvironment:
  sectionheader1--keyname1: value1 (specific to prod)
  sectionheader2--keyname1: value2 (specific to prod)

And then the idea is, I would replace every occurence of the token pattern %<> that I find a matching variable name for, and viola, I've constructed my config file specific to the environment I'm operating in.  And now, I can check and if I have any lingering %<> patterns, I know that not all of the variables were defined, and can throw an error.  Octopus deploy handles variable replacement in config files this way, which is what I have the most experience with.
Does Ansible have any way of doing this?  I could write a script to do it I suppose and just have Ansible call that, but I was hoping for a built in way of configuration variable replacement as code.
Comment: I think that you're looking for the Ansible template function and the jinja2 templating syntax
Answer: The ini_file module might be used.
The task below
- ini_file:
    path: /scratch/testenvironment.ini
    section: "{{ item.key.split('--').0 }}"
    option: "{{ item.key.split('--').1 }}"
    value: "{{ item.value }}"
  loop: "{{ testenvironment|dict2items }}"

gives
$ cat /scratch/testenvironment.ini

[sectionheader2]
keyname1 = value2
[sectionheader1]
keyname1 = value1

If the sections shall be alphabetically sorted use
 loop: "{{ testenvironment|dict2items|sort(attribute='key') }}"

Answer: With an appropriate setup template you should be able to set everything with a dict.
A .ini is in essence a 2 depth dict, so we're just going to treat it as such using 2 nested jinja2 for loops in a .j2 template.
In this example I'm setting the env variable on the commandline for compactness, but it can be set in inventory, host_vars, or group_vars files.
ansible/example.yml
---
- hosts: localhost
  gather_facts: false
  vars:
    dev:
      section1:
        key1: value1
      section2:
        key1: value1
    prod:
      section1:
        key1: value2 #(specific to prod)
      section2:
        key1: value2 #(specific to prod)
  tasks:
    - template: src=example.ini.j2  dest=/tmp/ansible.ini

ansible/templates/example.ini.j2
{% for section in vars[vars.env] %}
[{{section}}]
{% for key in vars[env][section] %}
{{key}}={{vars[env][section][key]}}
{% endfor %}
{% endfor %}

.
$ ansible-playbook ansible/test.yml -e env=dev; cat /tmp/ansible.ini

PLAY [localhost] ********************************************************************************************************************************************

TASK [template] *********************************************************************************************************************************************
changed: [localhost]

PLAY RECAP **************************************************************************************************************************************************
localhost                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

[section1]
key1=value1
[section2]
key1=value1

.
$ ansible-playbook ansible/test.yml -e env=prod; cat /tmp/ansible.ini

PLAY [localhost] ********************************************************************************************************************************************

TASK [template] *********************************************************************************************************************************************
changed: [localhost]

PLAY RECAP **************************************************************************************************************************************************
localhost                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

[section1]
key1=value2
[section2]
key1=value2


Hide the header of a view block when there is no content

Question: On a page, a views block should show some text on top of the view when the block doesn't hide and there is content to show:
Title •
.
Now, when there is no content in the block, this text should be hidden.
I've tried to do this with putting the header in the view as 'unfiltered text' in 'header' and then setting the view to hide when there's no content. This doesn't work or could it be that I'm doing something wrong?
Update, I got it to work, and think the following is happening:
It is possible to just put this text in the header of the view as 'unfiltered text' in 'header' and it will hide when there are no results.
However, when the view is based on a taxonomy relationship as it was with mine, and 'require this relationship' is not set, there will always be a result, so the header will show eventhough those results are filtered away.
Answer: Well I think you are asking how to hide a block view completely when it is inserted as a global: view area in the header of another view.

For the parent view:

When inserting the block view into the header of another view, make sure you leave the box unchecked that says: Display even if view has no result

For the block view that is being inserted check these 3 things:

1:
If you are displaying fields in the block view, you want first make sure you are hiding any empty fields under Show: Fields | Settings

2:
Then you want make sure you you have the Hide block if the view output is empty: set to yes under the advanced tab in the block view.

3:
You also want to add a contextual filter for the block view that defines the context you want. Then set the WHEN THE FILTER VALUE IS NOT AVAILABLE setting to hide view. (For the image below, my context needed was taxonomy term ID.)

Hope this helps!
Comment: Thank you for your elaborate instructions! I've managed to achieve the showing and hiding of the header using this technique, but don't you think there must be a better way? The only thing I would like to do is just put some text on top of the view when the block doesn't hide and there is content to show.
I will edit my question to be more distinct
Comment: You should be able to just add that text as a header message in the block view that is being hidden, and when there are no results for the view, the message in the header will be hidden as well. Are you inserting a view in another view, or just trying to accomplish this with one view?
Comment: Yes, you're right. I was just doing this with one view. When the view is based on a relationship as it was with mine, and 'require this relationship' was not set, there would still always be a result. (see update)


Are Azure Active Directory's TenantID and ClientID considered secrets?

Question: For testing purposes I've created an ASP.NET Core MVC app in VS2019 and added authentication "Cloud - Single organization".
As part of the creation process, VS registered an app in my subscription's Azure AD and allowed me to login with the users stored in there.
I then created another app registration in a different subscription and changed the MVC app's 'app settings.json' to contain the other subscription's app credentials:

Domain
TenantId
ClientId

And now I could login with users stored in the other subscription's directory.
My question is: if I push my MVC app to a public git repo, should I consider the above credentials secrets and remove them before committing?
There's no real danger in my opinion but on the other hand it feels wrong to expose them.
Answer: The both values (tenant_id and client_id) are not considered a secret. They are public. Once you publish your application publicly (and not just on intranet), everyone will be able to get both these values - they are both used in the OIDC redirect to authorization endpoint.
However I might consider hiding them anyway in the web.config / settings.json file - a general best practice for managing application settings. A nice opportunity to try Azure Application Configuration service ;)


Como alterar o foco das abas de um TabHost?

Question: Tenho o seguinte código.
private void TabsCadastro(int visualizar,int origem)
{
    TabSpec abaCLiente,abaEndereco,abaContrato;
    TabHost tabHost = getTabHost();

    abaCLiente = tabHost.newTabSpec("tag1");
    abaCLiente.setContent(R.id.clientes);
    abaCLiente.setIndicator("Cliente");

    abaEndereco = tabHost.newTabSpec("tag2");
    abaEndereco.setContent(R.id.endereco);
    abaEndereco.setIndicator("Endereço");

    abaContrato = tabHost.newTabSpec("tag3");
    abaContrato.setContent(R.id.contrato);
    abaContrato.setIndicator("Contrato");
    tabHost.setFocusableInTouchMode(true);

    if(origem == 0)
    {
        tabHost.addTab(abaCLiente);
        tabHost.addTab(abaEndereco);
        tabHost.addTab(abaContrato);
    }
    tabHost.getTabWidget().setEnabled(false);

    tabHost.setCurrentTab(0);

}

Gostaria de saber como faço para alterar o  foco das abas? Gostaria de criar um botão para alterar o foco ao invés de clicar nas tabs para isso. Vou colocar um botão em cada aba para navegar entre elas já tentei usar
    setFocused(boolean),
    setFocusable(boolean),

mas não consegui mudar o foco.
Comment: Tens que fazer uso do [`setCurrentTab()`](http://developer.android.com/reference/android/widget/TabHost.html#setCurrentTab%28int%29) para mudar de _tab_, algo tipo: `MainActivity.TabHost.setCurrentTab(1);`.
Comment: Acho que você não deveria usar mais TabHost, pois está muito ultrapassado. Usa ViewPager com essa biblioteca aqui:  https://github.com/bitjjj/PagerSlidingTitleIconTabStrip
Answer: Eu costumo fazer o seguinte:
private void initialiseTabHost(Bundle args) {
    tabHost = (TabHost) findViewById(android.R.id.tabhost);
    tabHost.setup();
    AddTab(this, this.tabHost, this.tabHost.newTabSpec("Tab1")
            .setIndicator(addButton("Tab1")));
    AddTab(this, this.tabHost, this.tabHost.newTabSpec("Tab2")
            .setIndicator(addButton("Tab2")));
    AddTab(this, this.tabHost, this.tabHost.newTabSpec("Tab3")
            .setIndicator(addButton("Tab3")));
    tabHost.setOnTabChangedListener(this);
}

public Button addButton(String texto) {
    Button button = new Button(getApplicationContext());
    RelativeLayout.LayoutParams layoutParamsRelative = new RelativeLayout.LayoutParams(
            0, 0);
    button.setLayoutParams(layoutParamsRelative);
    button.setText(texto);
    return button;
}

private void intialiseViewPager() {
    List<Fragment> fragments = new Vector<Fragment>();
    fragments.add(new Fragment1());
    fragments.add(new Fragment2());
    fragments.add(new Fragment3());

    pagerAdapter = new PagerAdapter(super.getSupportFragmentManager(),
            fragments);
    viewPager = (ViewPager) super.findViewById(R.id.viewpager);
    viewPager.setAdapter(pagerAdapter);
    viewPager.setOnPageChangeListener(this);
}


How can I prove these two questions without using the following theorem?

Question: Question 1: Let $X_1, X_2, \cdots$ be independent random variables such that $$P(X_n=-n^{\theta})=P(X_n=n^{\theta})=\frac{1}{2}.$$ If $\theta > -\frac{1}{2}$ prove that the Lyapunov condition works and the sequence satisfies the central limit theorem.
Question 2: Let $X_1, X_2, \cdots$ be independent random variables such that $$P(X_n=-n^{\theta})=P(X_n=n^{\theta})=\frac{1}{6n^{2(\theta -1)}}\quad \text{and} \quad P(X_n=0)=1-\frac{1}{3n^{2(\theta -1)}}.$$
If $1< \theta < \frac{3}{2}$ prove that the Lindeberg condition works works and the sequence satisfies the central limit theorem.

THEOREM: Let be $\lambda >0$, then $$\frac{1}{n^{\lambda +1}}\displaystyle\sum_{k=1}^{n} k^{\lambda}\underset{n\to +\infty}{\longrightarrow} \frac{1}{\lambda+1},$$ in such a way that $\displaystyle\sum_{k=1}^{n} k^{\lambda}$ has the order $\mathcal{O}= n^{\lambda + 1}$.

Solution of the question 1: $EX_n=0\; \forall n\in \mathbb{N}$, $Var(X_n)=EX_n^2=n^{2\theta}$ and $\displaystyle\sum_{k=1}^{n} Var X_k = \displaystyle\sum_{k=1}^{n}k^{2\theta}$ is (by the theorem above) $\mathcal{O}(n^{2\theta +1})$. Also $S_n=\left(\sum_{k=1}^{n}Var(X_k)\right)^{\frac{1}{2}}$ is (using the theorem above) $\mathcal{O}=\left(n^{(2\theta+1)/2}\right)$. By the Lyapunov condition there exists $\delta >0$, such that
\begin{align*}
\lim_{n\to +\infty} \frac{1}{s_n^{2+\delta}} \displaystyle\sum_{k=1}^{n} E|X_k|^{2+\delta} &=lim_{n\to +\infty} \frac{1}{2^{2+\delta}}\displaystyle\sum_{k=1}^{n} K^{(2+\delta)\theta}\\
 &=\lim_{n\to +\infty} \frac{\mathcal{O}\left(n^{(2+\delta)\theta+1}\right)}{\mathcal{O}\left(n^{(2+\delta)(2\theta +1)/2}\right)}\\
 &=\lim_{n\to +\infty} \frac{\mathcal{O}(n)}{\mathcal{O}(n^{(2+\delta)/2})}\\
 &=0\quad \text{for}\; \delta=2
\end{align*}
Thus, the Lyapunov condition is satisfied $\forall \alpha \in \mathbb{R}$ and $\delta =2$.
Therefore,
$$\frac{\displaystyle\sum_{k=1}^{n} X_k - E\sum_{k=1}^{n} X_k}{\sqrt{\displaystyle\sum_{k=1}^{n}Var(X_k)}}\overset{D}{\longrightarrow} \mathcal{N}(0,1).$$
The convergence above means that converge in distribution to standard normal distribution $\mathcal{N}(0,1)$.
REMARK: Notice that the question 1 is already answered, however I'm strying to prove again without use the theorem above. Can you help me with this?
Answer: This answer is just for part a. Lyapunov's condition is that $$\lim_{n\rightarrow\infty}\frac{\sum_{i=1}^n\mathbb E\left(|X_i-\mu_i|^{2+\delta}\right)}{\left(\sum_{i=1}^n\sigma_i^2\right)^{(2+\delta)/2}}=0$$
for some $\delta>0$. For this problem we have
$$\begin{split}\frac{\sum_{i=1}^n\mathbb E\left(|X_i-\mu_i|^{2+\delta}\right)}{\left(\sum_{i=1}^n\sigma_i^2\right)^{(2+\delta)/2}}&=
\frac{\sum_{i=1}^ni^{\theta(2+\delta)}}{\left(\sum_{i=1}^n i^{2\theta}\right)^{(2+\delta)/2}}\\
&=\frac{\sum_{i=1}^ni^{\theta(2+\delta)}}{\left(\sum_{i=1}^n i^{2\theta}\right)^{(2+\delta)/2}}\cdot \frac{\frac{1}{n^{\theta(2+\delta)}}}{\frac 1{n^{\theta(2+\delta)}}}\cdot\frac{\frac 1 {n^{(2+\delta)/2}}}{\frac 1 {n^{(2+\delta)/2}}}\\
&=\frac{\left[\sum_{i=1}^n\left(\frac i n\right)^{\theta(2+\delta)}\frac 1n\right]\cdot \frac 1 {n^{(2+\delta)/2-1}}}{\left[\sum_{i=1}^n\left(\frac i n\right)^{2\theta}\frac 1 n\right]^{(2+\delta)/2}}\\
&\longrightarrow\frac{\int_0^1x^{\theta(2+\delta)}dx\cdot \frac 1{n^{(2+\delta)/2-1}}}{\int_0^1x^{2\theta}dx}\end{split}$$
The integrals converge to $$\frac{2\theta+1}{\theta(2+\delta)+1}$$ if $\theta>-\frac{1}{2+\delta}$ and since $\delta>0$, $\frac1 {n^{(2+\delta)/2-1}}$ converges to $0$, so the whole expression is $0$ in the limit. Since $\delta$ was arbitrary, the Liapunov condition for CLT holds if $\theta>-\frac 12$.
Comment: You are welcome! I have put in a proof sketch for part b, I am not sure it is 100% correct, but it should give you some ideas! Thanks!
Comment: Perfect!!! Congratulations! Thank you for all the effort you put into this answer!
I still struggling with the second question. If you have any hint please, would you tell me? Of course, I have already much reasons to say thank you!!  You saved me here...
Answer: This is for part b (only a proof sketch).
Lindeberg's condition is that $$\lim_{n\rightarrow\infty}\frac{\sum_{k=1}^n\mathbb E\left[(X_k-\mu_k)^2\mathbb 1_{\{|X_k-\mu_k|>\epsilon s_n\}}\right]}{s_n^2}=0$$
for all $\epsilon>0$, where $s_n^2=\sum_{k=1}^n \sigma_k^2$. For this problem, $s_n^2=\sum_{k=1}^n\frac{k^2}{3}$ and looking at the indicator part we have
$$\begin{split}|X_k-\mu_k|&>\epsilon s_n\\
|X_k|&>\epsilon\sqrt{\sum_{k=1}^n\frac{k^2}3}\end{split}$$
$|X_k|$ can take on the values $0$, in which case the indicator is $0$, and $k^{\theta}$, in fact being largest when $k=n$, in which case we have
$$\begin{split}\frac{n^{\theta}}{\sqrt{\sum_{k=1}^n\frac{k^2}3}}&>\epsilon\\
\frac{\sqrt 3n^\theta}{\sqrt{\sum_{k=1}^n\left(\frac k n\right)^2\frac 1 n}\cdot n \cdot \sqrt n}&>\epsilon\\
\frac{\sqrt 3 n^{\theta-\frac 32}}{\left(\sum_{k=1}^n\left(\frac k n\right)^2\frac 1 n\right)^{\frac 1 2}}&>\epsilon\end{split}$$
In the limit the denominator becomes
$$\sum_{k=1}^n\left(\frac k n\right)^2\frac 1 n\longrightarrow \int_0^1 x^2 dx=\frac 1 3$$
while the numerator is $0$ if $\theta<\frac 32$. Therefore the indicator is $0$ in this case, and the expectation in the numerator of Lindeberg's condition is $0$. Since $s_n^2\rightarrow\infty$, the expression as a whole is $0$ and Lindeberg's condition is satisfied. (Note: $\theta>1$ because otherwise the denominator is $0$ in the problem description/ the probabilities are not valid.)
Comment: Thanks very much!!! I've done some sketches here, I'll compare. Thanks for all help.


Opening hours - Days and times

Question: I have created a content type - Shops in College
I would like to display opening days and times. Something like this:
Monday - 09:00-18:00
Tuesday - 09:00-18:00
Wednesday - 09:00-18:00
Thursday - 09:00-18:00
Friday - 09.00-13:00
Saturday - Closed
Sunday - Closed
Is there any way I can do this by managing the fields? Or how would I go about this?
Thanks
Answer: There is a module for Drupal 7 for this called Opening Hours and for 8.x there is Office Hours.
Comment: Oh thank you Im using Drupal 7 so I will have a look at it now.

Opening hours - Days and times


Analytic function map semicircular region bijectively to unit ball?

Question: Find an analytic function
$f: Ω\to\mathbb{C}$
which takes the semicircular region
$Ω =\{z\in\mathbf{C}:|z|<1,\text{Im} z >0\}$ one-to-one and onto the unit ball
$B_1(0) =\{z\in\mathbf{C}:|z|<1\}.$
My idea is let $f(z)=z^2$, but it seems the real segment [0,1) is missing. Is there any other function satisfying the requirement?
Answer: The mapping $$h: \Omega \longrightarrow Q_1, z \mapsto i \ \frac{1-z}{1+z}$$ maps the domain $\Omega$ conformally onto the first quadrant $Q_1 := \{ z = x + iy \in \mathbb{C} \ | \ x, y > 0 \}$. Subsequently, the mapping $z \mapsto z^2$ sends $Q_1$ conformally onto the upper half plane $UH := \{ z = x + iy \ | \ y > 0 \}$. Finally, the mapping $$g: UH \longrightarrow B_1(0), z \mapsto \frac{z-i}{z+i}$$ maps $UH$ conformally onto the unit disk $B_1(0)$. Hence the composed mapping $$f := g \circ z^2 \circ h: \Omega \longrightarrow B_1(0)$$ is the desired mapping you are looking for.
Comment: Thanks for your answer. I am new to this area. I wonder if there are some references/tricks about functions of the form $\frac{az-b}{cz-d}$? For example, how could I know they map some special area to some other special area?
Comment: You're totally right, there are indeed "some references/tricks" on functions of the form you mentioned: mappings $$\frac{az-b}{cz-d}$$ with $a,b,c,d \in \mathbb{C}$ satisfying $ad-bc \not = 0$ are called *Möbius transformations*, they play a crucial role in complex analysis and in particular in geometric function theory. Another reference I would recommend you to check is the *Cayley transform*, which is nothing else but the mapping $g(z) = \frac{z-i}{z+i}$ i mentioned in my answer - it is a fundamental result that $g$ maps the upper half plane conformally onto the unit disk.


.htaccess Redirection with parameters

Question: If I enter my website's URL with 'www' then it is redirecting me to the main URL of the website but without parameters.
eg:
http://www.subdomain.domain.com/param1/param2

redirects to
http://subdomain.domain.com/

But in above redirection it is not appending query string after the URL.
Desired redirection is:
http://subdomain.domain.com/param1/param2

I have tried with following code but none worked for me:
RewriteCond %{HTTP_HOST} ^www.subdomain.domain.com$ [NC]
RewriteRule ^(.*)?$ http://subdomain.domain.com/$1 [L,R=301]

Please help.
Answer: in RewriteCond, you will have to add a \ before .
RewriteCond %{HTTP_HOST} !^subdomain\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://subdomain.domain.com/$1 [R=301,L]

Comment: Ya it seems working.. but if i have a URL like this: http://subdomain.domain.com/about.html then what changes i should made in rule?
Comment: try to remove `www\.`  and tell me results
Comment: i think it was working with www but it worked because i added [NC,R=301,L] in the RewriteRule

.htaccess Redirection with parameters


Passing UI Entities between User Controls in MVP

Question: I am implementing the MVP pattern for the first time. My Application is a wizard. There is one single form and there are more than one User controls that are embedded into it.
Each control is a view and each view has a presenter. I am trying to implement the Passive MVP pattern. The presenter is responsible for handling all the actions and updating the view.
The issue is passing the UI Entities. I want to pass the User Input from my first view to the second view as the second view needs to process on it.
All the Views are instantiated on the Win Form.
Any help will be highly appreciated.
Regards
Answer: You could create a class which holds all the entities you need.
when opening a new window you pass the class in the constructor and voila, your data has been transferred.
Comment: I have implemented the same. In this case I am creating an object and passing it to the parametrized constructor of the view.
But as my Main Form carries out all the navigation,
I am landing up in too many passes.
The first view talks to the Main Form about the
user input and the Main Form then talks to the
second view about the same.
If tommorrow I feel like adding another layer,
 say a Manager then it increases the headache.
The first view will tell the manager,
the manager talks to the Main Form and then the
Main Form talks to the second view
Comment: Is there any other standard way to achieve the same?
Answer: i was thinking about the following scenario:
create an enumerable for holding the different views
public enum Views{
First,Second, Manager,Third,
}

Create an enumerable for your buttonstate
public enum ButtonState{Start,Next,Cancel,Back,}

create the class which will hold all the data
public class MyData
{
  //properties here
  //Also have a default constructor
  public MyData()
  {
  }
}

Then in your form use this new items:
Public Views MyViewState { get; set;}
Public ButtonState MyButtonState { get; set;}
Public MyData dataclass { get; set;}

Public Form1()
{
InitializeComponent();
MyViewState = Views.First;
MyButtonState = ButtonState.Start;
dataclass = new MyData(); //mostly at startup your class data is empty ...
ControlViews();
}

Public void ControlViews()
{
    //Based on your Buttons you will do what each form is asked to do:
      switch(MyButtonState)
      {
       case ButtonState.Start:
        //Since this is your startup: you only need to show your next view and replace you MyViewState
        MyViewState = Views.First;
        ///code for showing your view
       Break;
       case ButtonState.Next:
        //Since this time you probably filled in data you need to know in which MyViewState you are
         Switch (MyViewState)
         {
          Case Views.First:
           //You want to keep your data
           ///Code for placing data into your dataclass
           //After replacing the code, you then need to do some calculations and open the next view
           ///Code for calculations and placing this data in the form
           ///Code for opening the second view
           MyViewState = Views.Second;
          Break;
           // you then need to do this for each MyViewState
         }
       Break;
      }
}

The advantage of using this kind of a system is that all your data remains in the class and you simply show/close your views.
That's a way of how i would counter this.


Multiway Array Aggregation

Question: I'm having trouble understanding how the calculations for multiway array aggregations work using the example used in https://docs.google.com/file/d/0B5Ju2x50v6l5X0p3WDEwNkNTVW8/edit at page 165.
Consider a 3-D data array ABC partitioned into 64 chunks with dimensions 40*400*4000.
It then goes on to say the size of each partition is therefore 10*100*1000? Where are they getting these numbers from?
Further on it says:

To avoid bringing a 3-D chunk into memory more than once, the
  minimum memory requirement for holding all relevant 2-D planes in chunk memory, according to the chunk ordering of 1 to 64, is as follows: 40 × 400 (for the whole
  AB plane) + 40×1000 (for one row of the AC plane) + 100×1000 (for one chunk
  of the BC plane) = 16,000+40,000+100,000 = 156,000 memory units.

I understand the calculation for the AB plane but I don't understand the reason why we only need to calculate for one row of the AC plane and then moreover only one chunk for the BC plane.
Comment: i know it is a 4 years old post but if someone can please further explain the question "I understand the calculation for the AB plane but I don't understand the reason why we only need to calculate for one row of the AC plane and then moreover only one chunk for the BC plane." thank you
Answer: This example is where  40x400x4000 are the dimensions of a 3d cube.
The chunk is 4x4x4 = 64 in this case.  This could be represented by:
40x400x4000 / 4x4x4  = 10x100x1000
The latter figures 10x100x1000 reflect the dimensions of each partition or chuck itself.  I'm working on a similiar problem for an assignment I have due in a couple weeks so I Hope I have it right and it helps.

Multiway Array Aggregation


Como passo um array de apontadores de estruturas para uma função?

Question: #include <stdio.h>
#include <stdlib.h>

#define NUM_NOTAS 5
#define TAM_NOME 20

struct Aluno{
 char nome[TAM_NOME];
 int numero;
 int notas[NUM_NOTAS];
};
void preenche(struct Aluno* lista[], int tam){
 int i;
 int j;
 for(i=0;i<tam;i++){
    printf("Nome:");
    scanf("%s",&(lista[i])->nome);
    printf("Número:");
    scanf("%d",&(lista[i])->numero);
    for(j=0;j<5;j++){
        printf("Introduza a nota %d:",j);
        scanf("%d",&(lista[j])->notas[j]);
    }
 }
}

int main(int argc, char** argv) {
 struct Aluno* lista[5];
 preenche(&lista[5],5);

 return (EXIT_SUCCESS);
}

Gostaria de saber como é que passo struct Aluno* lista[5]; para a função preenche, porque da maneira que estou a fazer a função não lê o array.
Answer: Eu acho que o que você que r na verdade é isso:
#include <stdio.h>
#include <stdlib.h>

#define NUM_NOTAS 5
#define TAM_NOME 20

struct Aluno {
 char nome[TAM_NOME];
 int numero;
 int notas[NUM_NOTAS];
};

void preenche(struct Aluno lista[], int tam) {
    for (int i = 0; i < tam; i++) {
        printf("\nNome:");
        scanf("%s", lista[i].nome);
        printf("\nNúmero:");
        scanf("%d", &lista[i].numero);
        for (int j = 0; j < NUM_NOTAS; j++) {
            printf("\nIntroduza a nota %d:", j);
            scanf("%d", &lista[i].notas[j]);
        }
    }
}

int main(void) {
    struct Aluno lista[2];
    preenche(lista, 2);
    printf("\n----------------------");
    for (int i = 0; i < 2; i++) {
        printf("\nNome:");
        printf("%s", lista[i].nome);
        printf("\nNúmero:");
        printf("%d", lista[i].numero);
        for (int j = 0; j < NUM_NOTAS; j++) {
            printf("\nNota %d:", j);
            printf("%d", lista[i].notas[j]);
        }
    }
    return (EXIT_SUCCESS);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que não tem porque ter esse ponteiro. E se tem, precisaria alocar memória para ele. Aí basta passar a própria variável que já é um array (na verdade é um ponteiro no fim das contas). Dá pra simplificar fazendo assim e resolve o que precisa.
Resolvi alguns outros pequenos problemas. E mandei imprimir o resultado pra ver que está correto.
Se deseja usar um ponteiro, então use um ponteiro e não o array. Neste caso basicamente a mudança deve ser na declaração da variável que deve alocar memória de outra forma. Para um ponteiro para array precisa ter sentido nisso, o que não é o caso. Respondi com array porque é o que está na tag, e o código parece indicar que ele é importante, enquanto que o ponteiro não.
Comment: Mas o meu objectivo é passar como apontador, nesse caso o que teria que fazer?Porque a minha dúvida é trabalhar em estruturas com apontadores e gostava de perceber.
Comment: @ppfernandes Mas qual o motivo que quer passar como ponteiro? Não parece ter nenhum, o que está criando uma complicação desnecessária.
Comment: Sim eu sei mas isto é um exercício(de uma ficha) que precisa de ser feito dessa maneira mas já o consegui fazer obrigado pela ajuda.Quer que passe a minha resolução para o site?
Comment: @ppfernandes Quem pediu para fazer o exercício não está sendo razoável e está induzindo você aprender coisa errada. Eu tenho quase certeza que a solução está errada, apesar de aparentar que funciona. Funciona porque é um exercício simples que tem um uso de memória muito controlado, se for fazer a mesma coisa em outro código vai dar erros graves. Eu vivo dizendo que estar certo e funcionar são coisas bem diferentes. Para apender deve fazer o certo. Isto foi o que eu te mostrei. Além disso não tem na pergunta o requisito do exercício que deveria ter uma fundamentação para o pedido.
Answer: Basta trocar o preenche(&lista[5],5); por preenche(lista, 5);.
Ah, acho que no seu scanf("%d",&(lista[j])->notas[j]); você queria na verdade scanf("%d", &(lista[i])->notas[j]);. Ou seja, usou j ao invés de i.
Comment: Ao colocar dessa forma, lista[5] não entra na função.Simplesmente lê lista como um e não um array.
Comment: @ppfernandes Mas não é dessa forma que eu disse que é para colocar. É para colocar apenas `lista`, e não `lista[5]` e nem `&lista[5]`.
Comment: Sim eu usei a sua maneira mas dessa maneira não passa o array.Veja o print acima devia de aparecer lista[0],lista[1],.. e não só *lista.
Comment: @ppfernandes Acho que o seu problema está no `scanf`. Veja essa pergunta: http://pt.stackoverflow.com/q/137262/132


How to draw point to a QGraphicsView at run time without clearing the previous drawn points?

Question: I am new to Qt, How to draw point to a QGraphicsView at run time without clearing the previous drawn points? I have implemented a simple app which draw points without using timer. I want to update this using timer. How to do this? Please help.
<code>     QApplication a(argc, argv);
     QGraphicsScene scene(0,0,640,480);
     QGraphicsView view(&scene);
     QPen pen(Qt::black);
     int x = 0;
     int y = 0;

     double rad = 1;
     while(y < 640)
     {
        scene.addEllipse(x-rad, y-rad, rad*2.0, rad*2.0, QPen(), QBrush(Qt::SolidPattern));
        x++;
        y++;
     }

    view.show();
    return a.exec();
</code>
Comment: u mean with the help of timer u want to draw points...
Comment: i.e after each specific interval u want to draw point
Comment: yes. I need to update the GUI every second without clearing the previous drawn points
Comment: then implement timer for this..
Comment: but in timer function, I cudn't update the GUI. I am stuck in it. Cud u plz help me
Comment: can u provide the code for timer function...'
Comment: QTimer timer;
    QObject::connect(&timer, SIGNAL(timeout()), &scene, SLOT(updateStatus()));
    timer.start();
Comment: What I have to be write inside updateStatus?
Comment: write ur code for drawing points...
Comment: yes it works :) it was due to my aware of CPP calls
Answer: Created the scene, view and pen as member variables of MainWindow class and initializes in its constructor.
Call timer function from main.cpp
<code>    MainWindow w;

    QTimer timer;
    QObject::connect(&timer, SIGNAL(timeout()), &w, SLOT(updateStatus()));
    timer.start(0);
</code>
In MainWindow.cpp created a slot as shown below.
<code>void MainWindow::updateStatus()
{
    m_scene->addLine(m_x,m_y,m_x,m_y,*m_pen);
    m_x++;
    m_y++;
}
</code>
Now it works fine.
Answer: Write your code for drawing points in the slot of timer.


Content Screen Localization Google Sign-in

Question: I'm trying to find out how to translate the Google Sign-In screen for my application.
In the Google developer console you can enter different values for the "Consent Screen" which is the information displayed in the authorization screen while trying to log with your Google account in your web application.
There is no language options and I need to specify a different name (in other language) as well as localized Terms of use or Policy (and even the logo sometime).
How do I do that?
Answer: AFAIK, the end user will be presented with a localized signin and consent screen, depending on the language settings of his/her account.
I don't think it is possible to enter different URLs for policy/terms of use and/or for the name of the app. The only option i see is to enter use another domain name, with different credentials and configure a completely different consent screen.


How to make M2E eclipse plugin understand Bundle packaging

Question: I'm almost new with Osgi.
I'm using Eclipse 3.6 Helios for building my first Felix Bundle but find out that M2E don't understand bundle packaging...
Project build error: Unknown packaging: bundle

Project build error: Unresolveable build extension:
Plugin org.apache.felix:maven-bundle-plugin:2.0.0 or one of its dependencies could not be resolved:
Failed to collect dependencies for org.apache.felix:maven-bundle-plugin:jar:2.0.0 ()

As I done google searches, it was an error in Maven 2 but fixed in Maven 3 with M2E using.
Also, I'm using Window XP and under a proxy, which I think I sussefully config it, other connections in Eclipse work fine...
So I don't know how to get M2E understand bundle packaging ?
Answer: Using these settings, import the maven project.  If there are missing connectors (which links maven goals and eclipse plugins), the 'Next' button should be enabled.  Do Next and auto-resolve the connectors to install tycho plugins.  From now on, your project will have a Plugin nature.
P.S Be sure to at least have one class to compile in the project or maven-bundle-plugin will complain.
<packaging>bundle</packaging>
<build>
<plugins>
    <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>2.3.7</version>
        <extensions>true</extensions>
    </plugin>
</plugins>

Comment: +1 for the hint about connectors. I found that the option to search for them is also available as a quick fix: right-click the problem marker in the POM (next to the 'execution' tag), choose quick fix and look for the option to find connectors.
Answer: Justy FYI, ebelanger's answer above led me down the right direction. If you're not seeing the eclipse popup prompting for resolving connections, you need to add the parent pom that declares the plugin to eclipse.
In my case I had a child pom project I was importing into eclipse (but not the parent pom). Note that the actual plugin decleragion for maven-bundle-plugin was in the parent pom, not the child pom eclipse was aware of.
With just the child imported, Eclipse's build problems panel showed the errors about not being able to find the maven-bundle-plugin dependency, but the "quick fix" option after right clicking on the error in the problems panel was greyed out.
Importing the parent project into eclipse caused it to pop up the prompt asking for eclipse plugin connectors to install to support the maven-bundle-plugin.


Filtro com Data e Hora especifica das ultimas 24h

Question: Estou com a seguinte situação:

Preciso exibir todas as ordens de serviços lançadas a partir das 07h da manhã do dia anterior, até as 07h da manhã do dia atual. Consigo fazer isso quando quero retornar as ordens de serviços lançadas nas ultimas 24h a partir do horário atual, porem como disse antes, preciso que seja filtrado num horário especifico.

SELECT SERIE, NUMERO, DATA
FROM ORDENS
WHERE
DATA >= Convert(varchar(10), GETDATE() - 1, 120) AND
DATA < = Convert(varchar(10), GETDATE() - 1, 120) AND

Comment: Se você alterar para isso funciona? `DATA >= '2022-04-12 07:00:00'   AND
DATA <=  '2022-04-13 07:00:00'`. Se funciona é só tratar os dados informados no `where`
Comment: Funciona, mas não serve para o que preciso, pois esta visualização tem que ser gerada de forma automática e diariamente. A intenção é não ter interferência de usuário para alterar esta data todos os dias.
Comment: Exatamente isso, agora é só adaptar seu código para que seja montado isso. A hora é fixa, a sua única variante é a data, sendo que é a data atual -1. Dá uma olhada na [documentação da MS sobre GetDate](https://docs.microsoft.com/fr-ca/sql/t-sql/functions/getdate-transact-sql?view=sql-server-ver15)
Comment: Obrigado Leandro, a documentação serviu muito para meus estudos.
Answer: Segue uma sugestão para testes utilizando a função SmallDateTimeFromParts para obter a data atual as 7:00 e depois a função DateAdd para obter o dia anterior as 7:00:
declare @DataHoraFim as datetime2 =
    smalldatetimefromparts(year(getdate()), month(getdate()), day(getdate()), 7, 0);
declare @DataHoraIni as datetime2 =
    dateadd(day, -1, @DataHoraFim);

SELECT SERIE, NUMERO, DATA
FROM ORDENS
WHERE DATA BETWEEN @DataHoraIni and @DataHoraFim

Comment: Muito obrigado, funcionou perfeitamente.


Derivation of bias-variance decomposition of error

Question: I am repeating the derivation from slide #12 of http://www.cs.cmu.edu/~wcohen/10-601/bias-variance.pdf
$$E_{D,e}[(f - \hat{y})^2] = E_{D,e}[((f - h) + (h - \hat{y}))^2]$$
$$E[(f - h) ^ 2 + (h - \hat{y}) ^ 2] - 2 (E(fh) - E (f\hat{y}) - E(h^2) + E(h\hat{y}))$$
Basically the following term is claimed to be equal to 0 and I don't understand how it is 0:
$$2 (E(fh) - E (f\hat{y}) - E(h^2) + E(h\hat{y}))$$
Points of confusion:

It seems to claim that
$$E(f\hat{y}) = E(h\hat{y})$$ and thus the two terms are cancelled out. If so, how are they equal? One has actual function f, while the other has the model function 'h'.
Similarly how do other terms cancel out?

Please provide both mathematical proof as well as intuitive understanding as I have wasted hours trying to understand this on my own.
Answer: First up, $h$ is not arbitrary, it is defined on the same slide as
$$h=E[h_D(x)]=E[\hat{y}]$$
Note that since it's an expectation, it is a number, not a function.

Next, you have picked the wrong pairs to cancel out. The claim is a bit different:
$$E[fh] = E[f\hat{y}]$$ and $$E[h\hat{y}] = E[h^2]$$
This follows directly from the definition of $h$. E.g.,
$$E[fh] = E[f \cdot E[\hat{y}]] = E[f\hat{y}]$$
... which uses the fact that $f$ is deterministic and $E[E[z]] = E[z]$. The second identity is proven likewise:
$$E[h\hat{y}] = E[E[\hat{y}] \cdot \hat{y}] = E[E[\hat{y}] \cdot E[\hat{y}]] = E[h^2]$$
In summary, the trick works for the specifically chosen $h$. In general, of course, it won't hold.
Comment: Thank you for the clarification. If possible, could you also provide an intuitive explanation and/or derivation for E[f. E[y^hat]] = E[f y^hat]? I don't quite see why expectation of (f * expected value of predictions) would necessarily be equal to the expected value of (f * predictions) unless f can be taken outside the E[].


Why doesn't integration by substitution work in this case?

Question: I am asked to solve $\int_0^\frac{\pi}{4}\tan x\, \mathrm{d}x$.
This is what I did:
$$
\begin{align}
&\int_0^\frac{\pi}{4}\tan x \,\mathrm{d}x&\\
= {} &\int_0^\frac{\pi}{4}\frac{\sin x}{\cos x}\, \mathrm{d}x&\\
= {} &\int_0^\frac{\pi}{4}\sin x\frac{-1}{-\cos x} \,\mathrm{d}x&\\
= {} &-\int_0^\frac{\pi}{4}\varphi'(x)\frac{1}{\varphi(x)} \,\mathrm{d}x &\text{where $\varphi(x):=-\cos x$} \\
= {} &-\int_{\varphi(0)}^{\varphi(\frac{\pi}{4})} \frac{1}{z} \,\mathrm{d}z \\
= {} &-\int_{-1}^{-\frac{1}{\sqrt{2}}} \frac{1}{z}\, \mathrm{d}z \\
= {} &\Big[\ln z\Big]_{-1}^{-\frac{1}{\sqrt{2}}} \\
= {} &\ln \left(-\frac{1}{\sqrt{2}}\right) - \ln (-1)
\end{align}
$$
And this is where I am stuck, because the solution is definitely not a complex number. I know the correct answer (it's $-\ln\left(\frac{1}{\sqrt{2}}\right)$, my problem is that I don't know where I made a mistake.
Comment: A primitive of $1/x$  is $\ln(|x|)$.
Comment: you've forgotten negative sign at the pre-last  line, and l$n|x|$
Answer: It turns out that $\displaystyle\int\frac1z\,\mathrm dz=\log|z|$, not $\log z$.
Answer: You have lost a $-$ sign, so you should actually get
$$\ln\left(-1\right)-\ln\left(-\frac{1}{\sqrt{2}}\right)$$
And now, you can use the fact that
$$\ln(a)-\ln(b)=\ln\left(\frac{a}{b}\right)$$
to reach the desired result:
$$\ln\left(-1\right)-\ln\left(-\frac{1}{\sqrt{2}}\right)=\ln\left(\frac{-1}{-\frac{1}{\sqrt{2}}}\right)=\ln\left(\frac{1}{\frac{1}{\sqrt{2}}}\right)=\frac{\ln 2}{2}$$
It works, because the logaritm of a negative number (the main branch) $-x$ (where $x>0$) is $\ln(-x)=\ln(x)+i \pi$, and in your case, the $i\pi$'s will cancel each other out. They would not cancel out if you were trying to compute, for example $\int_{-2}^{2} \frac{1}{x} \mathrm{d}x$. In this case, the complex result can tell you that you did something wrong.
But you can avoid the mess with the complex numbers by simply saying that $\int \frac{1}{x} \mathrm{d}x=\ln|x|$, as José Carlos Santos mentioned it already.
Comment: @NajibIdrissi The main branch of $\log$ is usually defined such that its imaginary part is in the interval $(-\pi,\pi]$ (see e.g. [wikipedia](https://en.wikipedia.org/wiki/Complex_logarithm#Definition_of_principal_value)). Therefore, $\log(-1)$ is perfectly well-defined and equal to $i\pi$. More generally, the main branch of $\log$ is well-defined on negative numbers and equal to $\log(-x)=\log x+i\pi$.
Comment: @NajibIdrissi the main branch isn't *continuous* there, but it's perfectly well defined.
Comment: What do you mean by $\ln(-1)$?
Comment: @NajibIdrissi What do you mean? I think you know the answer. It's either a complex number or just "a formal thing" which will lead you to the desired result.
Comment: The main branch of the logarithm is not defined on negative numbers...
Comment: @NajibIdrissi my technical term might not be good. How would you call it then? Please, feel free to edid my answer as well.
Answer: You have
$$
\int_a^b\frac{1}{z}\,dz
$$
with $a<0$ and $b<0$. The antiderivative to use is $\ln(-z)$, which is a function defined on $(-\infty,0)$.
You can avoid the problem by writing instead
$$
\int_0^{\pi/4}(-\sin x)\frac{-1}{\cos x}\,dx=
\int_0^{\pi/4}\varphi'(x)\frac{-1}{\varphi(x)}\,dx
$$
where $\varphi(x)=\cos x$. For $x=0$ we have $\varphi(x)=1$; for $x=\pi/4$ we have $\varphi(x)=1/\sqrt{2}$, so the integral becomes
$$
\int_1^{1/\sqrt{2}}-\frac{1}{z}\,dz=
\int_{1/\sqrt{2}}^1 \frac{1}{z}\,dz=
\Bigl[\ln z\Bigr]_{1/\sqrt{2}}^1=-\ln\frac{1}{\sqrt{2}}=\ln\sqrt{2}=
\frac{1}{2}\ln2
$$


Consumable IAP can't be purchased multiple times

Question: I sell multiple consumable IAP in an iOS application, but I can only purchase each consumable once.
When I try to purchase it a second time, this message pops up:

Is it related to the sandbox environment? The status returned from
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions

is SKPaymentTransactionStatePurchasing. How should I handle it?
Comment: It looks like you have define your product as a non-consumable.
Comment: Nope. I've checked this.
Answer: I wasn't calling
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];

appropriately.
Comment: Elaborate more what was missing.
Comment: @khunshan You have to call the mentioned function, after you have successfully purchased the good.
Comment: yea i do. the issue is coming when i press purchase and close the app. so the purchase is in progress and this method was not called ever. i believe the transaction was never rolled back and this message started appearing.
Comment: @khunshan do you know how to roll it back? Without having to create an new product?


Getting users' ip using nodejs and saving to database

Question: I have an issue. I want to store the ipv4 of a user in my database. For that I am using this external API called https://ipapi.co/json.
I am trying to implement the system. I have thought of a solution and it goes this way - On the website, as soon as a user visits a page, an ajax get request is made to that API which fetches the user's ip and stores it in an input type= hidden to which I can get access in req.body and store in the database.
In order to avoid the user use chromedevtools to change that attribute I can add oncontextmenu="return false" onkeydown="return false;" onmousedown="return false;" to the body so that user cannot get access to the chrome devtools.
I am not sure if this will work out. Can you guys please suggest.
Another doubt that I have is that is the ajax request is made by the user or by the server? If the server makes the request then IP will be of the server which is useless. Please help!
Comment: You can't stop a user from submitting false/fake information. Getting the request [network ip](https://stackoverflow.com/questions/10849687/express-js-how-to-get-remote-client-address)
Answer:  once a user gets into your site a get request method is been done . And in the request object you can get the ip
Comment: I want the ipv4 as I told. Is that possible?
Comment: https://www.digitalocean.com/community/questions/how-do-i-forward-client-ip-instead-of-proxy-ip-in-nginx-reverse-proxy
Comment: proxy_pass_header  Set-Cookie;

proxy_set_header   Host               $host;
proxy_set_header   X-Real-IP          $remote_addr;
proxy_set_header   X-Forwarded-Proto  $scheme;
proxy_set_header   X-Forwarded-For    $proxy_add_x_forwarded_for;
Comment: thats all you need


How i can find all unique sets of positions of elements in matrix in C?

Question: I need to solve the following problem for a 5×5 matrix, but to explain I will use an example with a 3×3 matrix:
A = { { 1, 3, 2 }
     ,{ 3, 2, 3 }
     ,{ 0, 4, 5 } };

I need to find all distinct sets of 3 (because the matrix is 3x3)  positions sharing no row or column with the others, compute the sum of elements of A for each set of positions, and print the minimum of these sums.
Position = (0,0),(1,1),(2,2) sum = 1+2+5 = 8
           (0,0),(1,2),(2,1) sum = 1+3+4 = 8
           (0,1),(1,0),(2,2) sum = 3+3+5 = 11
           (0,1),(1,2),(2,0) sum = 3+3+0 = 6
           (2,0),(1,1),(0,2) sum = 0+2+2 = 4
           .
           .
           .

(I think you understood the main principle).
So the output must include:   (2,0),(1,1),(0,2)  minimal sum = 4
Remember:  I actually need to do it for a 5×5 matrix.
Comment: So you want to consider diagonals too, and diagonals that "wrap". When you iterate, take the iterators modulo 3 (or 5) to index.
Comment: Can you show us what goes wrong with your attempt? How did you try implementing it?
Comment: I think OP is asking for an algorithm that generates all possible combinations of index-pair triplets s.t. all row indices and column indices are not equal.
Comment: I think your example solution is wrong, (0,1) == 3, not 1. (0,0) is 1. The minimal sum is (2,0),(1,1),(0,2) =2+2+0=4
Comment: @mch yes you're right thank you
Comment: @Fearless_Wolf:  I made some edits to your question in a way that I hope clarifies it and makes it more likely that other people who have similar questions and search SO will find it. Please take a look and re-edit appropriately if I've inadvertently altered your meaning or intent (in which case, I apologize for the misunderstanding and I'd probably want to revisit my answer below). I felt pretty sure based on the discussion here and the other answer that my understanding was accurate.
Comment: @ThomasKammeyer  i think, i did it thank you , for your edits
Answer: Here's another suggestion:  all of the sets of locations in the matrix that you want to use can be represented as permutations of an identity matrix whose "1" entries tell you which matrix elements to add up.  You then take the minimum over the set of sums for all of the permutations.  You can represent a permutation with a simple array since there are only N elements equal to 1 in a permutation of the NxN identity matrix.  So call that array p where p(i) tells you which column on the i'th row to use.
So the fundamental observation here is that you want all permutations of the NxN identity matrix, and you can represent these as permutations of (0,1,...,N-1).
Pseudocode might look like:
Given: an NxN matrix (2-D array), M, for which you want the minimal sum of N
       elements with no subset falling on the same row or column

minsum = N * max entry in M (just initialized to guarantee >= min sum sought)
foreach permutation p of (0,1,...,N-1):
   sum = 0
   for i = 0:N-1:
      sum += M(i,p(i))
      if sum >= minsum: break; # (if we already know this isn't a new min, move on)
   if sum < minsum: minsum = sum
print("minimum sum = ", minsum)

Adding a bit of code to remember a particular set of locations that add up to the minimum is left here as an exercise for the reader.  Note that this gives up on any permutation as soon as it's not going to be a new minimum sum.
For an NxN array, there are N! permutations, so in practice this gets expensive fast for large N (not your current problem at N = 5).  At that point, deeper dynamic programming techniques to quit early on partial results or avoid recomputing subset sums by using, say, memoization would be applicable and desirable.
Most other algorithms are going to do the same basic work in some way that may or may not look obviously similar in code.  I like this approach because it has a nice mapping onto a fairly straight-forward understanding in mathematical terms and you can readily identify that what makes it get expensive quickly as N grows is the need to calculate a minimum over a rapidly-expanding set of permutations.
Algorithms to compute all permutations of an array are pretty easy to come by and you get one for free in C++ in the function next_permutation, which is part of the STL.  My recommendation is to google "list all permutations" and if you need to work in a particular programming language, add that to the query as well.  The algorithm isn't terribly complicated and exists in both recursive and iterative forms.  And hey, for the 5x5 case you could probably statically list all 120 permutations anyway.
Answer: A functional, albeit naive, way to do this is to use 6 for-loops (5 nested). Loop from 0 to 2 with the top loop storing its iteration # in an int (called firstRow for example). Similarly the second loop will store firstCol. The third loop will be used to store secondRow so you'll need to continue if secondRow == firstRow. For the last two loops you'll need to check against the indeces for the other two. In the innermost nested loop, call your findSum function with the 3 coordinate pairs.
testCoords(*arr1, *arr2, *arr3)
{
    #get the sum
}

#algorithm defined for n = 3
mySearch(n)
{
    int coord1[2], coord2[2], coord3[2]; #assume 3by3
    int minSum = n * MAX_VAL, obsSum;

    for (int r1 = 0; r1 < n; r1++)
    {
        coord1[0] = r1;

        for (int c1 = 0; c1 < n; c1++)
        {
            coord1[1] = c1;

            for (int r2 = 0; r2 < n; r2++)
            {
                if (r1 != r2)
                {
                    coord2[0] = r2;

                    for (int c2 = 0; c2 < n; c2++)
                    {
                        if (c1 != c2)
                        {
                            coord2[1] = c2;

                            for (int r3 = 0; r3 < n; r3++)
                            {
                                if (r1 != r3 && r2 != r3)
                                {
                                    coord3[0] = r3;

                                    for (int c3 = 0; c3 < n; c3++)
                                    {
                                        coord3[1] = c3;

                                        obsSum = testCoords(coord1, coord2, coord3);
                                        if (obsSum < minSum)
                                        {

                                            minSum = obsSum;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}

This will be fine for small arrays such as n=3 or n=5, but the number of iterations quickly gets ridiculous as its n^(n*2). For example, even with 5x5 matrix you'll do 10 million iterations (not too mention a long winded algorithm). A more dynamic algorithm or perhaps a tree implementation is probably a good fit here. For example, a recursive approach could find one index pair (which eliminates a row and column), then calls itself with the resultant (n-1)*(n-1) 2d array -- as so:
int minSum = n * MAX_VAL;

coordSearch(int **matrix, n)
{
    int thisCoord[2];

    if (n == 1)
    {
        return matrix[0][0];
    }

    else
    {
        for (int i = 0; i < n; i++)
        {
            thisCoord[0] = i;
            for (int j = 0; j < n; j++)
            {
                thisCoord[1] = j;

                ##need to update the matrix s.t. row represented by i is removed and col represented by j is removed
                ##ill leave that up to you -- assume its called updatedMatrix

                updatedMatrix = reduce(matrix, i, j);

                return matrix[thisCoord[0], thisCoord[1]] + coordSearch(updatedMatrix, n-1);
            }
        }
    }
}

int main(void)
{
        #have some 2d structure that is n * n

        int minSum = n * MAX_VAL, obsSum;
        int row, col;

        for (int i = 0; i < n; i++)
        {
            row = i

            for (int j = 0; j < n; j++)
            {
                col = j;

                updatedMatrix = reduce(matrix, row, col);
                obsSum = coordSearch(updatedMatrix, n- 1);
                if (obsSum < minSum)
                {
                    minSum = obsSum;
                }
            }
        }
}

For a 3x3 2d array, the recursive approach will look at the 9 coordinate pairs at the top level, then in the next level we will be dealing with a 2x2 2d array so we will only consider 4 coordinate pairs, then in the bottom level we just return whichever value resides in our 1x1 "2d array". Complexity is n^2 * (n-1)^2 * .. * 1. Keep in mind though, that each "step" requires updating the matrix which is a operation dense procedure.
Comment: With the recursive method , could you please say me how i can do that ?(with more details please)


Javascript Equivalent of PHP's regex for punctuation

Question: I'm using the following line of PHP to remove punctuation from strings:
$key = preg_replace("/\p{P}/u", "", $key);

Does anyone know how to do the same thing in Javascript/jQuery?
I know you can use jQuery's replace() like PHP's preg_replace(). I just don't know what regular expression to use.
Comment: javascript doesn't have expression for punctation. this may help http://stackoverflow.com/questions/7576945/javascript-regular-expression-for-punctuation-international
Comment: did you read this question? http://stackoverflow.com/questions/4328500/how-can-i-strip-all-punctuation-from-a-string-in-javascript-using-regex
Comment: @Decker - i need to make sure the expressions match exactly the same. i think the second answer on there might work for me. thanks.
Answer: Something like this :

Edit :
It seems that Javascript is not PECL compatible, so the p{P} will not work.
Comment: JavaScript regexes do not support `\p`.
Comment: It seems that, as the others stated, javascript is not pecl compatible, so this will not work. You can replace all non alphanumeric caracters but that may not give you the desired result
Comment: i think that's what all end up doing. that way i know php and javascript will produce the same results. Thanks!
Answer: In most cases the regular expressions will be the same in Javascript and in PHP. So, if yo have a regexp that works in PHP it's most likely going to work the same way in JS.  The main difference is that in JS you don't need to wrap (though you can if you want to) the regexp in a quotes. You can just call replace on the String directly like so...
myString.replace(/abc/i, "123");

Keep in mind that this doesn't actually alter the value of myString... it just returns the replaced version.
Comment: To get the actual behaviour of `\pP`, you'll need to use a bunch of Unicode ranges.
Comment: @alex, interesting... I'm not familiar with that command... entirely possible that my answer is completely useless for this particular example.


What shortcuts are there to figure out the major and minor scales that contain a set of multiple notes?

Question: What shortcuts are there to figure out the major and minor scales that contain a set of multiple notes?
e.g., Which major and minor scales contain: C,F,D ... or perhaps C and G#? ... or perhaps C, G, A#? (or, of course, if no scales fit the bill).
I am asking because I am starting to write melodies and would like to know how the pros here figure out the key AFTER THEY WRITE THE MELODY.
Comment: @MichaelCurtis I assume the reason for this and previous unusual questions can be found in Randy's profile, where he talks about developing a music teaching method.
Comment: But if you don't understand how music is either in or not in a key why do you expect that these melodies will be in a key to identify? That's why I asked: do you want to write melodies that are in keys?
Comment: "I am asking because I am starting to write melodies and would like to know how the pros here figure out the key" - if someone's *writing* a melody, don't they usually know what their tonal centre is? Once you know that, it's fairly straightforward to work out what the tonality is and choose an appropriate key signature. Doing it from a set of notes seems to make it a lot harder, especially as (as you say) some sets of notes won't be contained by any key.
Comment: @topomorto Is that how it works for you?
Comment: @topomorto - There's also figuring out the key/scale of a melody you didn't write, which is very useful when transcribing. Unfortunately, this comes with the complications of music still sounding tonal despite using all 12 notes of the chromatic scale (or, at the very least, an exotic scale like the double harmonic scale, a blues scale, or an octatonic scale), changing keys mid-piece, or simply being atonal. A further complication is changing the key but not the key signature; this is common in classical music.
Comment: I see you've clarified your question a bit - sorry, I initially understood your meaning as wanting to know the key while you are writing. I would still take the tonal centre as the starting point for working out the tonality, and then from that point think about what would be the most helpful key to use for notation.
Comment: You gave the motivation for the question, but not the motivation for composing. Are you trying or wanting to write melodies that are in keys? If so the more useful answer is not about matching tone sets to scale, but understanding the major/minor key tonal system.
Comment: @MichaelCurtis I want to figure out the key from the melody.
Comment: @MichaelCurtis Ah. Thank you. I had forgotten about that and deleted the info as it's not relevant to the questions. I'm no longer doing that (as of six months ago). My questions are solely for learning music theory.
Comment: When writing the melody, use a scale and a key you know.
Comment: @piiperi  Ok, so don't use any notes outside the key?
Comment: Key is not the same as scale. Key is more about tonal center than scale. There can be e.g. an occasional D chord with an out-of-scale F# note in a song that's in C major. What's important is where the home note is. But in any case, stick with the scale at first. Compose short snippets in different keys, so you'll get familiar with keys. Do one key a week or a month. Start with C major, no sharps or flats, home note C. At the end of the song, playing a C note should feel like being at rest at home.
Answer: I think that you might be approaching this the wrong way.
If you are writing a melody then just write it.  The "tonal centre", if it has one, should become obvious once you have written it.
Taking the approach that you need to know what key contains the notes you intend to use seems to be applying restrictions before you have even started.  It might be useful if you are improvising in a group but much less so when you are composing something.
Answer: There are many scales, both major and minor, that contain, as your example, C F and D. Knowing which they are isn't going to be a great deal of help in writing your melodies. If anything, your hearing will guide you to the next note/s - which may - or may not - still belong to that scale you considered. It's somewhat of a red herring.
A lot of pieces don't stay in one key (with one set of scale notes) from top to bottom anyway, so even if you know the cast iron answer - which will be more than one key, so confusing the issue anyway - it won't be of much help if your melody modulates.
It may be useful to think initially in a partcular key, with its particular scale notes. The melody will then have a 'home' thus somewhere to start from and finish at, sonically. The way to use that information is to glean it in the first place. Know your scales! All of them - major, harmonic/melodic/natural minors.
What you're almost saying is here's the answer, what's the question? Go with your ears, and work out what the notes are after. That will give you the key/scale notes, most likely when you feel the melody has come to rest. then might be a better time to 'establish' a key, then the next part may be easier to write in that knowledge. But maybe not. That's music for you!
Comment: To figure out the key afterwards, knowing which notes constitute which key is not so important as knowing which chord/harmony is the one which makes the piece feel it's arrived at rest, at home, rather than just having a little rest on its way there.
Comment: I thought it was obvious, but not, that figuring out the key would come after as the question is 'what key fits the notes' and not 'what notes can I use for each key'.

I've seen many questions where people post a melody and ask what the best key is soI think this is a common problem.
Answer: You're really posing two questions:
How can you identify scales that contain specific notes
The answer is to learn the order of sharps and flats in key signatures.
Sharp signatures have the order F, C, G, D, A, E, B and flat signatures are the reverse: B, E, A, D, G, C, F.  Knowing that, you can look at a set of notes and know which major and natural minor scales will contain them.
The first example, C-F-D is pretty straightforward.  The first sharp in sharp key signatures is F, so you can't be in any of the sharp keys with an F natural.  The fourth flat is D, and you've got a D natural - you can't have four or more flats.  That leaves you with four keys: C (no sharps or flats), F, Bb, and Eb (1, 2, and 3 flats)
Your third example is C-G-A#.  Because all key signatures with A# also have C# and G#, there aren't any sharp keys that fit.  But what if it's the enharmonic Bb?  All flat key signatures have a Bb, and any with four or fewer flats have C and G natural... so you could be in a key signature of F, Bb, Eb, or Ab.
Your second example, C-G# can't fit sharp key signatures, but it can fit flats if it's the enharmonic Ab.  But this brings up something else: there are more scales than just the major and natural minor - C and G# are both in the A harmonic minor, and the A melodic minor.  And a bunch of other scales as well.  But it's not really worth working out a method for identifying all of the scales because of your second question:
How do you figure out the key after writing the melody?
Listen to it.  Does it sound like it's come to a full stop at the end?  Almost all melodies do.
That full stop is the tonic.
So let's say your melody has F, Bb and C# notes in it, and your last note is D.  D is the tonic, which means you're in the key of D something.  It's not D major because of the F natural, and it's not D natural minor because of the C#.  That F note gives you a minor feeling (it's the b3 of D) so it's some minor scale.  Because all the Bs are flat, it's not the melodic minor.  The most likely choice is the D harmonic minor scale.
That's not the only possibility.  If you have a bunch of G# notes you could be in the Hungarian minor (also called the Gypsy minor).  But that's the essence of how you figure it out: identify the tonic, examine the third up from that tonic to determine if it's a major or minor scale type, and if you want to narrow it down to a specific scale, start eliminating possibilities based on the notes used.
Comment: So you seem to be saying there's no shortcut - you have to memorize all keys and notes?
Comment: @RandyZeitman you have to memorize something - it might as well be something useful like key signatures.
Comment: I've heard several major-key pieces whose melodies end on the mediant (but whose last chord is the tonic).
Answer: The answer is really the same as my answer to your previous question. Say you have a melody that uses the notes D-E-A-B. You transpose the notes up by half-tone steps, or write down the following table, to check which transpositions fit into C Major:

     C - D - E F - G - A - B C - D - E F - G - A - B
 +0      x   x         x   x                          <-  OK
 +1        x   x         x   x
 +2          x   x         x   x
 +3            x   x         x   x                    <-  OK
 +4              x   x         x   x
 +5                x   x         x   x                <-  OK
 +6                  x   x         x   x
 +7                    x   x         x   x
 +8                      x   x         x   x
 +9                        x   x         x   x
+10                          x   x         x   x      <-  OK
+11                            x   x         x   x

The transpositions of the melody notes that fit into C Major are 0, +3, +5 and +10. So to get the major keys that contain the notes, we transpose C Major down by those intervals:

C Major -  0  ->  C Major / A minor natural
C Major -  3  ->  A Major / F# minor natural
C Major -  5  ->  G Major / E minor natural
C Major - 10  ->  D Major / B minor natural

For melodic and harmonic minor keys, you'd have to use a separate table.
(You can of course use another key than C Major as the basis for the calculation, e.g. if you want to do it without writing down the table and there's another key that you're more familiar with, or you want to go straight to the minor keys.)
Answer: You have two question conflated into one: finding a suitable major/minor scale for a group of tones, and how the "pros" find a key of a melody.
Those are not the same thing.
For the first question treat major/minor scale as synonymous with key signature and you should be able to step up the accidentals of the various key signatures to find if the set of tones fit a major/minor key...

C,F,D ... or perhaps C and G#? ... or perhaps C, G, A#

The first sharp for key signatures with sharps is F# that doesn't match the set C,F,D all other key signatures with sharps going up the circle of fifths will contain an F# so none of the sharp key signatures will match the set. Going in the flat direction we go Bb, Eb, Ab, Db when we get to the Db we have a tone that doesn't fit the set and so we stop and know the set can't fit any key signature with 4 or more flats. That gives us key signatures of 0 sharps/flats, 1 flat, 2 flats and 3 flats which will match the set of tones C, F, D.
Things get complicated when considering minor scales.
C, G# won't fit a key signature with sharps (and of course not flats), because to get to a G# we will first hit upon a C#, i.e. there isn't a key signature with G# that doesn't have a C#. However, G# would be used for an A minor scale. A quick way to try figuring this out is ask if one of the tones could be a leading tone. A# could be the leading tone to A minor and the C would then be the mediant, the A minor scale could be used. In the case of C, G, A# non of the tones can be a leading tone for a scale containing the other tones: C leading tone to Db minor, but G and A# don't fit, and so on with the others.
Things are further complicated when you realize that every note of a melody does not need to fit a scale. In the case of C, G, A# the scale to use might be C major where the A# might be the chromatic lower neighbor tone leading up to a B. But we can't figure that out from just a list of tones. We would need to see the actual melody.
This makes a nice segue into the second question about finding a key. Both questions seem to be generally about figuring out the tonality of a melody. But you can't do that simply from a list of tones. Sequence, repetition, rhythm, etc are all essential for perceiving tonality. If someone presented a list of melody tones D, E, F#, G, A, B, C, you simply cannot tell what key the melody is in. That list of tones could be used for multiple keys: C major, G major, E minor, etc. or it might not be in a key at all! You must see the actual melody and understand what it is doing in terms of major/minor harmony (implied harmony if there is only a melody.)

EDIT
Just a quick addition to demonstrate how a list of tones will not be enough to determine a scale/key: consider this set: C, C#, D, D#, E, E#, F#, G, G#, A, A#, B, B# ...in what key or scale should is that set? Note the enharmonic spellings B# & C for a total of 13 tones in a major/minor system that uses a 12 pitch chromatic scale! Tones are not in melodic order but in ascending order from C. The answer is here.
Answer: The "circle-of-fifth" is a great tool for checking harmonic and melodic material. In short: Neighboring elements belong to a key, if you look at it as note names.
Check out the concept of "modal interchange", too, for notes/chords not belonging to a certain key, but being substituted into a melodic line or chord progression originating of closely related keys.
This way you can broaden the perspective if one note does not really fit in a certain key in the classical way.
Depending on style sometimes certain notes will not fit in a scale and only make sense in relating to a chord:
i.e. Blues:
 Improvising with a e-minor pentatonic (e g a b d ) over a E7 chord (e g# b d)  gives you a overall #9 - Sound (note g against g#) for example which adds a certain character to this style and defines it sonically.
So: What style do you want to write in?


exception floating parameter is not finite canvas

Question: I wrote this code but I have a problem in line 18
<code>    var c=document.getElementById("viewport");
    var ctx=c.getContext("2d");
    var imgData= new Image();
    imgData.src = "q.jpg";
    var length = imgData.length;
    var width = imgData.width;
    var img=ctx.createImageData(length,width);
    imgData.onload = function(){
        for (var i=0;i<length;i+=4)
            {
               .
               .
               .
                }
                imgData.data[i+3]=255;  //alpha
            }
        ctx.putImageData(img,10,10);
    };
    console.log(img .toString());
</code>
at This particular line
<code>var img=ctx.createImageData(length,width);
</code>
this is the exception that i get : floating parameter is not finite .
Answer: Your length & width vars are have invalid values when used in createImageData() because the image has not been fully loaded. That causes createImageData() to fail.
Instead:
<code>// declare length,width & img
var length,width,img;

imgData.onload = function(){

    // set the values when the image has been fully loaded
    length = imgData.length;
    width = imgData.width;
    img=ctx.createImageData(length,width);
</code>