Analysing data measured as proportional composition

Question: I have a data set on the proportional composition of marine substrate for different locations which I would like to compare. For example, one replicate transect within a location may be 50% sand, 25% seagrass, 25% rubble (there are 14 categories).
In general, how does one analyse such conditional proportional data, since each value for each variable (e.g. % sand) is dependent upon the other proportions?
If these were independent proportions I would consider an ordination (e.g. NMDS) to examine clustering of replicate transects with respect to locations, but is this possible with conditional proportions? and if so how do I treat the proportions (standardisation, distance measure etc.)?
Additionally, I am considering multiple regression to test whether site characteristics (substrate composition and location) influence the density of fish (no. individuals/square metre). Is this possible? or can someone suggest a suitable alternative?
When researching this question all I could find was information about variables measured independently as proportions - no help there!
Comment: I don't get why you dismiss an ordination (e.g., NMDS) for proportions (compositional data). You will get something similar with some typical transformations ("standardizations") of data matrices. I'm thinking of ecological abundance matrices (sites by species) where you make all sites "equally important" by dividing rows by row totals, i.e., sum of cells in each row = 1 (see default `wisconsin` transformation in vegan package in R as an example)
Answer: There is a very large literature on such data, since the 1980s at least usually called compositional.
http://en.wikipedia.org/wiki/Compositional_data
http://www.compositionaldata.com/
The largest single fraction of this literature is quite possibly in mathematical geology. Other applications are numerous. One is the study of expenditure budgets in economics.
Everyone agrees that the constraint that fractions sum to 1 (percents sum to 100) gives analysis a special twist. Hence there is one fewer piece of information than may at first appear. If you tell me 13 out of 14 fractions, the last follows from the constraint. Various transformations have been suggested for such data in the light of this. However, a common problem is that many observed proportions are zero (or undetectable).
Look at your local version of Amazon for texts, searching for "compositional data". I have not read
http://www.amazon.com/Analyzing-Compositional-Data-Gerald-Boogaart/dp/3642368085/
but it is likely to be fairly strong on what you should do and to be well linked to the rest of the literature.
In a way, there is no mystery here. Much more widely known is the case of two proportions which must sum to 1, such as fraction present and fraction absent or fraction survived and fraction not survived. Here it is not usually considered necessary to spell out that only one proportion need be analysed. Compositional data are just an extension of that.


How to discover what story the song is trying to convey?

Question: Someone said to me that the song Tempest from Beethoven is about someone in a hurry to get into a ship to travel. However, I didn't find anything on the internet about this story or any story. At that time, they also said the stories about other songs. How can I find these stories?
Comment: Well, I wouldn't come here without searching for it on some search engine. Also, as you should know, search engines don't have answers, but websites indexed do. Therefore, the answer has to be on some website like this.
Comment: @Matheus: Fair enough, but I just wonder what you would expect from an answer on a question as generic as "how do I find out what is the story behind a song". If the story is known, it's most likely google-able, if it's not you will get a personal opinion.
Comment: By "the song Tempest from Beethoven", do you mean the first movement (or maybe all 3 movements combined) of Ludwig van Beethoven's "Tempest" piano sonata?
Comment: At that day, they played "Beethoven Sonata No 17 'Tempest' Mov 3 Allegretto" before saying that, but I don't know if what they said relates just to this movement or the song altogether.
Comment: Sounds to me like the cart is in front of the horse.
Comment: Should the question be what song the story is trying to convey?
Comment: Is this an answerable question for this stack? It seems to me the answer is "google" (or your preferred search engine).
Comment: I was expecting some kind of website or books that I could find such information. For example, I would recommend janedoe-teas.com (hypothetical website not very known with everything about tea) if someone asked me about where to find something related with tea.
Comment: But, reading Laurence's answer, I guess I didn't find some story behind some songs because actually there aren't a story behind them. I just tried to look for the story behind Tempest and it was easy to find (and maybe this is what you are saying).
Answer: Sometimes (but not very often) a piece of music is consciously programmatic, literally describing a story.   Richard Strauss does this in his 'Don Quixote' and 'Till Eulenspiege'.   This is taken to extremes in the type of movie scoring known as 'Mickey Mousing' where every action on screen is matched by the music.  (Even with the most extreme 'Mickey Mousing' it can be interesting to try to reconstruct the action from hearing JUST the music. Description is not definition.)
Sometimes (and rather more often) a piece describes a situation, mood or emotion.  There are many pieces that are labelled 'Storm'.  Or 'Pastorale' describing peaceful countryside.   The description may be supplied by the composer, quite often it's tagged on afterwards by someone else!
There isn't often an actual story to be told.
Comment: Speaking of Mickey Mousing, Spastic Ink's "A Wild Hare" is a pretty impressive example (IMO) of Mickey Mousing progressive metal music to scenes from the movie *Bambi* (as made apparent in https://www.youtube.com/watch?v=q_p7lLId9Xk and https://www.youtube.com/watch?v=UhP4lg28fs0).


Where can I see the options accepted by the field API for the widget type?

Question: Where can I see the options accepted by the field API for the widget type?
$instance = array(
  'field_name' => $field_name,
  'label' => 'Demofield Demo',
  'description' => 'This is a demonstration text field.'
  'widget' => array(
      'type' => 'text_textfield',
  )
);

Answer: There isn't a preset list of widget types; the widget types are the ones defined from modules that implement fields. Using the following code, you can get the list of all the widget types implemented by the enabled modules:
$array = module_invoke_all('field_info');

foreach ($array as $id => $info) {
  print $info['default_widget'];
}

The code essentially invokes all the implementations of hook_field_info(), and print what is defined as default widget.
If you have installed Devel, instead of print you can use dsm().
If you want to know the settings available for the field implementation, then you need to look for the implementation of hook_field_settings_form(), such as list_field_settings_form(), or text_field_settings_form().
function text_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];

  $form = array();

  if ($field['type'] == 'text') {
    $form['max_length'] = array(
      '#type' => 'textfield',
      '#title' => t('Maximum length'),
      '#default_value' => $settings['max_length'],
      '#required' => TRUE,
      '#description' => t('The maximum length of the field in characters.'),
      '#element_validate' => array('_element_validate_integer_positive'),
      // @todo: If $has_data, add a validate handler that only allows
      // max_length to increase.
      '#disabled' => $has_data,
    );
  }

  return $form;
}

Comment: You can also look at the source code of the widget select in the field UI, which contains all possible values.
Comment: thx for response. But as much as I see the options for each one?
e.g. the number of lines in textareas?
Answer: The default options for each widget are listed in the hook_field_widget_info() implementation.
You can find all such implementations in core by searching for "_field_widget_info": You can find a list of all core implementations of that hook by searching for "_field_widget_info": http://api.drupal.org/api/search/7/_field_widget_info


Qual o uso correto do operador "in", em javascript?

Question: Esse código não retorna nada, por quê? Estou executando em evento "window.onload":
if(innerHeight in window){
     console.log('true');
}

Eu já havia usado o operador outras vezes, e funcionava, mas agora me veio essa... E então, alguém pode me ajudar aqui?
Answer: 'innerHeight' in window

Como estás à procura de uma propriedade deves usar uma String, senão é como se estivesses à procura do conteúdo da variável innerHeight em window, ou seja o que tens é:
var alturaEmPixeis = windows.innerHeight; // isto é um numero
if (alturaEmPixeis in window){

e devias ter
if ('innerHeight' in window){

para saber se o objeto window tem a propriedade de nome innerHeight.
Comment: Obrigado, Sergio! =)


How do I limit the node count of a content type to one per user?

Question: I have a custom content type. I would like to limit that each user can only create one node of this content type. How can I achieve this?
Answer: You can use the Node Limit module for that:

The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.


elm reactor http://localhost:8000/ is empty

Question: I am just starting with Elm locally.
I did
elm init

Hello! Elm projects always start with an elm.json file. I can create them!
...
Check out <https://elm-lang.org/0.19.1/init> for all the answers!
...

Then copy into src/Main.elm from Ellie app https://ellie-app.com/new
(I also tried empty and https://github.com/elm/elm-lang.org projects)
elm reactor

And when I run the elm reactor, I see nothing at http://localhost:8000/ :
browser just waits response forever, no errors in terminal, no errors or activity in browser console, just waiting.

P.S. using macBook with M1 chip, running macOS Ventura 13.3.1 (22E261).
Elm 0.19.1
Trying Firefox and Chrome, no errors in Terminal or in Browser console.
P.P.S. To recreate
elm init
elm make
elm reactor

Comment: You could also try curl: `curl http://localhost:8000` should dump out some HTML in your terminal.
Comment: I've tried it and it works for me. Do you have any errors in the browser console?
Comment: That is exactly the strange thing: no errors in console, no activity in Network, the port http://localhost:8000 is accepting connection, so the browser is waiting, but nothing comes out, even any error in terminal where `elm reactor` is launched, nor in browser. I think something may be missing in my setup or system. But from elm reactor, there should be some timeouts configured or logs what exactly it is doing now...
Comment: Does the server return some page? Can you add that response to your question? It might be that somehow the linking between html and js generated from Elm is not working properly. Also, check that your elm.json file is generated correctly, especially the `source-directories` property is relevant here.
Comment: Server returns nothing, no response, but the port is open and connection is created, that is why browser is waiting and not just saying that unavailable. Project created with `elm init`
Comment: I meant that maybe `elm init` with its default made some incorrect assumptions. `elm make` is not required when using `elm reactor`, but does it compile your files correctly? Compiled files should appear in `build` directory.
Comment: I trying on empty and https://github.com/elm/elm-lang.org project as well. The problem definitely is not related to project content.
Comment: Could it be a browser issue or browser extension? You could try a different browser.
Comment: Just tried with `curl http://localhost:8000` and Edge browser. The same nothingness. I should better just forget about this `elm reactor`
Answer: The solution should have been: "restart your computer".
It was silly of me, as I had exactly .js script running,
that gave descibed behavior: accepting connections,
but returning nothing, and never ending connection.
const http = require("http");

const host = 'localhost';
const port = 8000;

const requestListener = function (req, res) {};

const server = http.createServer(requestListener);
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`);
});

Once I stopped that service (when restarting IDE), I got reactor accessible
Comment: Be sure to mark your own answer as accepted, to help other people know there's a solution!


how to select value from a drop down using Selenium IDE

Question: I am using Selenium IDE for the first and has no knowledge of automation scripting. So far i am able to manage using IDE but one issue is I am not able to select a value from drop down list randomly rather entering the index or label values manually every time.
Can anyone please help me with this.
Thank You
Answer: I tried the below and it worked
Command: Select
Target : element Locator eg : id = card
Value : index=1
Answer: Use command select(selectLocator, optionLocator), 'selectLocator' is the Id of the drop down from which the value is being selected and the 'optionLocator' is the value being selected.
For eg: say a drop down having Id="//select[@id='type'" with values like 'TypeA, TypeB, TypeC,...'. If you are selecting 'TypeA' from the drop down, your command should go like this:
selenium.select("//select[@id='type']", "label=TypeA");

I hope this will solve your problem.
Answer: Tried below and it worked.
command: waitForNotVisible
target: class=sub-menu
value : index=3

Answer: General approach is firstly click on the element and then select value from the element.
For Clicking :
1.Command : click
2.target  : element locator like xpath/id/class of the element eg. xpath=xpath of the element
For Selecting value:
1.Command : select
2.target  : same element locator used for clicking
3.Value   : Visible text you want to select / Index  (You will get it by inspecting that element)
Answer: First get the total number of items in the dropdown. Use getSelectOptions to get an array of options of the select box. Then generate a random integer between 0 (inclusive) and the length of the array (exclusive. Then use select with an index locator to select the randomly chosen option.
Answer: Use
Command: KeyDown
Target:css=input.comboboxname
Value: \40
\40 is Down-Arrow Ascii value
then use \13 to make selection in value.(put value for command and Target same.)
Answer: a quick and dirty javascript starting point:
<form>
  <select id="mySelect" onchange="myFunction()">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
  </select>
</form>

click me

and the (somewhat) corresponding seleniumIDE runScript command:
command
runScript

target:
document.getElementById("myDropdown").selectedIndex = Math.floor(Math.random() * (document.getElementById("myDropdown").options.length-1))+1);

The +1 at the end is entirely optional: I've included it to prevent seleniumIDE from selecting the first
Answer: Command: Select
Target: Search an Element of the website app. (name, id)
Value: What value/result do you want to see?
Example:
As an user I want to select a list of colors of drop down list (Orange, Blue, Red) I want to select Blue color.
This is a script.
Command: Select
Target: name=color
Value: Blue
Answer: It will work with WaitForVisible command
Comment: Please explain how this works. Without some more information, this answer is not very helpful.


Network permission denied on one of three servers from one workstation

Question: Using Windows AD for security, I have three servers in a farm configured with the same share on all three.  One one of the servers I cannot access the share it says my access is denied even though it is setup the same as the others.
I logged into another workstation and I am able to access the third server without issue.
What can I do/check on my workstation to see why I am being denied access to the server?
I have obviously rebooted and cleared all current connections and I am still having issues connecting.  Is there a chance my workstation is being denied?
Thank you for any assistance,
Brett
edit: It's only from my main workstation I cannot access this one server of three.  If I login to a different workstation I am able to access the share on the third server.
Tried IP address instead of machine name, same issue so not dns.
Don't know if this makes a difference, but I can map to the share, but receive an access denied when trying to use it.  (only from my workstation)
I have explicitly given myself (domain\username) full control to the share and create rights on the folder and still cannot access the share.
Have tried to remove and recreate the share and am still receiving access denied.
EDIT:
Now this is an interesting finding (to me anyway) If I add the local group everyone to the share permissions I am able to access it.  If I add myself or our domain everyone to the share permissions I receive an access denied.  Remember this issue is only happening from one workstation to a one server.  I setup a new share on the server and it acts the same exact way as the others.
Have I mentioned that I can access the scheduled tasks share?
Answer: I'm not sure what you mean when you say a "farm", but I suspect it's a run-of-the-mill permission issue.
Access to a resource is based on the user account attempting the access, not the computer from which the access attempt is being made. I suspect that there's a difference in permission on the server that isn't acting the same as the other two.
If you would, use the "CACLS" command to dump the NTFS permissions on each of the server computers and post them here (sanitized as necessary). If the "C:\Foo" folder is shared, I'd be looking for the output of the command:
CACLS C:\FOO

You can redirect the output of that command to a text-file with the syntax:
CACLS C:\FOO > filename.txt

The "share permissions" are also suspect, but there's no good way to dump those to a text file to post here. In "Computer Management" on each server, nagivate to "System Tools", "Shared Folders", and "Shares". Display the "Properties" for the shared folder in question, go to the "Share Permissions" tab, and examine the permissions.
Comment: I really don't think its an issue on the server.  Remember I stated that I am able to access the share if I login to a different workstation and access the share.  It's only from my main workstation I cannot access this one server of three.
Comment: Yes Evan, farm is irrelevant.  I said it more as the three machines are configured the same as they are load balanced application servers.

Thank you for your response.
Comment: There's no mechanism in the Windows permission system to deny access based on the computer being used to access a resource-- only the user context. Something else is in play. Your name resolution from the "main workstation" to the problem server computer is good, right? You're not seeing anything in the security event log on the problem server computer?
Comment: most of the time it's forgetting that Share Permissions are not the same as Access permissions.
Comment: Yep. I wish Microsoft would just kill that unnecessary "feature". No one has needed "Share Permissions" for years. Nobody shares folders on FAT volumes anymore. The canonical permission live on the NTFS, period.  *sigh*
Answer: Well I was able to resolve the issue, though I am not exactly sure why it was resolved.
I started by looking for the UNC name in the registry (\servername) and since I don't really need any of the entries there for applications (I only connect to upload files and terminal services) I started deleting keys containing the value.
After completing this and verifying they where gone I am able to access the share again!
Pretty wild if you ask me but I knew it had to do with the workstation and not server configuration.
The entry I found most strange was under key HCU/Software/Microsoft/Windows/CurrentVersion/Explorer/MountPoints2
Perhaps it was left over from all the testing I have been doing lately I am not sure, but a possible candidate.
To all who responded, I really appreciate your input.  Thank you for your time
Brett
Answer: What OS?  Might be a firewall issue on that one server.
Check the permissions on the drive that the share is located.  Might have some inheriting permissions.
Answer: Get Account Lockout Tools from Microsoft.    LockoutStatus, will tell you if a user is locked out, and every DC in your domain.  If you are having AD replication errors, one controller may have you locked out.
Comment: I am not locked out as I may access the share as me from a different workstation.
Answer: It might be a NTLM level requirement.
I've had this issue before. The server would accept the connection but fail when the creds were a lower then acceptable level.
Comment: Could you please enlighten me on how I would check this?
Comment: Here ya go  http://uekb.shavlik.com/UpdateEXPERT/TroubleShooting/Tasks/UE0114.htm


Different results in Cox model and negative binomial?

Question: I am confused about a problem in my research. Can anyone give me some advices ?
I used a Negative binomial ( in MASS package) to examine the effects of 3 covariates on dependent variable ( number of living buds) . Then, I used Cox proportional hazard model to examine the effects of these 3 covariates on survival of this count data.
Personally, I think that the 3 covariates should have same effects ( negative or positive) in 2 models. However, the results of 2 models were not consistent. I mean that the effects of 3 covariates on number of living trees and survival of tree were different in 2 models.
Are there something wrong ? Or my thinking is wrong?
Answer: I'm not sure I understand your experiment entirely. You mention counts of buds that you model with negative binomial regression model, but what is the event that you use in the cox regression model? You can't model a count in a cox regression, if I'm not mistaken.
Principally, you're correct that the covariates should have similar effects. However, this assumes that the covariates are measured at baseline or that they are measured later, but not subject to change. If you have a covariate that might change with time, and you measure it after baseline, you can get results that are difficult to interpret and that can sometimes be surprising. The cox proportional hazards also assumes that the hazards are proportional across the covariates. If this assumption is violated, you may also get these kinds of strange results.
Data in the negative binomial model:
stumpID sprouts DBH  stump_length  slope
2       7       18   70            25.9
6       3       34.7 63            30.9
8       38      23.1 70            21.9
33      60      22   71.3          32.4
38      4       27.1 73.4          35
44      4       35.2 80            31.1

Data in Cox model:
sproutID time1 time2 status stump_diameter stump_length slope
1        35    37    1      23.14          70           21.88
2        35    37    1      23.14          70           21.88
3        35    37    1      23.14          70           21.88
146      21    41    0      26.36          47           24.63
147      21    41    0      26.36          47           24.63
148      25    27    1      26.36          47           24.63
152      23    25    1      26.36          47           24.63

Comment: Thank you @JonB for your reply. I observed the number of buds for different time periods in a year, every month ( count death buds and new buds). For negative binomial model, I only used number of living buds data at the end of survey. For cox model, my data don't violate assumptions of proportionality and linearity . And 3 covariates are time-independent (not change over time). More detail, I could not detect ant effects of 3 covariates on number of living buds at the time point in end of survey, but the these 3 covariates had effects on survival of buds. I am so confused about the results.
Comment: Can you update your question with a sample of your dataset?
Comment: Hi@JonB. Thank you for your reply.This is a sample of data in negative binomial model:  stumpID sprouts DBH stump length slope
2 7 18 70 25.9
6 3 34.7 63 30.9
8 38 23.1 70 21.9
33 60 22 71.3 32.4
38 4 27.1 73.4 35
44 4 35.2 80 31.1
And this is data in Cox model: sproutID time 1 time 2 status stump diameter stump length slope
1 35 37 1 23.14 70 21.88
2 35 37 1 23.14 70 21.88
3 35 37 1 23.14 70 21.88
146 21 41 0 26.36 47 24.63
147 21 41 0 26.36 47 24.63
148 25 27 1 26.36 47 24.63
152 23 25 1 26.36 47 24.63
Comment: Ok. I was hoping that you could update your question with a table of your data, but perhaps you can't due to low reputation? Anyway, it seems you have two times per row in the cox model. Are there time-dependent covariates? What does the "status" variable indicate?
Comment: Thank you @JonB. In cox model, the "time.1" is the entry time, the "time.2" is censoring time or time when event occurred. The "status" variable indicates the death of sprouts. The 3 covariates : stump.diameter, stump length and slope are constant over time.  I am afraid of that my problem coming from sample size.
Answer: Did you observe and note the entry date of every single bud in your sample from the time it was brand new? Because you're measuring a lifetime, and if you include older buds, you end up measuring less than a lifetime in those specific cases, which biases your results.


force Javascript to capture focus/blur event first time it is fired

Question: Edit : Solved, it is just when console is open at loading... no idea why !
I observed that focus and blur events are not captured first time they should but only after ; with those event listeners in my code :
<code>document.addEventListener("DOMContentLoaded", function() {
    window.addEventListener("focus", function () { ... }
    window.addEventListener("blur", function () { ... }
}
</code>
I don't understand why and everything I tested to patch this doesn't worked. For example adding window.blur();window.focus(); before or after, with or without timeouts doesn't function. Same with document.body.focus().
Do you know any solution that works ?
Answer: Solved, it is just when console is open at loading... no idea why !


Git IntelliJ "Authentication Failed"

Question: I clone project with git. When I trying push/pull etc. using IntelliJ, I`ve got error "Authentication Failed". But when I use git commands in the console everything is okey and I can push, pull etc. I don't know what is the problem in IntelliJ. I tried delete and add again git in Settings, but it's not work.
Comment: Try setting credentials: https://www.jetbrains.com/help/idea/using-git-integration.html
Answer: I had exactly the same issue.
Go to File -> Settings -> Version Control -> Git -> Check "Use credential helper".
Comment: Did not work for me either, authentication succeeds if using git from the command line though, and `id_rsa` is in the `.ssh` folder too.
Comment: Didnt work for me either.
Comment: I had this one but totally forgot how to do it on the new machine.  Somehow, import settings from old one doesn't work.  Thanks.
Answer: File - Invalidate Caches / Restart - Invalidate and Restart) worked for me.

Git IntelliJ "Authentication Failed”


Open Report Use Three Combobox Filter

Question: I have 3 combobox to filter data, then i want to open in command button to print preview..
Problems I have if i used 2 combobox it works but when i used three combobox the report is blank...there's any problems with the code?? here's the code i used :
Dim strWhereCondition As String
strWhereCondition = "[month] = '" & Me.cbmonth.Value _
                    & "' and [Works] = '" & Me.cbwork.Value _
                    & "' and [Works] = '" & Me.cbwork2.Value & "'"

Debug.Print strWhereCondition
DoCmd.OpenReport "Month List", View:=acViewPreview, _
WhereCondition:=strWhereCondition

and the requery for my form
SELECT *
FROM MyTable
WHERE (month = Forms!nameForm!cbmonth
OR Forms!MeForm!cbwork IS NULL)
And (works = Forms!nameForm!cbwork
OR Forms!nameForm!cbwork IS NULL)
AND (works = Forms!nameForm!cbwork2
OR Forms!nameForm!cbwork2 IS NULL);

can anyone help?
Answer: Month is a number, so try:
strWhereCondition = "[month] = " & Me.cbmonth.Value _
                & " and [Works] = '" & Me.cbwork.Value _
                & "' and [Works] = '" & Me.cbwork2.Value & "'"

Edit: Month is text.
However, [Work] is supposed to match two potentially different values:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"

Should most likely be:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [SomeOtherField] = '" & Me.cbwork2.Value & "'"

Comment: yes im sorry its text... example Januari, Februari etc.
Comment: field [Works] its on the same field..so the code cant filter the data on the same field??
Comment: Yes, but the two combos must return the same value - a bit odd - if any records should be returned. Again, study your secret output from Debug.Print.

Open Report Use Three Combobox Filter


Example of $a,~b\in G$ such that $ab\in H\leq G$ and $a^2b^2\notin H.$

Question:
Let $G$ be a group and $H$ be a subgroup of $G$. Let also $a,~b\in G$ such that $ab\in H$.
True or false?   $a^2b^2\in H.$

Attempt. I believe the answer is no (i have proved that the statement is true for normal subgroups, but it seems that there is no need to hold for arbitrary subgroups). I was looking for a counterexample in a non abelian group  of small order, such as $S_3$, or $S_4$, but i couldn't find a suitable combination of $H\leq S_n$, $\sigma$ and $\tau\in S_n$ such that $\sigma \tau \in H$ and $\sigma^2 \tau^2 \notin H.$
Thanks in advance for the help.
Comment: Just out of curiosity, what pair $\sigma,\tau\in S_3$ did you try in your ques for an example with $\sigma^2\tau^2\notin\langle\sigma\tau\rangle$? (I assume they did not commute, and were not both of order $2$.)
Answer: Consider $S_3$.
Let $a=(1 2 3)$ and $b=(2 3)$. Then $ab=(1 2)$ and $a^2b^2=(1 3 2)$
Let $H=\{1, ab\}$. Then $ab\in H$ but $a^2b^2\not\in H$
Answer: Take $G$ to be the free group on $a,b$, whose elements are the reduced words in the alphabet $a,b,a^{-1},b^{-1}$.
Take $H$ to be the cyclic subgroup generated by $ab$.
The non-identity elements of $H$ are the reduced words words $(ab)^n$ for $n \ge 1$ and $(b^{-1}a^{-1})^n$ for $n \ge 1$.
Since the reduced word $a^2 b^2$ does not have that form, it follows that $a^2 b^2 \not\in H$.
Answer: Let $u \in G$, $v \in H$.
Take $a=u$, $b=u^{-1}v$. Then $ab \in H$.
Moreover, $a^2b^2=uvu^{-1}v$, thus $a^2b^2 \in H \Leftrightarrow uvu^{-1}v \in H \Leftrightarrow uvu^{-1} \in H$.
Thus if $H$ is not normal, the property does not hold.
Comment: Failure of normality does not imply that *for all* $u \in G$, $\nu \in H$ we have $u\nu u^{-1} \not\in H$.
Comment: Yes. That may be not clear enough in my post: I proved that if the property held for every pair $(a,b)$, then the subgroup was normal. I think that in this case you answer « False ».
Comment: +1, to me this is just best possible.


Agregar dados com datas diferentes e considerando outras colunas no R

Question: Gostaria de agregar as linhas do dataframe TBCG2, quando a DATA_INGRESSO_ORGAO é diferente (vejam a coluna ID_SERVIDOR_PORTAL números 977, 1089, 1365, 1666, 2597, 2779 e 3036). Desejo manter a data mais antiga, conforme código abaixo. Porém, no caso da ID 2789, tenho CARGOs diferente para datas diferentes, nesse caso, quero manter as duas linhas, modificando o ID de uma delas acrescentando um x no ID. Ou seja, quero manter uma ID_SERVIDOR_PORTAL=2789 e outra ID_SERVIDOR_PORTAL=2789x. Este dataframe é só uma parte do meu banco de dados. Como devo proceder?
url=url("https://raw.githack.com/fsbmat/salarioDocente/master/Teste/TBCG2.csv")
TBCG2 <- read.csv2(url, header = TRUE,encoding = "ASCII")
TBCG2$DATA_INGRESSO_ORGAO <- as.Date(as.character(TBCG2$DATA_INGRESSO_ORGAO), format = "%d/%m/%Y")
library(sqldf)
TBCG2 <- sqldf('select ID_SERVIDOR_PORTAL,NOME,CPF,CARGO,
                min(DATA_INGRESSO_ORGAO) as DATA_INGRESSO_ORGAO,
                sum(BRU_Jan2013 )   as  BRU_Jan2013,
                sum(BRU_Fev2013 )   as  BRU_Fev2013,
                sum(BRU_Mar2013 )   as  BRU_Mar2013
                from TBCG2
                group by ID_SERVIDOR_PORTAL,NOME,CPF')

Answer: Aparentemente consegui uma solução, talvez não seja a mais rápida devido ao loop, mas o importante é que deu certo. Segue o código:
url=url("https://raw.githack.com/fsbmat/salarioDocente/master/Teste/TBCG2.csv")
TBCG2 <- read.csv2(url, header = TRUE,encoding = "ASCII")
TBCG2$DATA_INGRESSO_ORGAO <- as.Date(as.character(TBCG2$DATA_INGRESSO_ORGAO), format = "%d/%m/%Y")
a <- c(NULL)
b <- c(NULL)
df <- TBCG2[duplicated(TBCG2$ID_SERVIDOR_PORTAL),]
ID <- df$ID_SERVIDOR_PORTAL
for (i in 1:length(ID)) {
  a[i] <- min((1:nrow(TBCG2))[TBCG2$ID_SERVIDOR_PORTAL==ID[i]])
  b[i] <- max((1:nrow(TBCG2))[TBCG2$ID_SERVIDOR_PORTAL==ID[i]])
  TBCG2$ID_SERVIDOR_PORTAL[a[i]] <- ifelse(TBCG2$ID_SERVIDOR_PORTAL[a[i]]==TBCG2$ID_SERVIDOR_PORTAL[b[i]]&TBCG2$CARGO[a[i]]==TBCG2$CARGO[b[i]],TBCG2$ID_SERVIDOR_PORTAL[a[i]],as.numeric(paste(TBCG2$ID_SERVIDOR_PORTAL[a[i]],"001",sep="")))
}
library(sqldf)
TBCG2 <- sqldf('select ID_SERVIDOR_PORTAL,NOME,CPF,CARGO,
                min(DATA_INGRESSO_ORGAO) as DATA_INGRESSO_ORGAO,
                sum(BRU_Jan2013 )   as  BRU_Jan2013,
                sum(BRU_Fev2013 )   as  BRU_Fev2013,
                sum(BRU_Mar2013 )   as  BRU_Mar2013
                from TBCG2
                group by ID_SERVIDOR_PORTAL,NOME,CPF')


What is the Betti number of a group?

Question: I'm studying the Fundamental Theorem of finitely generated Abelian group, and it says that the number of factors equal to $\mathbb Z$ (textbook says it is the Betti number of the group) is unique up to isomorphism.

So what is "the number of factors"?

I tried to find through Wikipedia, and it says that it is the number of generators. So if I'm right, the Betti number of Z_6 is 2 (since 1 and 5 are the generators). Then, what is Betti number of Z_360? Should I try all the cases that are relatively prime to 360? Is there any way to get it easier? I really want to fully understand the definition and applications. Thanks for your help :)
Comment: Ah! Now I understand! Thank you very much!
Comment: Wait! but this textbook says every finite abelian group has a Betti number 0...?
Comment: Yes - this is why the number of generators comment on Wikipedia is wrong! The finite abelian group $\mathbb{Z}_5$ is generated by one object, but has Betti number zero (its free part is $0$). I think the confusion on Wikipedia is because they are talking about groups arising from topological spaces, and if you put enough restrictions on the space, you will only see groups isomorphic to $\mathbb{Z}^n$, so then the Betti number really is the number of generators - but this is not the case even for  general topological spaces.
Comment: Said another way - in the textbook's language, the Betti number is *not* the number of generators, but the number of factors isomorphic to $\mathbb{Z}$ (and I agree that this is the better definition). As $\mathbb{Z}$ is not finite, no finite abelian group can have a factor isomorphic to $\mathbb{Z}$.
Comment: One additional comment; I think the "number of generators" comment on Wikipedia is slightly wrong, but at the very least it means the minimal number of generators in a generating set, not the number of elements which are generators. So the "answer" for $\mathbb{Z}_6$ would be $1$, because it is generated by $1$ (or by $5$ - but one element is sufficient). Something like $\mathbb{Z}^2$ isn't generated by a single element; but it can be generated by two elements (e.g. $(1,0)$ and $(0,1)$), so the Betti number is $2$.
Comment: Eureka! Thank you again!
Comment: @user26857 The $n$th Betti number of a space $X$ is the Betti number of $H_n(X)$.
Comment: Hello, I dont understand yet. Betti numbers is like number of generators?? For example, how can I find the betti number of $Z x Z_6 x Z_8 x Z x Z_{10} x Z$???
Answer: Each finitely generated abelian group $G$ is isomorphic to $$\mathbb{Z}^n\oplus\bigoplus_{m\geq2}\mathbb{Z}_m^{k_m}$$
(where all but finitely many of the $k_m$ are $0$) by the fundamental theorem - which says something much more precise, but this is all we'll need. The Betti number is then $n$; the number of summands (or factors) that are isomorphic to $\mathbb{Z}$. Sometimes the $\mathbb{Z}^n$ is called the free part (and the other summands the torsion part), so you're looking for the number of generators of the free part.
Another more technical way to say this is that it's the dimension over $\mathbb{Q}$ of $G\otimes_{\mathbb{Z}}\mathbb{Q}$; because $\mathbb{Z}\otimes_{\mathbb{Z}}\mathbb{Q}\cong\mathbb{Q}$ and $\mathbb{Z}_m\otimes_{\mathbb{Z}}\mathbb{Q}\cong\{0\}$, this agrees with the above calculation.
Comment: @Math-Nerd No, $ℤ$ and $ℤ × ℤ/2ℤ$ are not isomorphic.
Comment: So the Betti number is the same as the rank? To me, [this definition](https://en.wikipedia.org/wiki/Betti_number#Definition) suggests that is the rank of the $k$-th homology group of the group.
Comment: That page is about the Betti number for topological spaces; the $k$-th Betti number of the space is the rank of its $k$-th homology group, which deserves to be called the Betti number of the group! To calculate the homology group of a group, you need to put a topology on it; for finite abelian groups, the most obvious one is the discrete one, in which case the $0$-th Betti number is the number of elements, and all the others are $0$ - this probably isn't what you wanted!
Comment: Well, there's always group [(co-)hohomology](https://en.wikipedia.org/wiki/Group_cohomology#Group_homology).
Comment: True - but the fact the OP says "Betti number" rather than "Betti numbers" suggests that this is not the point. I don't know if one of the cohomological Betti numbers will also agree with the rank.
Comment: BTW, then if two finitely generated Abelian groups have same Betti number, are they isomorphic?
Comment: For calculate Betti number... need I compute the number of isomorphic groups?

What is the Betti number of a group?


Google analytics per page

Question: I'd like to post alot of Google Analytics info about a page(node) on the page itself(visits, new visits, bounce rate, maybe even time series). What's the best module for this?
In particular, the info is for users that create their own pages and need to see analytics for their pages.
Any hints?
Thanks.
Answer: Try Drupal SEO may be what you are looking for.  http://drupal.org/project/seotools
From its project page:

The Drupal SEO Tools module seamlessly integrates a sophisticated all-in-one suite of search engine reporting, analysis and optimization tools into your website. It provides a dashboard that integrates analytics reports with links to webmaster tools and vital Drupal SEO modules.

Hope that helps.
Answer: http://drupal.org/project/google_analytics_reports also provides this functionality.  The 3.x branch includes Views support that allows you to create custom reports.
Some details from the project page:

Google Analytics Reports module provides graphical reporting of your site's tracking data. Graphical reports include small path-based report in blocks, and a full path-based report.

Google analytics per page


How to find column information for an aggregate grouping

Question: I have a complicated query written on SQL Server 2000 which in part contains a join onto a derived table. This table is unfortunately not returning exactly how I desired as the underlying data differs to what I expected. Say the data are like this:
USERID,OS,DATEINSTALLED
237,win,01/01/1980
237,dos,01/02/1978
237,lin,08/08/2002
132,win,03/03/1982
132,dos,03/07/2002
132,mac,03/07/2002

Then my query looked as so:
SELECT USERID, DATEINSTALLED = max(DATEINSTALLED)
FROM INSTALLATIONS
GROUP BY USERID

Which would give a result set of
237,08/08/2002
132,03/07/2002

But what I require is a result set of:
237,lin,08/08/2002
132,dos,03/07/2002

OR
237,lin,08/08/2002
132,mac,03/07/2002

I'm not really fussed if it picks up mac or dos but it must not give 3 rows; as what I need is one row per userid, with a max date and "a" valid OS for that combination. So mac or dos are valid, but win is not (for user 132).
As it's a derived table as part of a more complicated query I need to keep it as clean and simple as possible due to execution time (source table is a few hundred thousand rows in size). As implied by the tags I'm limited to SQL Server 2000.
Answer: Try this:
SELECT USERID, OS, DATEINSTALLED
FROM INSTALLATIONS
JOIN (
   SELECT USERID, DATEINSTALLED = max(DATEINSTALLED)
   FROM INSTALLATIONS
   GROUP BY USERID
) AS T
ON INSTALLATIONS.USERID = T.USERID AND INSTALLATIONS.DATEINSTALLED = T.DATEINSTALLED

Comment: So in order to build my derived table, the derived table will require a derived table. I will give this a go, hopefully in the next hour or two.
Comment: Thanks for your reply but that won't work. I'm afraid the fault is mine however for not getting my question correct, I'm sure your answer was correct as phrased. Updated my question to be what I was actually trying to ask, that I want 1 row per userid and date with any valid OS matching those 2 criteria.
Comment: Got it sorted in the end, the real query is giving me a headache at this point. What I've done is similar to your answer but replacing "OS" with "OS = MAX(OS)". Basically nesting and repeating the original logic that I had.


Como eu faço tratamento de Variáveis no PHP?

Question: Tenho o Seguinte Código no PHP:
Array:
$eqCodigos  = $_POST["eqCodigo"];

Tentativa de Tratamento para gravar no MySQl
$eqCodigo1 = explode("\n", $eqCodigos);
$eqCodigo2 = array_filter($eqCodigo1);
$eqCodigo  = trim($eqCodigo2);

Query mysql_query
mysql_query("INSERT INTO eq_Codigos (idEquipamento, cdCodigo, cdOpAlteracao, cdDtAlteracao) VALUES ('$idEquipamento', '$eqCodigo[0]', '$eqOpAlteracao', NOW()), ('$idEquipamento', '$eqCodigo[1]', '$eqOpAlteracao', NOW())")

Export da tabela depois do INSERT
INSERT INTO `eq_Codigos` (`idCodigo`, `idEquipamento`, `cdCodigo`, `cdOpAlteracao`, `cdDtAlteracao`) VALUES (27, 164, '123\r', 'Jonatas Messias', '2016-09-23 10:06:16'), (28, 164, '987', 'Jonatas Messias', '2016-09-23 10:06:16');

Só que na hora que salva no banco o primeiro código do Array fica com "\r" no final, dificultando na hora que vou fazer o Select.
Comment: @FlavioMisawa o que essa RegEx era para fazer? `^` iniciando no final?
Comment: Você pode usar uma expressão regular para retirar aonde tiver o /r `$ret = preg_split ('/$\R?^/m', $eqCodigos);`
Comment: Mas eu posso deixar o Código do jeito que esta ou eu posso usar essa expressão no lugar do trim?
Comment: `\r` ou `/r`? qual deles
Comment: @WallaceMaxters é \r, editei a pergunta e coloquei o export da tabela após o insert para você vê como que fica no MySql.
Answer: Primeiro eu gostaria de apontar alguns erros no seu código, para analisarmos a situação:
$eqCodigo1 = explode("\n", $eqCodigos); // Isso vira um `array`
$eqCodigo2 = array_filter($eqCodigo1); // Certo, o `array` será filtrado
$eqCodigo  = trim($eqCodigo2); // Usar trim num `array` vai gerar erro, pois ele espera uma `string`.

A primeira coisa a ser feita no caso é mudar esse código para:
$eqCodigo1 = explode("\n", $eqCodigos);
$eqCodigo2 = array_filter($eqCodigo1);
$eqCodigo  = array_map('trim', $eqCodigo2);

Uma das situações a serem feitas aqui é verificar que alguns sistemas operacionais a quebra de linha é \r\n, e não somente \n.
Ao fazer um teste com a seguinte string:
  explode("\n", "\r\n a" )

O Resultado foi:
[
  "\r",
  " a",
]

Ou seja, observe que \r "ficou para trás". A minha solução para isso, seria primeiramente tratando os dados, para que eles fiquem padronizados para \n sempre.
Ou seja:
  explode("\n", str_replace("\r\n", "\n", $eqCodigos));

Se quiser ressumir o processo de declaração de variáveis, você ainda pode fazer assim:
$eqCodigo = array_map('trim', array_filter(explode("\n", str_replace("\r\n", "\n", $eqCodigos))));

Comment: Muito Obrigado a sua Solução e explicação me ajudaram muito. Consegui resolver o problema! Usando  o resumo que você passou!


Help identify brand of guitar

Question: I recently got a guitar from my dad's friend for my birthday. He didn't play with it at all and gifted it to me. It's a really nice guitar, but I can't identify the brand of the guitar. The only clue I have about the guitar is the logo on the headstock, which I unfortunately can't decipher.
I would be very happy if someone could identify the brand!
Comment: I'm voting to close this question because identifying instruments isn't [on topic here](https://music.stackexchange.com/help/on-topic).
Comment: It's a great idea, any time you get a new instrument, to take it to an expert to look over. They can probably best advise you about its history, authenticity, and whether it matters, as well as spot any work that's needed.
Answer: This is the logo for Jaws Custom Guitars in Switzerland. Probably closed down at this point, as far as I can tell, they imported guitars from Asia, possibly china.
Comment: By answering, it encourages folk to ask questions which are not part of the site's remit.

Help identify brand of guitar


How to refresh include (inc) file

Question: I updated an include (inc) file. It was a text change. I want my website to show these changes. I cleared the cache. Nothing changed. I restarted the server. Nothing changed. I checked the server. The new include (inc) file is there. Not sure how else to refresh the include (inc) file.
It's located at htdocs\sites\all\modules\custom\myMods
Here is the new file: ( I simply changed the text in the  of the description )
<?php
/**
 * @file
 * siam_team_profile.field_group.inc
 */

/**
 * Implements hook_field_group_info().
 */
function siam_team_profile_field_group_info() {
  $field_groups = array();

  $field_group = new stdClass();
  $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
  $field_group->api_version = 1;
  $field_group->identifier = 'group_parcon|node|team_member|form';
  $field_group->group_name = 'group_parcon';
  $field_group->entity_type = 'node';
  $field_group->bundle = 'team_member';
  $field_group->mode = 'form';
  $field_group->parent_name = '';
  $field_group->data = array(
    'label' => 'Parental Consent',
    'weight' => '7',
    'children' => array(
      0 => 'field_consent',
      1 => 'field_name_of_parent',
      2 => 'field_ethnicity',
    ),
    'format_type' => 'fieldset',
    'format_settings' => array(
      'label' => 'Parental Consent',
      'instance_settings' => array(
        'required_fields' => 1,
        'classes' => 'group-pconsent field-group-fieldset',
        'description' => '
The section below is to be filled out by the student's parent or guardian.

By agreeing to this Parent/Guardian Consent statement, I give my permission for my son/daughter to participate in  MATLAB Math Modeling Challenge, which is funded by The MathWorks and organized and administered by the Society for Industrial and Applied Mathematics (SIAM). I give my permission to disclose his/her name and likeness in text, still pictures, and in videos, for publication in press releases, on the M3Challenge and MathWorks* websites, and in SIAM News. I also give my permission to release his/her name and likeness to any and all online or print local, regional, or national newspapers, radio and television outlets, and via any other media, including social media platforms, that seek to publicize the Challenge and its participants in any way.

On behalf of myself and my child, I hereby (a) waive any right or cause of action arising as a result of his/her participation in the Challenge and (b) release and discharge MathWorks and SIAM from any and all claims or causes of action (known or unknown) arising out of his/her participation in the Challenge (including, but not limited to, its or their negligence).

I understand that for teams proceeding to the final competition process, the students\' live presentations at the final Challenge event will be photographed and/or videotaped, and these photos and videos may be used for webcast, broadcast, posting to the M3 Challenge website, in news releases, and in the media, as well as in internal or external SIAM or MathWorks publications, online or in print, and on any SIAM or MathWorks Internet websites and digital social media presence, and I consent to any and all such use.

*MathWorks includes The MathWorks, Incany and all of its product lines, affiliates, subsidiaries, and their successors and assigns, and any and all of their past and present directors, officers, representatives, agents and employees, whether as individuals or in their official capacity.

',
      ),
      'formatter' => 'collapsible',
    ),
  );
  $field_groups['group_parcon|node|team_member|form'] = $field_group;

  $field_group = new stdClass();
  $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
  $field_group->api_version = 1;
  $field_group->identifier = 'group_personal|node|team_member|form';
  $field_group->group_name = 'group_personal';
  $field_group->entity_type = 'node';
  $field_group->bundle = 'team_member';
  $field_group->mode = 'form';
  $field_group->parent_name = '';
  $field_group->data = array(
    'label' => 'Personal Information',
    'weight' => '0',
    'children' => array(
      0 => 'field_first_name',
      1 => 'field_gender',
      2 => 'field_grade',
      3 => 'field_teamail',
      4 => 'title',
    ),
    'format_type' => 'fieldset',
    'format_settings' => array(
      'formatter' => 'collapsible',
      'instance_settings' => array(
        'description' => '',
        'classes' => 'group-personal field-group-fieldset',
        'required_fields' => 1,
      ),
    ),
  );
  $field_groups['group_personal|node|team_member|form'] = $field_group;

  // Translatables
  // Included for use with string extractors like potx.
  t('Parental Consent');
  t('Personal Information');

  return $field_groups;
}

Old file for reference:
            <?php
    /**
     * @file
     * siam_team_profile.field_group.inc
     */

    /**
     * Implements hook_field_group_info().
     */
    function siam_team_profile_field_group_info() {
      $field_groups = array();

      $field_group = new stdClass();
      $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
      $field_group->api_version = 1;
      $field_group->identifier = 'group_parcon|node|team_member|form';
      $field_group->group_name = 'group_parcon';
      $field_group->entity_type = 'node';
      $field_group->bundle = 'team_member';
      $field_group->mode = 'form';
      $field_group->parent_name = '';
      $field_group->data = array(
        'label' => 'Parental Consent',
        'weight' => '7',
        'children' => array(
          0 => 'field_consent',
          1 => 'field_name_of_parent',
          2 => 'field_ethnicity',
        ),
        'format_type' => 'fieldset',
        'format_settings' => array(
          'label' => 'Parental Consent',
          'instance_settings' => array(
            'required_fields' => 1,
            'classes' => 'group-pconsent field-group-fieldset',
            'description' => '
The section below is to be filled out by the student's parent or guardian.

    By agreeing to this Parent/Guardian Consent statement, I give my permission for my son/daughter to participate in Moody\'s Mega Math (M3) Challenge, which is funded by The Moody\'s Foundation and organized and administered by the Society for Industrial and Applied Mathematics (SIAM). I give my permission to disclose his/her name and likeness in text, still pictures, and in videos, for publication in press releases, on the M3 Challenge and Moody\'s* websites, and in SIAM News. I also give my permission to release his/her name and likeness to any and all online or print local, regional, or national newspapers, radio and television outlets, and via any other media, including social media platforms, that seek to publicize the Challenge and its participants in any way.

    On behalf of myself and my child, I hereby (a) waive any right or cause of action arising as a result of his/her participation in the Challenge and (b) release and discharge Moody\'s and SIAM from any and all claims or causes of action (known or unknown) arising out of his/her participation in the Challenge (including, but not limited to, its or their negligence).

    I understand that for teams proceeding to the final competition process, the students\' presentations at Moody\'s headquarters in Manhattan will be photographed and/or videotaped, and these photos and videos may be used for webcast, broadcast, posting to the M3 Challenge website, in news releases, and in the media, as well as in internal or external SIAM or Moody\'s publications, online or in print, and on any SIAM or Moody\'s Internet websites, and I consent to any and all such use.

    *Moody\'s includes Moody\'s Corporation, and any and all of its affiliates, subsidiaries, and their successors and assigns, and any and all of their past and present directors, officers, representatives, agents and employees, whether as individuals or in their official capacity.

',
          ),
          'formatter' => 'collapsible',
        ),
      );
      $field_groups['group_parcon|node|team_member|form'] = $field_group;

      $field_group = new stdClass();
      $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
      $field_group->api_version = 1;
      $field_group->identifier = 'group_personal|node|team_member|form';
      $field_group->group_name = 'group_personal';
      $field_group->entity_type = 'node';
      $field_group->bundle = 'team_member';
      $field_group->mode = 'form';
      $field_group->parent_name = '';
      $field_group->data = array(
        'label' => 'Personal Information',
        'weight' => '0',
        'children' => array(
          0 => 'field_first_name',
          1 => 'field_gender',
          2 => 'field_grade',
          3 => 'field_teamail',
          4 => 'title',
        ),
        'format_type' => 'fieldset',
        'format_settings' => array(
          'formatter' => 'collapsible',
          'instance_settings' => array(
            'description' => '',
            'classes' => 'group-personal field-group-fieldset',
            'required_fields' => 1,
          ),
        ),
      );
      $field_groups['group_personal|node|team_member|form'] = $field_group;

      // Translatables
      // Included for use with string extractors like potx.
      t('Parental Consent');
      t('Personal Information');

      return $field_groups;
    }

Comment: You tagged the question "8". Sure you are using Drupal 8? Afaik this is a hook from the 7 version of the module.
Answer: There is cache somewhere along the stack so if its not drupal cache
try making a small change on the file that includes this file and saving in order to force renewing the timestamp
or you might want to try
//after include
clearstatcache();

more info here http://php.net/manual/en/function.clearstatcache.php
or if you have opcache enabled can try to setting it opcache.enable = 0 or
//
opcache_invalidate ( string $script [, boolean $force = FALSE ] )

or please tell us how your website is accessed all service running on your server that might be intercepting the generation of the site

How to refresh include (inc) file


ERRO AO INSTALAR PYAUDIO

Question: Para usar o speech recognition com microfone, preciso instalar o Pyaudio, mais ao executar a instalação pip install pyaudio recebo o seguinte erro:
Collecting pyaudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
Using legacy 'setup.py install' for pyaudio, since package 'wheel' is not installed.
Installing collected packages: pyaudio
    Running setup.py install for pyaudio ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\grave\\AppData\\Local\\Temp\\pip-install-svyt8sdr\\pyaudio_a8a346e98970466681cc9c80c30e69cd\\setup.py'"'"'; __file__='"'"'C:\\Users\\grave\\AppData\\Local\\Temp\\pip-install-svyt8sdr\\pyaudio_a8a346e98970466681cc9c80c30e69cd\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\grave\AppData\Local\Temp\pip-record-mu8_l4wl\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\python39\Include\pyaudio'
         cwd: C:\Users\grave\AppData\Local\Temp\pip-install-svyt8sdr\pyaudio_a8a346e98970466681cc9c80c30e69cd\
    Complete output (17 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.9
    copying src\pyaudio.py -> build\lib.win-amd64-3.9
    running build_ext
    building '_portaudio' extension
    creating build\temp.win-amd64-3.9
    creating build\temp.win-amd64-3.9\Release
    creating build\temp.win-amd64-3.9\Release\src
    C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -Ic:\python39\include -Ic:\python39\include -IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.9\Release\src/_portaudiomodule.obj
    _portaudiomodule.c
    c:\python39\include\pyconfig.h(117): warning C4005: 'MS_WIN64': redefini‡Æo de macro
    src/_portaudiomodule.c: note: consulte a defini‡Æo anterior de 'MS_WIN64'
    src/_portaudiomodule.c(29): fatal error C1083: NÆo ' poss¡vel abrir arquivo incluir: 'portaudio.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\grave\\AppData\\Local\\Temp\\pip-install-svyt8sdr\\pyaudio_a8a346e98970466681cc9c80c30e69cd\\setup.py'"'"'; __file__='"'"'C:\\Users\\grave\\AppData\\Local\\Temp\\pip-install-svyt8sdr\\pyaudio_a8a346e98970466681cc9c80c30e69cd\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\grave\AppData\Local\Temp\pip-record-mu8_l4wl\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\python39\Include\pyaudio' Check the logs for full command output.

e ao executar  pip install PyAudio-0.2.11-cp39-cp39-win_amd64 recebo:
ERROR: Could not find a version that satisfies the requirement PyAudio-0.2.11-cp39-cp39-win_amd64
ERROR: No matching distribution found for PyAudio-0.2.11-cp39-cp39-win_amd64

tenho instalado aqui:
Python 3.9, speech_recognition, Google API Client Library for Python e pywin.
Answer: Tente instalar primeiro o modulo pywin pip install pipwin
E logo em seguida rode o seguinte comando pipwin install pyaudio
Pronto, provavelmente o modulo pyaudio agora irá funcionar!
Comment: muito obrigado, funcionou.

ERRO AO INSTALAR PYAUDIO


Como formatar um array php

Question: Estou fazendo uma consulta SQL no meu model e no controller, estou imprimindo os valores do array.
A exibição esta assim:
Array ( [campo1] => 98 [campo2] => SOLO [soma] => 1 ) Array ( [campo1] => 92 [campo2] => DARTH [soma] => 11 ).

Mas gostaria de formatar assim:
[campo1] => 98 =>[campo2] =>
            SOLO [soma] => 1
[campo2] => 92 =>[campo2] =>
            DARTH [soma] => 11

Como fazer?
Esse é o meu foreach:
foreach ($variavel1 as $key) {
   print_r($key);
}

Comment: Amigo, posta o método em questão todo do seu controller pra melhor análise
Answer: Se você deseja ver o conteúdo do array não é necessário executar um foreach, basta utilizar a tag pre do HTML em conjunto com a função print_r do PHP desta forma:
echo '
'.print_r($array, true).'
';

O resultado será:
Array
(
    [0] => Array
    (
        [campo1] => 98
        [campo2] => SOLO
        [soma] => 1
    )
    [1] => Array
    (
        [campo1] => 92
        [campo2] => DARTH
        [soma] => 11
    )

)

A tag pre tem o objetivo de facilitar a leitura dos dados, preservando os espaços e quebras de linha retornados pelo print_r.
E a função print_r quando tem o segundo parâmetro informado como true ao invés de imprimir, retorna a informação para podermos utilizar como desejarmos.
Answer: Tente user o VarDumper do próprio Yii2
\yii\helpers\VarDumper::dump($array, 10, true);

É um pouco diferente do jeito que ilustrou, mas dessa forma fica bem claro
Answer: Vejamos você está imprimindo  uma subarray que é encontrada pelo for each  se  você quiser imprimila desta forma você estará deixando de ter uma array  e  passarar a ter um  string
pode fazer isso pela função implode
foreach ($variavel1 as $key) {
    $output = implode(', ', array_map(
        function ($v, $k) { return sprintf("[%s]=>'%s'", $k, $v); },
        $key,
        array_keys($key)
    ));
    echo $output."\n";
}

isso imprimirá algo como
[campo1]=>'98', [campo2]=>'SOLO', [soma]=>'1'
[campo1]=>'92', [campo2]=>'DARTH', [soma]=>'11'

Como formatar um array php


Android Toolbar menu actionViewClass or actionLayout cannot be right alignment

Question: I want to have a menu icon on the toolbar, when click on this menu icon and change to checkbox icon.
Like the search icon in the toolbar. When click on search menu button, show the searchView.
This is how the searchView is added in the menu.
<item android:id="@+id/action_search"
            android:title="@string/action_menu_search"
            android:icon="@drawable/ic_action_search"
            app:showAsAction="ifRoom|collapseActionView"
            app:actionViewClass="android.support.v7.widget.SearchView"/>

So i did the same for the checkbox
app:actionViewClass="android.widget.CheckBox"

But the actionview is shown, it is left align to the home up button. May be it is because checkbox is wrap_content.
But i want it to be right align to the end of the parent view.
So after checking this https://developer.android.com/training/appbar/action-views.html
I think i can use the actionLayout.
So i change as below:
<item android:id="@+id/action_delete"
            android:title="delete"
            android:icon="@drawable/ic_action_delete"
            app:showAsAction="always|collapseActionView"
            app:actionLayout="@layout/toolbar_checkbox_layout" />

toolbar_check_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent">

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="Text"
        android:gravity="center"
        android:textColor="@color/colorAccent"/>

    <android.support.v7.widget.AppCompatCheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:buttonTint="@color/colorAccent"
        android:layout_gravity="end|center"
        android:layout_marginEnd="15dp"
        android:layout_marginRight="15dp" />

</LinearLayout>

The result is like that. It still cannot be right alignment. I want checkbox to be right side of the toolbar. Any suggestion? please. Thanks a lot
Answer: MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#ffffff"
tools:context="com.example.raj.jazzflurry.MainActivity">
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/faqfoods_bar"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay" >
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_gravity="end"
            android:layout_height="?attr/actionBarSize">
            <include
                layout="@layout/btn_share"
                android:id="@+id/btn_share"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

btn_share.xml
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizantal" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text"
    android:layout_gravity="center"
    android:textColor="@color/colorAccent"/>

<android.support.v7.widget.AppCompatCheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@color/colorAccent"
    android:layout_gravity="center" />

</LinearLayout>

Java file (inside of on create)
 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Hai");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.colorprimary1));

Manifest.xml
  <activity
        android:name=".MainActivity"
        android:screenOrientation="portrait"
        android:theme="@style/Theme.AppCompat.NoActionBar">

Comment: I don't want to modify my toolbar as above. I just want to set action view class or action layout that can be pinned to the right.  When switch to action view, toolbar will automatically switch to home up button(back button).


SQL Server 2014 trigger across multiple databases

Question: I have 2 databases test1 and test2. Let's say that I have a system, that updates specific values in database test1.
Now I want to create a trigger which is placed in database test2 to check if database test1 updates the values.
When it is updated, I want to write something to database test2.
I have tried it with the following trigger:
ALTER TRIGGER [dbo].[testtrigger]
ON [test2].[dbo].[naam2]
AFTER UPDATE ON [test1].[dbo].[naam]

However, I get a syntax error at:

Incorrect syntax near 'ON'. Expecting ',',AS,NOT_FOR, or WITH

Now I wonder why this is happening. I have searched about how to do this, and the all reference to ON.
I'm using Microsoft SQL Server 2014
I will add a image to try and make it more clear if it isn't.
Comment: You cannot do this - the trigger always has to be where the action happens - you cannot have a trigger that "observes" another table - the trigger is fired when an insert, update or delete happens on the table that the trigger is defined on.
Answer:
trigger is in database test2,when a table in database test1 changes,iwant to respond..

Your syntax is wrong..Below is overview of how you can do it
create trigger triggername on test1.dbo.table1
after update
as

begin
insert into test2.dbo.table2
select * from deleted

end

Comment: i missed triggername,also your syntax is not valid,,use just databasename
Comment: What i did:

  **USE [test1].[dbo].[naam]
GO

create trigger ON [test1].[dbo].[naam]
after update
as

begin
insert into [test2].[dbo].[naam2]
select * from deleted

end**

Result is that it still gives the error at **ON**.  Expecting ID or Quoted_ID
Comment: Okay, that is working. However, it makes the trigger in database **test1**. My goal is to keep the trigger inside database **test2** so that database test1 does not have any triggers. I want the **test2** database to check if the **test1** database has any updates.
Comment: trigger won't work like that,you can write custom logic and compare
Comment: Because the whole problem is. We have a application, and we are writing a trigger that throws data to an other database. However, when we update it manual (Via SQL) the Trigger works. However, when we let the system do it (Wich put an update every 5 minutes in the database) it does nothing. The whole application actually stops with updating inside the database.
So i had the idea to put the trigger inside the other database, in the hope that it would work.


The name 'parametros' does not exist in the current context

Question: Tenho o código abaixo e está dando o seguinte erro:

The name 'sql' does not exist in the current context The name
  'parametros' does not exist in the current context

Alguém pode me ajudar por favor?
Agradeço desde já...
public DataSet PesquisarProtocolos(string usuarioAutenticado, long? codigoProcotolo, int? codigoMenu, string campoPesquisaDinamica, string valorPesquisaDinamica, string periodo, int? mes, int? ano, int? codigoStatus, int? codigoMotivo, int? codigoTipoRemuneracao, int? codigoGrupoContestacao, int? codigoTipoContestacao, int? codigoMotivoContestacao, bool carregarDivergentes, int? perfil = null, string parceirosGestaoCarteira = "", int codigoCargo = 0)
        {
            if ((codigoCargo == 9) || (codigoCargo == 1029) || (codigoCargo == 1030))
            {
                //vou colocar depois o código
            }
            else if ((codigoCargo == 8) || (codigoCargo == 11))
            {
                //vou colocar depois o código
            }
            else
            {
                 string sql = string.Format(@"
                SELECT DISTINCT
                       C.[COD_PROTOCOLO_CONTESTACAO]
                      ,C.[COD_PROTOCOLO_CONTESTACAO_RELACIONADO]
                      ,C.[QTD_LINHAS_PROCESSADAS]
                      ,C.[QTD_LINHAS_DIVERGENTES]
                      ,(SELECT TOP 1 LOGIN FROM ADM_USUARIO U WHERE U.cod_usuario = C.COD_USUARIO_RESPONSAVEL) [COD_USUARIO_RESPONSAVEL]
                      ,C.[DSC_PERIODO_PAGAMENTO]
                      ,C.[NUM_ANO_PAGAMENTO]
                      ,C.[NUM_MES_PAGAMENTO]
                      ,C.[COD_ESPELHO_ASSOCIACAO]
                     ,C.[COD_TIPO_REMUNERACAO]
                      ,C.[NUM_MES_REFERENCIA]
                      ,C.[NUM_ANO_REFERENCIA]
                      ,C.[COD_PARCEIRO_REFERENCIA]
                      ,C.[DT_CRIACAO]
                      ,C.[DSC_ARQUIVO]
                      ,C.[DT_ATUALIZACAO]
                      ,TR.DESC_TIPO_REMUNERACAO
                      ,SP.desc_status_processo
                      ,AM.desc_motivo
                      ,DATEDIFF(DAY, HP.DT_HISTORICO, GETDATE()) AS SLA
                      ,P.cnpj_parceiro
                      ,P.nom_razao_social
                      ,E.NUM_MES_COMISSAO
                      ,E.NUM_ANO_COMISSAO
                    ,case when  c.cod_tipo_remuneracao=4 then 'Mensal' else T.desc_tipo_quinzena end AS PERIODO
            FROM [CON_PROTOCOLO_CONTESTACAO] C
            LEFT JOIN REM_ESPELHO E ON E.COD_ESPELHO = CAST(C.COD_ESPELHO_ASSOCIACAO AS BIGINT)
            LEFT JOIN GAC_TIPO_QUINZENA T ON T.cod_tipo_quinzena = E.cod_periodo_Comissao
            INNER JOIN ADM_TIPO_REMUNERACAO TR ON TR.cod_tipo_remuneracao = C.cod_tipo_remuneracao
            INNER JOIN CON_CONTESTACAO_HISTORICO_PROCESSO HP ON HP.COD_PROTOCOLO_CONTESTACAO = C.COD_PROTOCOLO_CONTESTACAO  AND DT_MUDANCA_FILA is null
            INNER JOIN ADM_STATUS_PROCESSO SP ON SP.cod_status_processo = HP.cod_status_processo
            INNER JOIN ADM_MOTIVO AM ON AM.cod_motivo = HP.COD_MOTIVO
            LEFT JOIN GDC_PARCEIRO P ON P.cod_parceiro = C.COD_PARCEIRO_REFERENCIA
            LEFT JOIN GDC_SEGMENTO SG ON SG.cod_segmento = P.cod_segmento
            LEFT JOIN GDC_CANAL canal ON canal.cod_canal = SG.cod_canal
            LEFT JOIN GDC_CANAL_PERFIL perfil ON perfil.cod_canal_perfil = canal.cod_canal_perfil
        WHERE
            (C.COD_PROTOCOLO_CONTESTACAO = @COD_PROTOCOLO_CONTESTACAO OR @COD_PROTOCOLO_CONTESTACAO IS NULL)
            AND (perfil.cod_canal_perfil = @PERFIL OR @PERFIL IS NULL)
            AND (
                @LOGIN IS NULL
                OR (COD_USUARIO_RESPONSAVEL IS NULL OR COD_USUARIO_RESPONSAVEL = '')
                OR (COD_USUARIO_RESPONSAVEL IS NOT NULL AND COD_USUARIO_RESPONSAVEL = (SELECT cod_usuario FROM ADM_USUARIO WHERE Login = @LOGIN))
                OR (SELECT COUNT(*) FROM ADM_USUARIO where sit_libera_pedido = 1 AND Login = @LOGIN) = 1)
            AND (@COD_MENU IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (
                    SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_HISTORICO_PROCESSO
                    WHERE COD_MENU = @COD_MENU AND DT_MUDANCA_FILA IS NULL
                    AND (DATEPART(MONTH,DT_HISTORICO) = @MES OR @MES IS NULL) AND (DATEPART(YEAR,DT_HISTORICO) = @ANO OR @ANO IS NULL)
                ))
            {0}
            AND (@PERIODO IS NULL  OR @PERIODO = DSC_PERIODO_PAGAMENTO)
            AND (C.COD_TIPO_REMUNERACAO = @COD_TIPO_REMUNERACAO OR @COD_TIPO_REMUNERACAO IS NULL)
            AND (@COD_GRUPO_CONTESTACAO IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_ESPELHO_ITEM WHERE COD_GRUPO_CONTESTACAO = @COD_GRUPO_CONTESTACAO))
            AND (@COD_TIPO_CONTESTACAO IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_ESPELHO_ITEM WHERE COD_TIPO_CONTESTACAO = @COD_TIPO_CONTESTACAO))
            AND (@COD_MOTIVO_CONTESTACAO IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_ESPELHO_ITEM WHERE COD_MOTIVO_CONTESTACAO = @COD_MOTIVO_CONTESTACAO))
            AND (@COD_STATUS IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_HISTORICO_PROCESSO WHERE COD_STATUS_PROCESSO = @COD_STATUS AND DT_MUDANCA_FILA IS NULL))
            AND (@COD_MOTIVO IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_HISTORICO_PROCESSO WHERE COD_MOTIVO = @COD_MOTIVO AND DT_MUDANCA_FILA IS NULL))
            AND (@CARREGAR_DIVERGENTES = 1 OR (@CARREGAR_DIVERGENTES = 0 AND C.COD_PROTOCOLO_CONTESTACAO IN (select cod_protocolo_contestacao from CON_CONTESTACAO_ESPELHO_ITEM where sit_divergente = 0)))
             ", string.IsNullOrEmpty(parceirosGestaoCarteira) ? "" : string.Format("AND P.cod_parceiro IN ({0})", parceirosGestaoCarteira)); ;

            Dictionary<string, object> parametros = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(valorPesquisaDinamica) && !string.IsNullOrEmpty(campoPesquisaDinamica))
            {
                sql += string.Format("AND (CAST({0} AS VARCHAR(MAX)) LIKE '%' + @VALOR_PESQUISA_DINAMICA + '%')", campoPesquisaDinamica, valorPesquisaDinamica);
                parametros.Add("@VALOR_PESQUISA_DINAMICA", valorPesquisaDinamica);
            }

            sql += "  ORDER BY SLA DESC ";

            parametros.Add("@LOGIN", usuarioAutenticado ?? (object)DBNull.Value);
            parametros.Add("@PERFIL", perfil ?? (object)DBNull.Value);
            parametros.Add("@COD_PROTOCOLO_CONTESTACAO", codigoProcotolo ?? (object)DBNull.Value);
            parametros.Add("@CARREGAR_DIVERGENTES", carregarDivergentes ? 1 : 0);
            parametros.Add("@COD_MENU", codigoMenu ?? (object)DBNull.Value);
            parametros.Add("@PERIODO", periodo ?? (object)DBNull.Value);
            parametros.Add("@MES", mes ?? (object)DBNull.Value);
            parametros.Add("@ANO", ano ?? (object)DBNull.Value);
            parametros.Add("@COD_STATUS", codigoStatus ?? (object)DBNull.Value);
            parametros.Add("@COD_MOTIVO", codigoMotivo ?? (object)DBNull.Value);
            parametros.Add("@COD_TIPO_REMUNERACAO", codigoTipoRemuneracao ?? (object)DBNull.Value);
            parametros.Add("@COD_GRUPO_CONTESTACAO", codigoGrupoContestacao ?? (object)DBNull.Value);
            parametros.Add("@COD_TIPO_CONTESTACAO", codigoTipoContestacao ?? (object)DBNull.Value);
            parametros.Add("@COD_MOTIVO_CONTESTACAO", codigoMotivoContestacao ?? (object)DBNull.Value);

        }

        using (TFPlusDO db = GetConnection<TFPlusDO>())
        {
            return db.Query(sql, parametros);
        }

    }

Comment: @GWER Desculpe, nós dois editamos ao mesmo tempo e o sistema por algum motivo deu preferência à minha edição. Se você tiver alguma outra edição a sugerir, sinta-se a vontade.
Comment: O sql tá fora do escopo do using. Deveria ter declarado o `sql` fora do else, o mesmo com o `parametros`.
Comment: @Patrick escreve uma resposta sobre isso.
Comment: @VictorStafusa Obrigado pelo comentário, mas a minha edição foi basicamente a mesma que a sua! De qualquer jeito agradeço a preocupação, e sua edição está ótima assim. ;)
Answer: No C# (e em muitas outras linguagens), existem os escopos, que são contextos que delimitam a área de atuação de uma variável, por exemplo.
Se você tentar fazer
public String Foo(int y, int x) //escopo externo
{
    if (x == y) //escopo interno
    {
        String z = "Igual";
    }
    return z;
}

Irá dar erro, pois o z está em um escopo mais interno que o return.
Em C#, um truque que você pode usar para não esquecer isso é: tudo o que estiver declarado dentro das chaves, não pode ser referenciado fora delas.

O problema no seu código é que você simplesmente declarou as variáveis sql e parametros em escopos diferentes.
Puxe-as para um nível acima, fora do else, e tudo ficará ok.
public DataSet PesquisarProtocolos(argumentos...)
{
    String sql;
    Dictionary<string, object> parametros;
}

Comment: Boa visualização.
Answer: Faça assim que resolverá o seu problema:
*Observe que eu apenas inserir as variáveis no inicio do método. Dependendo da sua aplicação, talvez seja necessário fazer uma verificação nas variáveis.
public DataSet PesquisarProtocolos(string usuarioAutenticado, long? codigoProcotolo, int? codigoMenu, string campoPesquisaDinamica, string valorPesquisaDinamica, string periodo, int? mes, int? ano, int? codigoStatus, int? codigoMotivo, int? codigoTipoRemuneracao, int? codigoGrupoContestacao, int? codigoTipoContestacao, int? codigoMotivoContestacao, bool carregarDivergentes, int? perfil = null, string parceirosGestaoCarteira = "", int codigoCargo = 0)
{
    Dictionary<string, object> parametros = new Dictionary<string, object>();
    string sql = string.Empty;
    if ((codigoCargo == 9) || (codigoCargo == 1029) || (codigoCargo == 1030))
    {
        //vou colocar depois o código
    }
    else if ((codigoCargo == 8) || (codigoCargo == 11))
    {
        //vou colocar depois o código
    }
    else
    {
        sql = string.Format(@"
    SELECT DISTINCT
            C.[COD_PROTOCOLO_CONTESTACAO]
            ,C.[COD_PROTOCOLO_CONTESTACAO_RELACIONADO]
            ,C.[QTD_LINHAS_PROCESSADAS]
            ,C.[QTD_LINHAS_DIVERGENTES]
            ,(SELECT TOP 1 LOGIN FROM ADM_USUARIO U WHERE U.cod_usuario = C.COD_USUARIO_RESPONSAVEL) [COD_USUARIO_RESPONSAVEL]
            ,C.[DSC_PERIODO_PAGAMENTO]
            ,C.[NUM_ANO_PAGAMENTO]
            ,C.[NUM_MES_PAGAMENTO]
            ,C.[COD_ESPELHO_ASSOCIACAO]
            ,C.[COD_TIPO_REMUNERACAO]
            ,C.[NUM_MES_REFERENCIA]
            ,C.[NUM_ANO_REFERENCIA]
            ,C.[COD_PARCEIRO_REFERENCIA]
            ,C.[DT_CRIACAO]
            ,C.[DSC_ARQUIVO]
            ,C.[DT_ATUALIZACAO]
            ,TR.DESC_TIPO_REMUNERACAO
            ,SP.desc_status_processo
            ,AM.desc_motivo
            ,DATEDIFF(DAY, HP.DT_HISTORICO, GETDATE()) AS SLA
            ,P.cnpj_parceiro
            ,P.nom_razao_social
            ,E.NUM_MES_COMISSAO
            ,E.NUM_ANO_COMISSAO
        ,case when  c.cod_tipo_remuneracao=4 then 'Mensal' else T.desc_tipo_quinzena end AS PERIODO
FROM [CON_PROTOCOLO_CONTESTACAO] C
LEFT JOIN REM_ESPELHO E ON E.COD_ESPELHO = CAST(C.COD_ESPELHO_ASSOCIACAO AS BIGINT)
LEFT JOIN GAC_TIPO_QUINZENA T ON T.cod_tipo_quinzena = E.cod_periodo_Comissao
INNER JOIN ADM_TIPO_REMUNERACAO TR ON TR.cod_tipo_remuneracao = C.cod_tipo_remuneracao
INNER JOIN CON_CONTESTACAO_HISTORICO_PROCESSO HP ON HP.COD_PROTOCOLO_CONTESTACAO = C.COD_PROTOCOLO_CONTESTACAO  AND DT_MUDANCA_FILA is null
INNER JOIN ADM_STATUS_PROCESSO SP ON SP.cod_status_processo = HP.cod_status_processo
INNER JOIN ADM_MOTIVO AM ON AM.cod_motivo = HP.COD_MOTIVO
LEFT JOIN GDC_PARCEIRO P ON P.cod_parceiro = C.COD_PARCEIRO_REFERENCIA
LEFT JOIN GDC_SEGMENTO SG ON SG.cod_segmento = P.cod_segmento
LEFT JOIN GDC_CANAL canal ON canal.cod_canal = SG.cod_canal
LEFT JOIN GDC_CANAL_PERFIL perfil ON perfil.cod_canal_perfil = canal.cod_canal_perfil
WHERE
(C.COD_PROTOCOLO_CONTESTACAO = @COD_PROTOCOLO_CONTESTACAO OR @COD_PROTOCOLO_CONTESTACAO IS NULL)
AND (perfil.cod_canal_perfil = @PERFIL OR @PERFIL IS NULL)
AND (
    @LOGIN IS NULL
    OR (COD_USUARIO_RESPONSAVEL IS NULL OR COD_USUARIO_RESPONSAVEL = '')
    OR (COD_USUARIO_RESPONSAVEL IS NOT NULL AND COD_USUARIO_RESPONSAVEL = (SELECT cod_usuario FROM ADM_USUARIO WHERE Login = @LOGIN))
    OR (SELECT COUNT(*) FROM ADM_USUARIO where sit_libera_pedido = 1 AND Login = @LOGIN) = 1)
AND (@COD_MENU IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (
        SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_HISTORICO_PROCESSO
        WHERE COD_MENU = @COD_MENU AND DT_MUDANCA_FILA IS NULL
        AND (DATEPART(MONTH,DT_HISTORICO) = @MES OR @MES IS NULL) AND (DATEPART(YEAR,DT_HISTORICO) = @ANO OR @ANO IS NULL)
    ))
{0}
AND (@PERIODO IS NULL  OR @PERIODO = DSC_PERIODO_PAGAMENTO)
AND (C.COD_TIPO_REMUNERACAO = @COD_TIPO_REMUNERACAO OR @COD_TIPO_REMUNERACAO IS NULL)
AND (@COD_GRUPO_CONTESTACAO IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_ESPELHO_ITEM WHERE COD_GRUPO_CONTESTACAO = @COD_GRUPO_CONTESTACAO))
AND (@COD_TIPO_CONTESTACAO IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_ESPELHO_ITEM WHERE COD_TIPO_CONTESTACAO = @COD_TIPO_CONTESTACAO))
AND (@COD_MOTIVO_CONTESTACAO IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_ESPELHO_ITEM WHERE COD_MOTIVO_CONTESTACAO = @COD_MOTIVO_CONTESTACAO))
AND (@COD_STATUS IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_HISTORICO_PROCESSO WHERE COD_STATUS_PROCESSO = @COD_STATUS AND DT_MUDANCA_FILA IS NULL))
AND (@COD_MOTIVO IS NULL OR C.COD_PROTOCOLO_CONTESTACAO IN (SELECT COD_PROTOCOLO_CONTESTACAO FROM CON_CONTESTACAO_HISTORICO_PROCESSO WHERE COD_MOTIVO = @COD_MOTIVO AND DT_MUDANCA_FILA IS NULL))
AND (@CARREGAR_DIVERGENTES = 1 OR (@CARREGAR_DIVERGENTES = 0 AND C.COD_PROTOCOLO_CONTESTACAO IN (select cod_protocolo_contestacao from CON_CONTESTACAO_ESPELHO_ITEM where sit_divergente = 0)))
    ", string.IsNullOrEmpty(parceirosGestaoCarteira) ? "" : string.Format("AND P.cod_parceiro IN ({0})", parceirosGestaoCarteira)); ;

        if (!string.IsNullOrEmpty(valorPesquisaDinamica) && !string.IsNullOrEmpty(campoPesquisaDinamica))
        {
            sql += string.Format("AND (CAST({0} AS VARCHAR(MAX)) LIKE '%' + @VALOR_PESQUISA_DINAMICA + '%')", campoPesquisaDinamica, valorPesquisaDinamica);
            parametros.Add("@VALOR_PESQUISA_DINAMICA", valorPesquisaDinamica);
        }

        sql += "  ORDER BY SLA DESC ";

        parametros.Add("@LOGIN", usuarioAutenticado ?? (object)DBNull.Value);
        parametros.Add("@PERFIL", perfil ?? (object)DBNull.Value);
        parametros.Add("@COD_PROTOCOLO_CONTESTACAO", codigoProcotolo ?? (object)DBNull.Value);
        parametros.Add("@CARREGAR_DIVERGENTES", carregarDivergentes ? 1 : 0);
        parametros.Add("@COD_MENU", codigoMenu ?? (object)DBNull.Value);
        parametros.Add("@PERIODO", periodo ?? (object)DBNull.Value);
        parametros.Add("@MES", mes ?? (object)DBNull.Value);
        parametros.Add("@ANO", ano ?? (object)DBNull.Value);
        parametros.Add("@COD_STATUS", codigoStatus ?? (object)DBNull.Value);
        parametros.Add("@COD_MOTIVO", codigoMotivo ?? (object)DBNull.Value);
        parametros.Add("@COD_TIPO_REMUNERACAO", codigoTipoRemuneracao ?? (object)DBNull.Value);
        parametros.Add("@COD_GRUPO_CONTESTACAO", codigoGrupoContestacao ?? (object)DBNull.Value);
        parametros.Add("@COD_TIPO_CONTESTACAO", codigoTipoContestacao ?? (object)DBNull.Value);
        parametros.Add("@COD_MOTIVO_CONTESTACAO", codigoMotivoContestacao ?? (object)DBNull.Value);

    }

    using (TFPlusDO db = GetConnection<TFPlusDO>())
    {
        return db.Query(sql, parametros);
    }

}


C* algebra inequalities

Question: I need help on proving the following.  If $A$ is a C* algebra with unit, not necessarily commutative, then why is it that $(b^*)b\leq||b||^21$ wrt the partial order induced by the cone $A_+$?  Also, why is it then true that for all $a$ we have $a^*b^*ba\leq||b||^2a^*a$?  In your response, please help me with a solution that does not involve any sort of embedding theorem.  I seem to remember that there is an embedding of all C* algebras into B(H) for some Hilbert space H, but I don't know the proof.  If this is true, please let me know, but I do not want to have it used if at all possible.  Thanks!
Comment: First question: open any book covering $C^\ast$-algebras in a serious way e.g. Arveson recommended [here](http://en.wikipedia.org/wiki/C*-algebra). Second question: order is stable under conjugation by $a$. Last question: http://en.wikipedia.org/wiki/Gelfand-Naimark-Segal_construction which will also be covered in that book.
Comment: I should clarify that my definition of positive element in a C* algebra is one that is $a^*a$ for some $a$.  In the B(H) case or for any of its norm-closed C* subalgebras with unit, this aligns with the idea that $\geq 0$ is equivalent by definition to $T$ being positive.  It is the abstract definition in the general case that gives me problems, as I do not know how to wield it to solve this problem.
Comment: The second quickly follows from the first: if $T\ge 0$ then $a^*Ta\ge 0$ for any $a$. (Precisely, if $T=b^*b$, then $a^*Ta=(ba)^*(ba)$.
Comment: I take it you do not have at your disposal the fact that $b$ is positive if and only if $b=b^*$ and $\sigma(b)\subseteq [0,\infty)$?
Comment: Thank you Jonas.  that was very helpful.
Answer: The easiest way to prove the first inequality is indeed by embedding in $B(H)$ (via the universal representation).
Anyway, it can be done in different ways depending on what you want to use. One more algebraic way would be to notice that the spectrum of $\|b\|^2-b^*b$ is
$$\tag{1}
\{\|b\|^2-\lambda:\ \lambda\in\sigma(b^*b)\}.
$$
Then you can also notice that the spectral radius of $b^*b$ is
$$
r(b^*b)=\lim_{n\to\infty}\|(b^*b)^n\|^{1/n}\leq\|b^*b\|=\|b\|^2.
$$
This tells us that any $\lambda$ in $\sigma(b^*b)$ satisfies $-\|b\|^2\leq\lambda\leq\|b\|^2$ (I'm using here that $\sigma(b^*b)\subset\mathbb{R}$, which is easy to obtain from the fact that $b^*b$ is selfadjoint); so all the elements in the set (1) are non-negative. Now we can apply functional calculus to the selfadjoint operator $c=\|b\|^2-b^*b$ with the function $g(t)=t^{1/2}$ (possible since the spectrum of $c$ is nonnegative); the operator $g(c)$ is selfadjoint and $\|b\|^2-b^*b=g(c)^*g(c)\geq0$.
The second inequality follows from the first one and the fact that if $x\leq y$, then $a^*xa\leq a^*ya$ (because $y-x=z^*z$, so $a^*(y-x)a=a^*z^*za=(za)^*za\geq0$.
Comment: I thought that GNS referred to the particular representation induced by a state, while the Gelfand-Neumark theorem is the one that says every C*-algebra can be embedding in $B(H)$.  The Gelfand-Neumark theorem can be proved roughly by using Hahn-Banach to get a bunch of states, and then taking the direct sum of their GNS representations.
Comment: A potential problem here is that it is nontrivial to show from the abstract definition of a C*-algebra that $b^*b$ has spectrum contained in $[0,\infty)$.  This fact is also useful in proving the Gelfand-Neumark theorem.
Comment: I haven't read about GNS for many years, so I don't claim that I'm using the names in the "proper" way. Regarding the spectrum thing, I think that my argument also works if we only use that $\lambda$ is real, and that one is easier to obtain; I'll edit accordingly.
Comment: Yes, good point. $\sigma(b^*b)\subseteq [-\|b\|^2,\|b\|^2]$ suffices to show that $\sigma(\|b\|^21-b^*b)\subseteq[0,\infty)$, and then to finish it suffices to know just enough functional calculus to get a positive square root of $\|b\|^21-b^*b$.
Comment: Good point too. I'll add the functional calculus part.
Comment: I was able to use your hint in the comments.  There is a way to prove this without using such advanced machinery.  Functional calculus will do.  f of a spectrum is the spectrum of f.
Comment: I saw several solutions here involving the GNS construction.  But the GNS construction with which I'm familiar only says that unital C* algebras with a positive faithful state linear functional defined on them can be embedded into B(H) for some H.  Why does every unital C* algebra have a such a faithful state?
Comment: The point is that states separate points (and this is a consequence of Hahn-Banach and some positivity considerations). If your algebra is separable, you can then get a countable family $\{\phi_n\}$ of states that separates points, and then you consider $\sum_n 2^{-n}\phi$. When the algebra is non-separable you can still get a faithful unbounded functional. Now, to say that every C$^*$-algebra embeds in $B(H)$ one does not need GNS; it can be done via the universal representation (I'll correct that in the answer).

C* algebra inequalities


Issues with Today Widget extension

Question: I have a Today Widget for my app, however I have been told about an issue with it.
Basically, what seems to be happening (I can't test this for myself) is that the widget will sometimes just display 'unable to load' and other times it will just display with a height of 0.
I can't really see why this is happening. I've tested it out on my device and the simulator for weeks now and have never ran into this issue.
I was wondering if it could possibly be down to the refresh code:
<code>    func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
    // Perform any setup necessary in order to update the view.

    var defaults = NSUserDefaults(suiteName: "group.AffordIt")
    var newCheck = defaults.boolForKey("new")

    if newCheck == true {
        completionHandler(NCUpdateResult.NewData)
    } else {
        completionHandler(NCUpdateResult.NoData)
    }
}
</code>
'newCheck' is true whenever something changes within my app that needs to be displayed in the widget.
Does anyone know what the possible causes of these issues are?
Answer: "unable to load" message appears if your extension crashes often. You can try to re-enable it by removing and adding the extension again.
Comment: I released an update to my app to address another bug. I didn't modify the widget code at all and it seems to have fixed it anyway so maybe it is an iOS 8 bug. The 'unable to load' error still displays if the user tries to use the widget without ever having opened the app yet though. So is there any way of changing this message?
Comment: @user3746428 you can create a `NSUserDefaults` key (Google how to read shared defaults between app and widget) that is a simple `BOOL` indicating whether your app has been run first. Check the key when your app starts and if it's `false` display a message telling the user to run the app first.
Answer: Are you using your own view controller and xib instead of using storyboard? If yes, it is probably that you didn't set the preferredContentSize in your view controller.
try to put the following code in the init function of ur view controller:
<code>    self.preferredContentSize = CGSizeMake(320, 100);
</code>
I have just began the extension programming today so I am not sure is it really helpful for u or not. Here is the result in my own widget:
Answer:
Press Edit button in today extensions
Remove your extension
Add your extension again.

Issues with Today Widget extension


Monoid and category

Question: Let $M$ be a monoid.
Let $a, b$ be elements of $M$.
We denote $\operatorname{Hom}(a, b) = \{s\ |\ sb = a\}$.
Then we get a category whose set of objects is $M$.
We denote this category by $C(M)$.
Let $M, N$ be monoids.
Suppose $C(M)$ is isomorphic to $C(N)$.
Is $M$ isomorphic to $N$?
Answer: Your claim is false. Observe that, if $M$ is a group, then $C (M)$ is a category where there is exactly one morphism between any two objects. But the isomorphism class of such a category is determined uniquely by the cardinality of its object set. Thus, for example, $C (\mathbb{Z} / 4)$ is isomorphic to $C (\mathbb{Z} / 2 \times \mathbb{Z} / 2)$.

Monoid and category


Get my database under Version Control using a DVCS [Mercurial]

Question: What would be the best approach for versioning my whole database ?
Creating a file for each database object (table,view,procedsure..) or rather having one file for all DDL scripts and any new change will be put in a separate file ?
What about handling changes made in a Database manager tool ?
I'd like to have a generic solutions for any kind of RDBMS.
Are there any other options ?
Comment: Microsoft SQL Server can be put on Source Safe Version Control, I'm not informed of other similar solutions. I'd really like to find some other solution that works for other databases to.
Comment: @Flakron Bytyqi: **Source Safe**?! If [Eric Sink](http://www.sourcegear.com/vault/) sees this, he will personally go to your house and paper-cut you to half death with a sales invoice.
Answer: I'm a huge VCS fan in general and a big Mercurial booster, but I really think you're going down the wrong path.
VCSs aren't just about iterative changes, the "what", they're also about answering the "who", "when", and "why".  For a database those answers are a lot less interesting or hard to provide to the VCS.  If you're doing nightly exports and commits the "who" will always be "cron" and the "why" will always be "midnight".
The other thing modern VCSs do really well is helping you merge changes from multiple branches.  That's less applicable in the database world.  Very seldom do you say "I want this table structure, but this data", and if you do the text/diff merge isn't going to help you much.
The thing that does do "what" and "when" very well is an incremental backup system, and that's probably the better fit.
At work we use Tivoli and at home I use rdiff-backup and duplicity, but there are plenty of great options.
I guess my general rule of thumb is "if it was typed by hand by a human then it does into source control, and if it was generated/exported then it goes in the incremental backups"
Certainly you can make this work, but I don't think it will buy you much over the more traditional backup solutions.
Comment: I am inclined to disagree. We work on our database with several devs and growing, and things become a mess because we are not able to easily track the changes to our code. The data isn't the problem, that can be handled with regular backups. It's the code that needs structure.
Answer: Have a look at this post
Answer: If you need generic solution - put everything in the scripts (simple text files) and put under Version Control system (can be used any of VCS).
Grouping similar database objects into scripts will be depend on your requirement.
So you may for example:
Store table/indexes/ in one or several script
   Each procedure store in individual script or combine small procedures into one script.
However need to remember one important thing with this approach: don't forget change scripts if you changed table/view/procedure directly in databases and don't create/recreate/compile you db objects in database after changing scripts.
Answer: SQL Source Control currently supports SVN and TFS, but Mercurial requests are increasing rapidly and we're hoping to have a story for this very soon.
We use UserVoice to measure demand so please vote accordingly if you're interesting in this: http://redgate.uservoice.com/forums/39019-sql-source-control
Comment: Good news - SQL Source Control has now been released with support for Mercurial (and any source control system with a suitable command line).


If partial regression coefficient is zero, then $Y$ is independent of $X_i$ conditional on all other regression variables

Question: In a textbook Causal Inference in Statistics - A Primer (p. 81), it says

Given the regression equation $$y=r_{0}+r_{1} x_{1}+r_{2}x_{2}+\cdots+r_{n} x_{n}+\epsilon$$
if $r_{i}=0$, then $Y$ is independent of $X_i$ conditional on all the
other regression variables.

I get that if $r_{i}=0$, a correlation between $Y$ and $X_i$ is 0. But how can they be conditionally independent?
Answer: Under the condition that all the $X_k$ with $k\ne i$ are fixed, i.e. $X_k = x^\ast_{k}$, we have that $Y$ is given as:
$$
\begin{align}
Y &= r_0 + r_1x^\ast_1 + \ldots + r_{i-1}x^\ast_{i-1} \;+ r_i x_i + \; r_{i+1}x^\ast_{i+1} + \ldots + r_nx^\ast_n + \epsilon\\
    &= f + r_ix_i + \epsilon,
\end{align}
$$
where $f=r_0 + \sum_{k\ne i} r_kx^\ast_k$ is simply a fixed constant. Now, if $r_i=0$, $Y$ reduces to
$$
Y = f + \epsilon,
$$
i.e. the noise $\epsilon$ shifted by $f$ and thus is clearly independent of $X_i$ (I presume that the noise is defined to be independent of all $X_r$).