Carregar arquivo (imagem), com PHP para enviar para AWS S3

Question: Atualmente eu tenho um script que eu recebo a imagem a partir de um post como este:
$amazonS3 = new AmazonAwsS3;
$amazonS3->uploadFile($_FILES['anexo']['tmp_name'], $_FILES['anexo']['name'], "sig/$class/$idAmdamento");

porém ao inves de eu pegar esse arquivo de um POST, eu preciso agora pegar o arquivo dentro de um diretório e carrega-lo para a amazonS3, mas eu não estou conseguindo faze-lo. tentei ler com o file(), readfile(), file_get_content() ex: $arquivo = readfile('../arquivos/chamados/anexo_1377633937.jpg'); mas o array vem vazio....
nesse caso eu consigo fazer o download da imagem, mas não consigo ler a imagem e armazena-la no temp do PHP para envia-la para outro local
header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header ('Content-Disposition: attachment; filename='.$a->getArquivoNome().';');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header ('Content-Length: '.filesize('../arquivos/chamados/'.$a->getArquivo()));
        ob_clean();
        flush();
        readfile('../arquivos/chamados/anexo_1377633937.jpg');

alguém pode me ajudar? :)
Answer: $amazonS3 = new AmazonAwsS3;
$directory = '/path/to/my/directory';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));
foreach($scanned_directory as $f){
    $amazonS3->uploadFile($directory.$f, $directory.$f, "sig/$class/$idAmdamento");
    // se for colocar o exclui file cria o unlink
    // @unlink($directory.$f);
}

Na verdade, você só vai pegar o NOME DO ARQUIVO DE ORIGEM e NOME DO ARQUIVO NO DESTINO não precisa passar necessariamente um ponteiro para o registro e sim os filenames
Comment: cara, muito obrigado, eu sei que a formulação da minha pergunta não foi boa, mas você tirou um tempo para responde-la e me ajudou muito mesmo, obrigado.


How to get the p-value for the full model from R's coxph?

Question: In a coxph model with 2 variables (let's say age and sex), how can I get the p-values for LR, Wald and score tests which I see in the summary(coxphobject) as below?
Concordance= 0.653  (se = 0.058 )
Rsquare= 0.085   (max possible= 0.924 )
Likelihood ratio test= 30.09  on 12 df,   p=0.002708
Wald test            = 34.73  on 12 df,   p=0.0005169
Score (logrank) test = 34  on 12 df,   p=0.0006736,   Robust = 17.61  p=0.1279

I think those values represented in the summary as p=... for each model are the p-values for the full model, but I cannot figure out how to retrieve them. If there is only one variate, let's say age, then I can retrieve the p-value using
summary(coxphobject)$coefficients[5], which is the same as the one I see for the Wald test in the summary(coxphobject). But when there are two variables (age and sex), summary(coxphobject)$coefficients[1,5] and summary(coxphobject)$coefficients[2,5] give the p-values for age and sex separately, but they both are different from the p-values I see for the full model in the summary(coxphobject) for LR, Wald and score tests.
I appreciate any help. Thanks.
Answer: 1) Put summary(coxphobject) into a variable
summcph <- summary(coxphobject)

2) examine it with str()
str(summcph)

Values! Values everywhere!
so we find, (proceeding line by line in your above output):
a) the Concordance values
summcph$concordance

b) the Rsquare values
summcph$rsq

c) The Likelihood ratio test values
summcph$logtest

d) The Wald test values
summcph$waldtest

e) The score test values
summcph$sctest

f) The robust values
summcph$robscore

It really helps if you post a reproducible example, rather than make us go find your data set in order to check we're doing all the options the same. For example, you didn't mention you had a cluster term. (It would take an extra few moments for you, and would have saved me ten minutes while I tried to figure out why I couldn't get the last couple of values. At the least you could have mentioned which example you ran in the help!)


Filter data from two content types with different criteria in view

Question: I've got these two content types, A and B. It's pretty straightforward to set up and display them in the same view. However, I can't get them filtered. I've added two filters rules, one for each content types, a1 and b1 respectively, in the hope that I can extract the right parts of the data from A and B and show them in my view. But that doesn't work out.
//
a1=published and content type A and category=aa
b1=published and content type B and tag=bb
//
Here is what I got while trying to do so:

no rules at all,
view displays all the stuff from A and B
rule a1,
view displays A only
rule b1,
view displays B only
rule a1 or b1,
shows nothing

filter groups i used

Is there anything wrong or filter criteria can only be applied?
Any help is appreciated.
--update 1--
I did some more experiments about grouping filter criteria:
 - case 1
Content: Published (Yes)  AND
Content: Type (= Portfolio)
OR
Content: Published (Yes)  AND
Content: Type (= Blog entry)  AND
Content: Tags (= frontpage) | Settings
 - case 2
Content: Published (Yes)  AND
Content: Type (= Portfolio)
Content: Tags (= frontpage) | Settings
OR
Content: Published (Yes)  AND
Content: Type (= Blog entry)  AND

"Content: Tags" is a unique field which only appears in content type "Blog entry" . To my surprise, case 1 and 2 will yield the same result, blog entries, even though "Content: Tags" has nothing to do with the content type "portfolio".
--update 2--
a bug?
Incorrect filter group OR behavior
Answer: a1 and b1 will show nothing, because content type == A AND content type == B is always false for 'A != B'
On filter block, you have a drop down with options. You need to group them into groups connected with OR, so you will have:
published and ( (content type == A and category == aa) or (content type == B and tag == bb ) )

Comment: Hi Mołot, I did use "or" instead of "and", please find the link of screenshot I just added to the original question which displays my filter groups setting. Thanks
Comment: Looks OK, and that's a bad news. It means I cannot help you.
Answer: If you want to show parts (you must mean fields) of your two content types just do the following:

Add a filter of Content type checking the two content types A & B
At the Format/Show section click on content and on that window choose fields.
Then go the Fields section and start adding fields that belong to those types.
Comment: Thanks, but I've already managed to show the fields in view. It is the individual filter criteria that confused me.
Comment: No problem. Glad you solved your problem.
Comment: Actually the problem is still there, I can't filter the right nodes to be shown in my view. I've add some update to the original question. THX
Comment: case 1 seems correct. are you sure you have created nodes of protfolio type?
Comment: yes, I can see them if I use "content type" as the only filters.
Comment: Then maybe you are forgetting to add fields from portfolio type. I think there's no other explanation.


What does TCM connection with Icache in this RISCV version?

Question: In the middle of this page (https://github.com/ultraembedded/riscv), there is a block diagram about the core, I really do not know what is TCM doing in the same block with the Icache ? Is it an optional thing to be inside the CPU ?
Answer: Some embedded systems provide dedicated memory for code and/or for data.  On some of these systems, Tightly-Coupled Memory serves as a replacement for the (instruction) cache, while on other such systems this memory is in addition to and along side a cache, applying to a certain portion of the address space.  This dedicated memory may be on the chip of the processor.
This memory could be some kind of ROM or other memory that is initialized somehow prior to boot.  In any case, TCM typically isn't backed by main memory, so doesn't suffer cache misses and the associated circuitry, usually also has high performance, like a cache when a hit occurs.
Some systems refer to this as Instruction Tightly Integrated Memory, ITIM, or Data Tightly Integrated Memory, DTIM.
When a system uses ITIM or DTIM, it performs more like a Harvard architecture than the Modified Harvard architecture of laptops and desktops.
Comment: It says that ITIM "provide low-latency access to instruction memory", however since it is a kind of ROM, would not be slower ? Also if the core is implemented with icache/TCM as the above RISCV, how would the CPU decide to take the instructions from ?
Comment: By address range, but I don't know how it is configured.
Comment: I see, So this CPU actually working with both icache and TCM. But when does it need to access icache and when does it need to access TCM ? Also, From the link I provided, it says : (0x0000_0000 - 0x0000_ffff 64KB TCM Memory) which is the address range of TCM, and MEM_CACHE_ADDR_MIN = 0
    MEM_CACHE_ADDR_MAX = 32'hffffffff  ..... It seems that cache (it did not specify instruction or data ) has covered the full range of addresses including TCM !! It is confusing a bit to me
Answer: The cache has no address space. CPU does not ask for data from the cache, it just asks for a data, then the memory controller first checks the cache if the data is present in the cache. If it is in the cache, data is fetched, if not then the controller checks the RAM. All processor does is ask for data, it does not care where the data came from. In the case of TCM, the CPU can directly write data to TCM and ask data from TCM since it has a specific address. Think of TCM as a RAM that is close to the CPU.


Using different sets of page objects with the same selenium tests

Question: [This is cross-posted with SQA - https://sqa.stackexchange.com/questions/35081/using-different-sets-of-page-objects-with-the-same-selenium-tests]
I'm working on a selenium test suite for a set of similar websites. The test suite would be execute separately for each site and the tests in the suite are applicable to all websites.
These websites are built on the same underlying platform, however have different theme/scheme and therefore page objects for these sites need to be different.  This is not a case of one or two selectors being different, but majority of selectors different - yet the rest of the structure is the same.
I can easily create two (or three, or whatever) sets of page objects, however I can't figure out how to tell the test executor (Cucumber cli in my case) which page objects to use.
The closest I can come up with is use different package names with common base classes and then individual pages extending from the common base classes. Another possibility is to extract all the selectors into property files and load one or another based on an input parameter, however this would preclude me from using PageFactory. I can also, probably, create separate sets of page objects in different source sets and then compile one or the other based on my need - but, again, I can think of the theory, yet not the execution.
So, what's the right approach and how to achieve this?  If it matters, the project is built using gradle.
Answer: Since the tests are suitable for all the sites I will assume the only difference between the pages is the selectors behind the objects.
cssSelector and xpath provides or. Assuming text field has ID id1, id2 or id3 depends on the page you can use
@FindBy(how = How.CSS, using = "#id1, #id2, #id3")
private WebElement textField;

This will return the WebElement matching one of the ids.
Comment: Thanks - that would be too simple.  Majority of selectors are by css and they are conflicting.  For example, I have selector for "product list items", which is `li.Lb` in one theme, but `li.Lc` in another.  Yet, `li.Lb` is a valid selector in the second one, which will return a set of completely incorrect elements.
Comment: @AleksG There isn't more unique way to locate elements? `li.Lb` doesn't seem to be very unique locator (even if it is unique in specific site). Any way, another option is to override/extend the `FindBy` annotation. This will allow you to add logic to it to support reading from locators property file as you suggested.
Comment: Hm, overriding `FindBy` might actually be an interesting idea - I'll investigate it.
Answer: The solution turned out to be a custom ElementLocator and ElementLocatorFactory with a corresponding custom annotation.  It's a bit more work, but it's a very clear solution.  I published it on github. In short, the implementation allows to do this:
public class MyPage {
    @SearchWith(page="MyPage", name="myElement", locatorsFile="{locators}")
    WebElement someElement

    ...
}

Then run the whole test with -Dlocators=site1.json or -Dlocators=site2.json - and corresponding locators will be loaded from one or the other. It even allows to specify -Dlocators=[site3.json] and load locators from site3.json resource (as obtained using this.getClass().getResourceAsStream(locatorsFile))


How to choose the major, minor, diminished chords, etc. along the chord progression

Question: This is a typical circle of fifths chord progression.

My question is how do we choose the chord to be major, minor, or diminished along with the progression:

A  -> D -> G -> C -> F -> B -> E -> A?
Why is that:
Am  -> Dm -> G -> C -> F -> Bdim -> E -> Am?
What are some golden rules to determine the major, minor, diminished along with the progression?

The image is from this video.
Comment: Seriously, stop watching theory videos and start playing songs on the piano. If you had played the chords, you would have noticed that they use only the white keys of the piano. Apart from E which has a raised G. Really, just stop watching the theory hoo-ha. Spend a few months playing songs.
Comment: @piiperiReinstateMonica - If wonderich is anything like me, s/he could play songs for *years* without learning a thing about music theory other than rudiments. I only became conscious of chord progressions back when I started taking Harmony 3 lessons from the Royal Conservatory of Music curriculum (read: Grade 8-9).
Comment: @piiperiReinstateMonica - I notably started developing absolute pitch before being aware of chord progressions. My first multi-instrument arrangement, which I made in Grade 8 once I recognized Middle C and nothing else with my absolute pitch, was done with no knowledge of chord progressions and was threadbare as hell. (It was of "Sing, Sing, Sing".)
Answer: The reason it's Am Dm G C F Bo E is that they're all diatonic - their notes all belong to the same key - A minor. That way, they all sound like they 'belong' together, which, of course, they will do.
They don't have to be those minors, majors, etc. Am D G C F B E works almost as well. Obviously it's the circle of 4ths, which crops up in plenty of different music - and the ii>V>I that occurs in so many pieces is part of that sequence. The preceding chord is the V (or v) of the next, hence the 'dominant' label.
Choice of chord? Depends on the melody - the notes from that will usually need to blend with those of the accompanying chord, so one will dictate what the other could be.
Comment: Thank you! +1. Other than Am D G C F B E, could you give additional examples using the same progression: A -> D -> G -> C -> F -> B -> E -> A, or variation of this (longer or shorter) progression ?
Answer: We can tell you which flavour of each chord to use if you want to keep the sequence diatonic to one key.  But there's no particular reason to do that!
The strength of the progression lies in the 'cycle of 5ths' bass line.  I suggest you maintain the same harmonic density - all triads, all 7th chords etc. - otherwise it can sound a bit disjointed.  Apart from that, there are no wrong answers.  Musical composition involves choice, otherwise from any given starting chord there'd only be one 'correct' path.  So choose!
Answer: You can choose the chord types Am -> Dm -> G -> C -> F -> Bdim -> E -> Am for A -> D -> G -> C -> F -> B -> E -> A because all of those chords fit in A minor (with no tonicizations and no modulations). In A minor, you can interpret those chords as i -> iv -> VII -> III -> VI -> ii° -> V -> I.
You get more flexibility by allowing tonicizations and modulations (especially since circle of fifths progressions often involve both of those). For example, you can use B instead of Bdim in the above chord progression so you use V of -> V -> i instead of ii° -> V -> i.
Put accidentals on some of those chord labels in the skeleton and you can come up with some spicier chord progressions while still using exclusively common practice period harmony. For example, you can use A -> D -> G -> C -> F -> B♭ -> E -> A for I -> IV -> V of -> V of -> V of -> ♭II -> V -> I. There's also the similar Am -> D -> G -> C -> F -> B♭ -> E -> Am for i -> IV -> V of -> V of -> V of -> ♭II -> V -> i. For a different sound, there's also A -> D -> G♯ -> C♯ -> F♯ -> B -> E -> A for I -> IV -> V of -> V of -> V of -> V of -> V -> I.
Comment: Thank you! +1. Could you give additional examples using the same progression: A -> D -> G -> C -> F -> B -> E -> A, or variation of this progression?
Comment: @wonderich - I added 2 more examples to my answer just now. Note that they involve secondary dominant chains.


Xcode Unit Tests: Xcode doesn't stop at breakpoints

Question: Using Xcode 6.3 Beta 2 with Units Tests I have the following problem:
When I do unit testing the breakpoints in the unit-test module work but the break codes in the code under test don't are ignored.
Any ideas?
Comment: While this is quite and old question, I am now having the same issue on XCode 6.3 (6D570) iOS SDK 8.3 released on 8/Apr/2015!!!! - it does not stop on any breakpoints at all and none of the solutions listed in other posts of SO resolve the issue
Comment: It works normally on newly created projects, so the issue seems to be with projects created on earlier versions of XCode ...
Comment: @grep Did you ever manage to sort this?
Comment: I still experience this issue at times with XCode 8.3.3. Restarting XCode can help. Sometimes setting a breakpoint on the first line of the method (on the method signature) can also help when a breakpoint within the body of the method does not work.
Comment: My xcode stops on test breakpoints, but blows up one second after..... :(
Comment: Have no such issue on Xcode 7+
Comment: I am getting this problem in case Testing project the breakpoints do not work. Do you guys got any solution.
Comment: Running into same problem. Any solution?
Answer: I had the same issue and the reason was the scheme settings:
1.- Edit your scheme
2.- Choose "Test" in the left panel
3.- Check the "Debug executable" option
That was all.
Answer: Simple point to check even if this post is quite old: Does your Test-Method start with the prefix "test"?
Omitting the prefix doesn't produce a warning and Xcode simply doesn't execute the method any more.
This can look like Xcode doesn't stop at your breakpoint - nevertheless Xcode doesn't execute the method at all!


Color scatterplot by grouping in pandas

Question: Having a pandas df as follows:
# Sample data
data = {
    'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'y': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
    'z': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A']
}

# Creating a pandas DataFrame
df = pd.DataFrame(data)

I try to make a scatterplot that colors each group individually.
I tried (following my intuition..):
df.groupby('z').plot.scatter('x', 'y', color = 'z')

This doesn't work..

So I searched and found:
plt.figure()
for z in df['z'].unique():
    subset = df[df['z'] == z]
    plt.scatter(subset['x'], subset['y'])

This works and produces:
.
But to me, this seems like a 'workaround'. Is there really no way to use the pandas grouping directly as an argument for the plotting method?
Comment: I see, you want the same plot (`groupby` is used to create multiple plots), then it's already well described [here](https://stackoverflow.com/questions/14885895/color-a-scatter-plot-by-column-values). You have options in pure pandas and with `seaborn` that is also a nice alternative for full customization ;)
Comment: `df.plot.scatter('x', 'y', c='z')` is the most straightforward if you have color codes
Comment: @mozway Thx. That is basically what I was searching for.
Comment: Can you provide a example dataset and ideally a schematic of the graph that you would expect?
Comment: @mozway Thx for your reply. I added a `df` and the expected output.
Answer: Use DataFrame.plot.scatter with pass color with convert strings to numeric by Categorical and Categorical.codes, also is possible use custom colormap:
df.plot.scatter('x', 'y', color = pd.Categorical(df['z']).codes, cmap='viridis')

Color scatterplot by grouping in pandas


Duplicate value in autocompletetext

Question: I have an AutoCompleteText receiving information from the database. My problem is that if my table as the same value it will appear duplicate in the suggestions. Is there any sollution to only appear once??
List<String> lista = new ArrayList<String>();

public void onClick(View v) {
            // TODO Auto-generated method stub
            actv.showDropDown();
        }

public void devolvenome(){

    Cursor cursor=d.rawQuery("SELECT * FROM lol;", null);
    if(cursor.moveToLast()){
        lista.add(cursor.getString(cursor.getColumnIndex("cam")));
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,lista);
    text.setThreshold(0);
    text.setAdapter(adapter);
    text.setTextColor(Color.RED);
}

Comment: read this http://www.sqlite.org/lang_select.html
Answer: Try using the DISTINCT keyword in your query like this:
SELECT DISTINCT * FROM LOL;

The DISTINCT keyword can be used to return only distinct (different) values.
Comment: You want to return just 1 of the multiple same values from the database right? If that's correct than this should be the way to go
Comment: i tried and it didn't do anything so i tried: SELECT DISTINCT cam FROM LOL.  It worked.
Answer: Well i just made a little adjust. I don't know if it's the most correct thing to do but it's working:
Cursor cursor=d.rawQuery("SELECT DISTINCT cam FROM lol;", null);
if(cursor.moveToLast()){
    lista.add(cursor.getString(cursor.getColumnIndex("cam")));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,lista);
text.setThreshold(0);
text.setAdapter(adapter);
text.setTextColor(Color.RED);

Duplicate value in autocompletetext


Calculating pm problem: $5$ man and $5$ women running in a race

Question: Let's say there are $5$ man and $5$ women running in a race. Let the variable X that indicates the highest position in ranking for a woman. So, for example, if $X = 1$, that means that a woman took first place(any woman) and if $X = 6$, that means that women took the last places on the ranking.
I guess, obviously there are $10!$ different outcomes for ranking.
How can I calculate $p_X(x)$ with $x = 1, 2, 3, 4, 5, 6$?
Edit : Two or more people cannot take the same place in the ranking. All 10! different outcomes are equally possible.
Comment: Are we to suppose that each ranking is equiprobable? (which of course is completely unlikely for a real race with real people!)
Comment: The women are assumed to be indistinguishable. There are ${10 \choose 5}$ ways to place them in $10$ empty slots. You're correct that $6$ is highest value $X$ can take on.
Comment: You didn't really answer Bram28's question.  Are all of the $10!$ possible outcomes considered equally likely?
Comment: I wasn't responding to Bram28
Comment: @Bram28 Yes, all 10! outcomes are equally possible. I will edit the post.
Answer: The women are assumed to be indistinguishable. There are ${10 \choose 5}$ ways to place them in $10$ empty slots. You're correct that $6$ is highest value $X$ can take on.
If we are assuming every one of the $10$ people are equally fast, then the probability that a woman is in the first position is $\frac{1}{2}$ by symmetry.
The probability that the best position by a woman is $X=2$ is $$\frac{5}{10}\cdot\frac{5}{9}=\frac{{5 \choose 1}}{{10 \choose 1}}\cdot\frac{{5 \choose 1}}{{9 \choose 1}}$$
since a man has to be in the first position and then a woman has to be in the second position
The probability that the best position by a woman is $X=3$ is $$\frac{5}{10}\cdot\frac{4}{9}\cdot\frac{5}{8}=\frac{{5 \choose 2}}{{10 \choose 2}}\cdot\frac{{5 \choose 1}}{{8 \choose 1}}$$
since a man has to be in the first and second position and then a woman has to be in the third position
$\vdots$
The probability that the best position by a woman is $X=6$ is $$\frac{5}{10}\cdot\frac{4}{9}\cdot\frac{3}{8}\cdot\frac{2}{7}\cdot\frac{1}{6}\cdot\frac{5}{5}=\frac{{5 \choose 5}}{{10 \choose 5}}\cdot\frac{{5 \choose 1}}{{5 \choose 1}}$$
Can you go from here to obtain $p_X(x)$?
Answer: Here is a solution where order matters.
$P(X=1)+P(X=2)+P(X=3)+P(X=4)+P(X=5)+P(X=6)$
$=\frac{{5 \choose 1}\times9!}{10!}+\frac{{5 \choose 1}\times{5 \choose 1}\times8!}{10!}+\frac{{5 \choose 2}\times 2! \times{5 \choose 1}\times7!}{10!}+\frac{{5 \choose 3}\times 3! \times{5 \choose 1}\times6!}{10!}+\frac{{5 \choose 4}\times 4! \times{5 \choose 1}\times5!}{10!}\frac{{5 \choose 5}\times 5! \times{5 \choose 1}\times4!}{10!}$
$=\frac{5}{10}+\frac{5\times5}{10\times9}+\frac{5\times4\times5}{10\times9\times8}+\frac{5\times4\times3\times5}{10\times9\times8\times7}+\frac{5\times4\times3\times2\times5}{10\times9\times8\times7\times6}+\frac{5\times4\times3\times2\times1\times5}{10\times9\times8\times7\times6\times5}$


delete or clear session in symfony 4.4

Question: I am saving the current user s data in a session, I am using Symfony 4.4
I am getting and setting the data to the session variable this way
<code>$session = $this->get('session');
$session->set('user', $user);
</code>
is there any way to clear and delete the session after logging out
I tried
<code>$session->invalidate();
</code>
and deleting the session one by using remove and nothing happened
<code>$session->remove('user');
</code>
Comment: Looks like you got something working but just to be clear the get user functionality is in the Symfony framework.  Unless your instructor is not letting you use the SecurityBundle.  Which would actually be a good training approach.
Comment: Symfony already provides a way to get the current user and takes care of the logging out process.  What exactly are you trying to accomplish?
Comment: actually, it's a school project and our tutors are limiting our use of bundles like fosuser etc so we got to implement some functionalities from scratch
Answer: i randomly came across this and it works just fine
<code>$this->get('session')->clear();
</code>

delete or clear session in symfony 4.4


Python Selenium - How to Click AJAX Button? (Selenium not finding XPath)

Question: In Python Selenium, how can I click an AJAX button using XPath?
Example:
driver.find_element_by_xpath('//[@id="btn_fx_contract"]').click

This button is Zebra_Dialog.
The HTML is:
<input type="button" id="btn_fx_contract" class="btn_fx_print_red" value="accept" onclick="fx_contract_save('0000000', 'B')">

The function fx_contract_save is AJAX.
Answer: driver.find_element_by_id('btn_fx_contract').click

Searching by id is a way more reliable way
Answer: As per the HTML to click on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following solutions:

CSS-SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.btn_fx_print_red#btn_fx_contract"))).click()

XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='btn_fx_print_red' and @id='btn_fx_contract']"))).click()


Flag got declined

Question: I recently flaged a post I believe was off topic:
Convert nginx rewrite rule to htaccess rewrite rule
And the flag was declined. Is this correct decision? Should this question not be asked on different community such as Server Fault?
This question is still not answered and I believe if it was asked in correct place, it would be answered already.
Can you tell me why you think this question belongs on Magento SE?
Answer: The flag was automatically declined by the system because in the review queue it got 3 "Leave open" votes: https://magento.stackexchange.com/review/close/130863.
Indeed, this looks like it is not really about Magento, but this can be just our opinion.
Comment: The reason for my flag was because I believe the person who asked the question would get better answer in different community. The question was asked Jan 31 and still didn't receive an answer, do you think it's worth moving the question to different community or leaving it here?
Comment: The question is too old to migrate.
Comment: Answered my question. Thanks Marius.

Flag got declined


Retrieving users from Database on to forms

Question: I have a webform with a select option type field. I need an authenticated user to view other available users in the website in this list. So, it needs to be dynamic by communicating with the database. What is the best way to do this?
Thanks in advance!
Answer: You have to use hook_webform_select_options_info() in your custom module.
I made my first module with that hook because i needed to achieve a similar thing but with people who were linked thanks to module relation. I show you what i did (i change the query to retrieve all users from the site, i'm not an expert in query). It was my first code, so it's not very optimize but it's work.
function my_module_webform_select_options_info() {
  $items['membres'] = array(
  'title' => t('Membres'),
  'options callback' => 'webform_membres_options',
  );
return $items;
}

function webform_membres_options($node)  {
  global $user;
  $store = array();

  $result = db_query("SELECT users.name AS users_name, users.uid AS uid, users.mail AS  users_mail
                      FROM {users} users
                      WHERE (( (users.status <> '0') ))");

 //Store mail|username in an array (good format for select options)
 foreach ($result as $row) {
   $store[$row -> users_mail] = $row -> users_name;
 }
 //All users don't have relationship so we have to check the length of array
 if (count($store > 0)) {
   return $store;
 }
     else {
   return false;
 }
 }

You'll see your list in Load a pre-built option list when you'll build your webform (after selecting "select options") Don't forget to put a default value for the select list.
After you'll see your list in the webform :
Comment: Thanks. I am just a beginner to Drupal and hence I am not that wee versed with stuff. If I am not asking too much, please let me know if I am right. I should now go to the webform.api.php.... add the lines of the code for querying the DB and this should take care of things. Right?
Comment: @user9890 welcome to drupal answers, when you post a question here please ensure it does not ask for a "From scratch implementation".. no one likes to do others' homework, you need to try things on your own first and in case you are stuck ask for help. The [FAQ](http://drupal.stackexchange.com/faq) should help you on what you can and can't ask here. Secondly its taboo to modify/hack a core or contributed module in drupal, you should look up the internet on writing a 'custom module' and usage of hooks in drupal.. there are plentiful resources that would help you with it and get your task done.
Comment: There're plenty of resources when you want to create your first module : [drupal.org](http://drupal.org/node/361112) and [this one is easy to follw](http://www.packtpub.com/article/creating-your-first-module-drupal-7-module-development)
Comment: @optimusprime619 Sorry about that. This is not my homework, it was just a personal website which I am trying to do, with forums and discussions. I wanted to make sure, because I did not want to break the integrity of the site or create any errors by modifying any wrong file. Thank you for the input.
Answer: Here is another aproach. I just used this on a project i am working on.
/**
 * Same as example above
 */
function YOUR-MODULE_webform_select_options_info() {
  $items = array();
  $items['users'] = array(
    'title' => t('Users'),
    'options callback' => '_YOUR-MODULE',
  );

  return $items;
}

/**
 * Get a list of all uids except uid 1
 * This is easier to read.
 */
function _YOUR-MODULE($component, $flat, $filter, $arguments) {

  $all_users = entity_load('user');
  foreach($all_users as $value) {
    $user_list = (array)$value;
    if($user_list['uid'] > 1) {
      $user_names[$user_list['uid']] = $user_list['name'];
    }
  }

  return $user_names;
}

/**
 * Set the default value of the select list to the current user
 */
function YOUR-MODULE_form_alter( &$form, &$form_state,$form_id ){
  global $user;
  $uid = $user->uid;

  //
  if ($form_id == 'webform_client_form_YOUR-WEBFORM-ID' && $uid > 1) {
    // manipulate component values like this:
    $form['submitted']['YOUR-WEBFORM-FIELDNAME']['#default_value'] = $uid;
  }
}

Edit: I added some more comments and a solution for setting the default value of the select list to the current ID.
Comment: Hello and welcome. Answers with code only may work, but they are "doing things by the rote" if they work indeed. If the code is not exactly fit for that particular purpose, they are outright useless. It is much better to describe approach in human readable language and only back it up with code. And if code is most important part of the answer, please at least add some comments to explain what and how it is supposed to do.
Comment: I just updated my example. Hope it helps.


How to Output a List of Summaries From Different Grouping Variables When Using Dplyr::Group_by and Dplyr::Summarise

Question: library(tidyverse)

Using a simple example from the mtcars dataset, I can group by cyl and get basic counts with this...
mtcars%>%group_by(cyl)%>%summarise(Count=n())

And I can group by both cyl and am...
mtcars%>%group_by(cyl,am)%>%summarise(Count=n())

I can then create a function that will allow me to input multiple grouping variables.
Fun<-function(dat,...){
dat%>%
group_by_at(vars(...))%>%
summarise(Count=n())
}

However, rather than entering multiple grouping variables, I would like to output a list of two summaries, one for counts with cyl as the grouping variable, and one for cyl and am as the grouping variables.
I feel like something similar to the following should work, but I can't seem to figure it out. I'm hoping for an rlang or purrr solution. Help would be appreciated.
Groups<-list("cyl",c("cyl","am"))

mtcars%>%group_by(!!Groups)%>%summarise(Count=n())

Answer: Here's a working, tidyeval-compliant method.
library(tidyverse)
library(rlang)

Groups <- list("cyl" ,c("cyl","am"))

Groups %>%
  map(function(group) {
    syms <- syms(group)
    mtcars %>%
      group_by(!!!syms) %>%
      summarise(Count = n())
  })

#> [[1]]
#> # A tibble: 3 x 2
#>     cyl Count
#>   <dbl> <int>
#> 1     4    11
#> 2     6     7
#> 3     8    14
#>
#> [[2]]
#> # A tibble: 6 x 3
#> # Groups:   cyl [?]
#>     cyl    am Count
#>   <dbl> <dbl> <int>
#> 1     4     0     3
#> 2     4     1     8
#> 3     6     0     4
#> 4     6     1     3
#> 5     8     0    12
#> 6     8     1     2


Why tableview cell text not changed according to orientation, while cell height did

Question: my code as below,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Color Cell" forIndexPath:indexPath];
    ......
    ......
    ......

    if (UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
        cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:14.0f];
    } else {
        cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:24.0f];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat rowHeight;
    if (UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
        rowHeight = ([[UIScreen mainScreen] bounds].size.width - 52) / [colorArray count];
    } else {
        rowHeight = ([[UIScreen mainScreen] bounds].size.height - 64) / [colorArray count];
    }
    return rowHeight;
}

When running it, table view could auto reorientate correctly, cell height as well. But cell text size does not change accordingly.
Why? How to fix it?
left is on portrait, right is on landscape
Comment: it seems font size is reduced. i think ratio of cell height and font size is not correct in landscape mode . just reduce the font size further more .
Comment: no, the text sizes in portrait and landscape are exactly same, not changed according to orientation. Only cell height did. I added a snapshot of comparison.
Comment: Do you have a minimum font size set in the IB?
Comment: tried it, even set minimum size (9 pt) samler than the size (14) set in the code. But nothing changed.
Answer: UITableViewCell not reload when change orientations in device,reload your table view after changing orientation
Comment: do you mean `self.tableView reloadData` ? Where to put it ?
Comment: add self.tableView reloadData when change orientation.
Comment: add it in `viewDidLoad` or `(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath`, or other?
Comment: -(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if(port right)
    {
        //reload action;
    }
    else
    {
        //reload action;
    }

}


Customising the contact form

Question: I'm using the contact form inside a block on my frontpage, however the labels are pretty ugly, and I'd like to customise the form a bit.
Is there some template file I can grab and put in my theme? I'm using Drupal 7.
I've done some looking but no luck.
Comment: Does this help you? I'm afraid I use Drupal 6 so can't test. http://bri-space.com/content/theming-contact-form-drupal-7-contactsiteform
Comment: I'm afraid I couldn't get this working.
Answer: I decided to go with a non-Drupal alternative to create my contact form:
jQuery Contact Form
I modified the CSS heavily however :)

Customising the contact form


Why isn't the second whole note's accidental natural?

Question:
Above is a staff. After the third bar, why isn't the second C either sharp or natural?
Comment: I think you don't understand key signatures properly. This might help you in undertanding them: http://www.musictheory.net/lessons/24 .
Comment: The notation in the question is correct. However, it would be foolish not to reinforce it with cautionary accidentals.
Comment: Thanks so much, I really hate reading wiki, for it covers so many unnecessary stuffs. This is highly encouraged.
Comment: You can find many other topics and resources on that site.
Answer: Accidentals (sharps, flats or naturals) only change notes until the end of the bar they are in. So, the C# above doesn't affect the C in the next bar. However, flats or sharps in key-signatures affect all notes in the music, for instance the Bb and Eb above, unless "overruled" by another accidental, for example the B natural above.
Comment: I just want to add although it is unnecessary, most composers would put a natural sign next to the C as a reminder to the musician to play a C instead of a C#.
Comment: @ Dom - yes, they do, and I feel it's clogging up the staves. It's not necessary, the bar line cancels anyway. Take it further, if there's another C in the next bar, should the writer remind us again, after all, it's another bar...
Comment: @Dom Often it's not the composer but the editor who adds the superfluous accidentals.
Comment: There's no flat in front of the C or Cb in the key signature. So, nothing to make it flat.
Comment: I think you might be getting the signs for sharps, flats and naturals mixed up.
Comment: So what you r saying is, there is a natural sign before the first c because there is no bar before it to cancel flat signatures?
Comment: Still doesn't explain my question. Why isn't it a flat c?


Extended Euclid Theorem - Can there be more than one pair of x and y for two numbers A and B

Question: GCD(A,B) is Ax + By. So can there be more than one pair of x and y. If yes, how can I find them?
I used the following code to find x and y :
pair< int ,  int>* extendedeuclid( int a,  int b){
    if(b == 0){
        pair< int,  int>* newpair = new pair< int, int>;
        newpair->first = 1;
        newpair->second = 0;
        return newpair;
    }
    pair< int, int>* oldpair = extendedeuclid(b , a%b);
    pair< int, int>* newpair = new pair< int, int>;
    newpair->first = oldpair->second;
    newpair->second = oldpair->first - ((a/b) * oldpair->second);
    return newpair;
}

When i tried to run this code for sample input a =10 , b = 9
it gives answer x = 1,y = -1 which is correct but is there any way to find other solution like x = -8 and y = 9 in this case .
Comment: this question is about maths and has nothing to do with c++ or programming in general
Comment: I'm voting to close this question as off-topic because it is not about programming but rather belongs on [Mathematics Stack Exchange](https://math.stackexchange.com/) once the questioner has added more of his own work and explained just where he is stuck.
Comment: @Damien: If the OP modifies the question, it gets bumped to the top of the review queue and more people will look at it. People with enough reputation can vote to reopen the question. Five votes will reopen the question, then more answers may be given. For me to vote to reopen, the OP will need to show how this is a practical programming problem. That will be difficult, since I know the answer to the question and the difficulty is all mathematical--the programming is trivial.
Comment: @user463035818: "How can I find…" with the C++ tag is a request for expressing an algorithm in C++ code. If the OP is interested in implementing the algorithm in C++, it is not an unrelated tag.
Comment: @user463035818: The question does not ask for a book, tool, library, tutorial, or other off-site resource. It does ask for information. You could answer that with code, or you could answer it with information about what algorithm would solve the problem and how it could be implemented in C++.
Comment: @user463035818: "How can I find…" is an algorithm question suitable for Stack Overflow.
Comment: @EricPostpischil Its not up to me to decide what question is suitable for SO and which is not. I was merely refering to unrelated tags, that have been removed in the meanwhile
Comment: @EricPostpischil in that case it would consider it as offtopic for "asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow" or maybe some other reason. "Please write some code for me?" is not a question, is it?
Answer: This relation corresponds to the Bézout's identity.
All solutions are given by (x + k*b/gcd(a,b), y -k*a/gcd(a,b)), if (x,y) is a particular solution, where k is an arbitrary integer.
The particular (x,y) solution is for example provided by the extended Euclidian algorithm.
The pair (b/gcd(a,b), -a/gcd(a,b)) is the 'smallest' (u,v) pair such that ua + vb = 0.
Source: Wikipedia!
Comment: @James K Polk It is assumed to be an answer in English! Better to use 'pair'. Thank you again for the correction.
Comment: @James K Polk Thank you for editing. Please note that it was a mathematical answer, not a C++ one. In my mathematics classes a very long time ago, the professor was using the term 'couple'. But it was in French, may be different in English. Anyway, as there is a 'C++' tag, better to use `pair` effectively.
Comment: Yes, I went out on a limb in my edit, in my English math classes our instructors always used the word 'pair', however if you prefer 'couple' you can revert the edit or I'll gladly do it.


Dimension of the poset $(\mathbb{R}^2,\ge)$

Question: I am working on the question about the poset $(\mathbb{R}^2,\ge)$ such that $(x_1,y_1)\ge (x_2,y_2)$ iff $x_1\ge x_2, y_1\ge y_2$. I found the conclusion that the dimension of this poset is $2$, but I am not quite clear about how to prove it (The dimension of a poset is the smallest number of total orders the intersection of which gives rise to the partial order). Any thought would be appreciated.
Answer: Great, so I think you and I are on the same page about why the dimension is at most $2$; we just need to show that the dimension can't be $1$. But if the dimension was $1$, then the partial order $(x_1, y_1) \geq (x_2, y_2)$ would have to be total, and we can check that it isn't. Indeed, $(1, -1)$ and $(-1, 1)$ are incomparable, and this is enough.
Comment: Hello Keeley, thanks a lot for your reply! In your explanation, you mentioned that the dimension is at most $2$ and this is where I am stuck. Is there any theorem offering this upper bound for the dimension? Thanks again.
Answer: As explained in Keeley's answer, the poset does not have dimension $1$, since it is not a total order. It remains to show that it has dimension $\leq 2$, and to do this, we just need to exhibit it as the intersection of two total orders.
The lexicographic order $\leq_{\mathrm{lex}}$ is defined by $(x_1,y_1)\leq_{\mathrm{lex}} (x_2,y_2)$ if and only if $x_1 < x_2$ or ($x_1 = x_2$ and $y_1 \leq y_2$).
The reverse lexicographic order $\leq_{\mathrm{rlex}}$ is defined in the same way, but reversing the roles of $x$ and $y$: $(x_1,y_1)\leq_{\mathrm{rlex}} (x_2,y_2)$ if and only if $y_1 < y_2$ or ($y_1 = y_2$ and $x_1 \leq x_2$).
If you're not familiar with these orders, you should prove that they are total. I claim that their intersection is our ordering $\leq$.
Suppose $(x_1,y_2)\leq (x_2,y_2)$. This means $x_1\leq x_2$ and $y_1\leq y_2$. Since $x_1\leq x_2$, we have $x_1 < x_2$ or $x_1 = x_2$. In the latter case, we also have $y_1\leq y_2$. So in either case, we have $(x_1,y_1)\leq_{\mathrm{lex}} (x_2,y_2)$. The symmetric argument shows that $(x_1,y_1)\leq_{\mathrm{rlex}} (x_2,y_2)$. So ${\leq} \subseteq (\leq_{\mathrm{lex}}\cap \leq_{\mathrm{rlex}})$.
Conversely, suppose $(x_1,y_1)\leq_{\mathrm{lex}} (x_2,y_2)$ and $(x_1,y_1)\leq_{\mathrm{rlex}} (x_2,y_2)$. By the definition of $\leq_{\mathrm{lex}}$, $x_1 < x_2$ or $x_1 = x_2$, so $x_1\leq x_2$. Similarly, by definition of $\leq_{\mathrm{rlex}}$, $y_1\leq y_2$. So $(\leq_{\mathrm{lex}}\cap \leq_{\mathrm{rlex}})\subseteq {\leq}$.
Comment: @HarukiY You're welcome. If the question is resolved, you should mark it as resolved by accepting one of the answers you've been given (click the green check mark).
Comment: Hello Alex, that makes a lot of sense. Thanks so much!


Deployment for staging and production

Question: I need to make the deployment easy between my staging and production servers.
How can I do this? I need to deploy all the changes, so if I pull from Github and run the script, the changes are applied!
Has anyone written any script or module for this?
I am using Drupal 7.
Answer: You should look into drush, drush deploy and especially features.  Not all Drupal configuration options are supported by features, and you will need to do some work to create a deployment process that works for you.  There is no single script that will do everything correctly for you.
Comment: Thanks.  n.b. drush_make is included in Drush core version 7.x-5.x; if you are still using Drush 4, it would be a good idea to upgrade.  Also, you can generate a Drush Makefile from an existing Drupal site via drush generate-make. There is a work-in-progress command to build an install profile from an existing Drupal site at http://drupal.org/node/1368242.
Comment: Wish I could upvote this twice. :-) I'll add that with drush you can create a makefile for your site. http://drupal.org/project/drush_make
Answer: There is Beanstalk

Advanced Deployment Tools Deploy your repositories to (S)FTP, SSH and
  Amazon S3 in one click.

And there is GitHub's post-receive hooks.
GitHub will POST to a supplied URL when someone pushes to the repo. Just write a short PHP script to run on your linode VPS and pull from GitHub when it receives said POST.
Answer: You may be interested in Fabric

Fabric is a Python library and command-line tool for streamlining the
  use of SSH for application deployment or systems administration tasks.
It provides a basic suite of operations for executing local or remote
  shell commands (normally or via sudo) and uploading/downloading files,
  as well as auxiliary functionality such as prompting the running user
  for input, or aborting execution.

You may also be interested in drush for command line access to Drupal.
e.g, some relevant drush commands:
<code>archive-dump    Backup your code, files, and database into a single file.
archive-restore Expand a site archive into a Drupal web site.
core-rsync (rsync)    Rsync the Drupal tree to/from another server using ssh.
</code>
or both :)
Comment: can i do with a script, to perform all the changes
Comment: Yes, you could script the entire thing so it's automatic.
Answer: Although the question is a year before I would suggest using these 3 tools.
Git + Capistrano + Drush.
It just works for such kind of tasks.
Here are some Capistrano gems/files related to Drupal to help you automate Drupal development:

http://rubygems.org/gems/capistrano-drupal
http://rubygems.org/gems/capdrupal
https://github.com/chadfennell/dapistrano

And here are some useful resources so you don't have to search all over the web:

Jochen Verdeyen - DEPLOYING DRUPAL WITH CAPISTRANO (video)
Simple and powerful site deployment with capistrano - Kim Pepper (video)
DrupalCon Munich 2012: Deploy with Capistrano (video)
Deploying Drupal With Git and Capistrano (blog)
Answer: These are my finding. Drush provides the sync, using mysql dump and restore as complete, not the changes made after some interval.
Many things can be tracked with
 - Configuration Module
 - Features
 - Extra Features
Please see the presentation for further.
https://docs.google.com/file/d/0B6Sp-HBmxgGMMnhhQXVrR1hDUVU/edit?usp=sharing
Comment: Hello, and welcome to Drupal Answers. May you expend your answer with a summary of what reported in the linked page. On Stack Exchange, answers merely containing a link are not considered answers.

Deployment for staging and production


How to get the correlation between two large (sparse) matrices?

Question: I have two large (sparse) matrices (500000*500000) and would like to perform the mantel test to get a similarity measure.

Is there a way to break-up these matrices into smaller ones and perform the test?
Or can you suggest a way to do it efficiently without running into memory problems?
Comment: If you just want to estimate a "similarity measure," you don't need the Mantel test: just compute (say) the Pearson correlation between the two matrices.
Answer: You can simply take random samples (i.e. submatrices) and estimate the Mantel test statistic.  With enough samples, this should converge on the same conclusion.  In this way, you can avoid having to cook up a method for accessing all of the data.
However, as these are sparse matrices, it's better to go after a method for accessing the data via coordinate object lists (COO representation), i.e. (row, column, value), and implement a simple calculation for tabulating the test statistic across the two matrices.  You can merge the two matrices' COO versions or perform more complex tabulations using the data.table package.
Ultimately, it depends on how many values exist in your matrices (i.e. how dense they are).  Attacking them in sparse matrix formats may be best if they're very sparse.  Using a subsampling method may be better if they're not super sparse.
Comment: Great! I now have the mantel statistic for various pairs of submatrices. To approximate the final correlation, do I compute the mean of these mantel statistics? Also, how do I know the final P-value for this statistic? [please excuse my ignorance]
Comment: Well, this is where the question veers more toward the statistics.SE site...  bootstrap estimates of test statistics are a stats topic, rather than a programming topic, so that audience is more apropos.


struct as parameter causing "mismatch in formal parameter list"

Question: Hi I'm having a problem using a struct as a parameter.
My struct looks the following:
typedef struct temps {
    string name;
    float max;
} temps;

I can use it in my main without problems like:
temps t;
t.max = 1.0;

but using it in a function signatures like this:
void printTemps(const temps& t) {
    cout << t.name << endl << "MAX: " << t.max << endl;
}

It gives me the following compiler message:

error C2563: mismatch in formal parameter list

Here is a mwe:
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <Lmcons.h>

using namespace std;

typedef struct temps {
    string name;
    float max;
} temps;

void printTemps(const temps& t) {
    cout << t.name << endl << "MAX: " << t.max << endl;
}

int main(int argc, char **argv)
{
    temps t;
    t.max = 1.0;
    printTemps(t);
}

Any ideas whats wrong on the struct?
Comment: @user2798895 does MCVE you posted compile without windows.h and Lmcons.h?
Comment: Don't use typedef struct in C++. Show the compiler error message.
Comment: Which compiler and version? It works for me on MSVC 2017.
Comment: Is there a max() macro still in the windows headers? I am thinking of this: https://stackoverflow.com/questions/11544073/how-do-i-deal-with-the-max-macro-in-windows-h-colliding-with-max-in-std
Comment: Which headers and using statements did you use? Please post a full [mcve].
Comment: I put `#include` and `using namespace std;` at the top and it compiled fine on g++ 6.3.0
Comment: just added the includes. sry for that
Comment: Included string and fstream, works fine on Ubuntu 17.04, no warnings or errors even with -Wall. Can't test with windows headers.
Comment: @rex same for me but getting the error
Comment: I created a fresh project and it compiled without warnings.
Comment: @drescherjm using the name of a function-like macro without `(` following it, does not invoke the macro
Answer: You're using the C typedef struct declaration.
typedef struct temps {
    string name;
    float max;
} temps;

//void printTemps(const temps& t) {
void printTemps(const struct temps& t) {  // should match the C idiom
    cout << t.name << endl << "MAX: " << t.max << endl;
}

But since you are programming in C++, you should use the C++ way of declaring structs.
struct temps {
    string name;
    float max;
};

void printTemps(const temps& t) {
    cout << t.name << '\n' << "MAX: " << t.max << '\n';  // using \n is more efficient
}                                                        // since std::endl
                                                         // flushes the stream

Comment: It's true that OP should avoid the typedef, however the typedef makes no change to the program (and therefore this change wouldn't fix the problem, unless the compiler is bugged or OP has not posted the real code, which is probably the case).


Find convergence of an integral which is not decreasing.

Question: Let $I=\int_0^{\pi/2} \log(\sin x)dx$. Then

I diverges at $x=0$.
I converges and is equal to $-\pi\log 2$.
I converges and is equal to $-\pi/2 \log 2$.
I diverges at $x=\pi/4$.

I found that value of integral is zero.
and also that $\log(\sin x)$ is not a decreasing function, so we can not use integral test here. I am not able to think of applying any other series convergence test here.
Please, help me out.
Comment: http://math.stackexchange.com/questions/815571/integral-int-pi-2-0-ln-sin-x-dx?noredirect=1&lq=1
Answer: The answer is the third one.
We have that
$$I=\int_0^{\pi/2} \log(\sin x)dx=\int_0^{\pi/2} \log(\sin(\pi/2-x)dx=\int_0^{\pi/2} \log(\cos x)dx.$$
Moreover
$$\int_0^{\pi} \log(\sin x)dx=I+\int_{\pi/2}^{\pi} \log(\sin x)dx
\\=
I+\int_0^{\pi/2} \log(\sin (\pi-x))dx\\=
I+\int_0^{\pi/2} \log(\sin x)dx=2I.$$
Hence
$$2I=\int_0^{\pi/2} \log(\sin x)dx+\int_0^{\pi/2} \log(\cos x)dx=
\int_0^{\pi/2} \log(\sin x\cos x)dx\\=\int_0^{\pi/2} \log\left(\frac{\sin 2x}{2}\right)dx=\int_0^{\pi/2} \log(\sin 2x)dx-\int_0^{\pi/2} \log(2)dx\\
=\frac{1}{2}\int_0^{\pi} \log(\sin t)dt-\frac{\pi}{2}\log(2)
=\frac{2I}{2}-\frac{\pi}{2}\log(2)$$
which implies that $I=-\frac{\pi}{2}\log(2)$.


Razor em arquivo javascript

Question: Tenho um pequeno código que funciona em _Layout:
$.ajax({
    type: "POST",
    url: "@Url.Action("Action", "Controller")",
    success: function () {
          //Seu código aqui ...
    }
});

Até agora funciona tudo bem, só que _Layout está ficando muito grande. então que quero adicionar um arquivo javascript e adicionar ela em _Layout.
Só que o problema é arquivo do javascript. Ele não reconhece '@'.
Como posso resolver isso?
Answer: Não resolve. JavaScript é uma coisa, Razor é outra.
O @ faz parte da sintaxe do Razor e quer dizer que isso será processado do lado do servidor antes de a resposta ser enviada ao cliente. Os arquivos JavaScript são enviados ao cliente da mesma forma que são escritos, portanto não são pré-processados por um mecanismo como o Razor.
Existem algumas alternativas:

Criar uma view com a seção de scripts e carregá-la no arquivo _Layout, usando RenderPage.
Algo como:
@RenderPage("~/Views/Shared/_Scripts.cshtml")

Usar uma biblioteca como o RazorJS para pré-processar os arquivos JavaScript.
Comment: Não tem como saber, nunca usei. Mas bem provável que ela atenda aos casos mais básicos, como este da sua publicação.
Comment: A biblioteca **RazorJS** é confiável ? Porque já faz 6 anos sem atualização.
Answer: Crie um arquivo .js e coloque seu código:
$.ajax({
    type: "POST",
    url: "Action",
    success: function () {
          //Seu código aqui ...
    }
});

E ai na sua View Layout, você instancia:
@section scripts{

}

Não acredito que dê para utilizar Helpers do Razor em arquivos .js.

Razor em arquivo javascript


Do runners on base get a run if the batter hits a home run?

Question: Do the runners on the base get a free run when the batter hits a home run?
I have seen a game where there was a runner on first and the batter hit a home run, but instead of getting one home run, they got two even though it would have been impossible to run all the bases without getting out.
Comment: Americans (and others): go easy on the downvotes. Not everybody grew up with baseball.
Comment: @PhilipKendall - Excellent point. In fact, Americans (and others) should upvote this specifically to encourage people who want to know about baseball to ask about it :)
Comment: I expect the same treatment for anyone (nationality aside) that asks a question about a sport they are not familiar with...to which I have [included](http://meta.sports.stackexchange.com/a/669) on our meta post for new users.
Comment: @PhilipKendall: There are even (adult, middle-aged) Americans who don't know this stuff ... as I am every time my wife comes to a game with me.
Answer: I think you're confusing "run" and "home run". In high-level terms:

A run is scored when a player starts off as a batter then makes it all the way back round to home plate without being put out, no matter if he stops at any bases along the way.
A home run happens when a batter hits the ball over the fences (or equivalent). When this happens, any players currently on first, second or third bases also get to finish their circle of the bases and score a run (but not a home run).

As such in your situation, two runs are scored: one for the player who was already on first, and one for the batter who hit the home run. However, only the batter is credited with a home run. It's possibly also worth noting here that for the purposes of winning the game, runs are the only thing that matters. It doesn't matter if they were home runs or not - they all count as runs; it's perfectly possible to win a game without scoring a single home run, but you obviously have to score at least one run.
Comment: @Dr.DrfbagIII along the same lines, "home run" can mean "when the batter scores a run on one play" http://sports.stackexchange.com/a/14340
Comment: @chepner That's fair. That's why I say "can mean" rather than "does mean" or "always means." I updated the [answer I reference](http://sports.stackexchange.com/a/14340) to reflect this.
Comment: I've never given it a second thought because I grew up with baseball, but I now realize that "home run" is a pretty nebulous term.  By definition, all runs are a result of reaching home base, but a "home run" is a specific case.  If just learning the game, I'd suggest trying to replace all instances of "home run" with another term: a dinger, four-bagger, round-tripper or one of the many, many synonyms.
Comment: @Dr.DrfbagIII while that may be a nice idea, if you're watching any media coverage, they're going to use "home run" so people are going to have to understand the term.
Comment: @ᴍᴀsᴛᴇʀᴍɪɴᴅ_ᴇᴅ That's not necessarily true. No home run is credited if there are errors on the play, and I can think of an extremely contrived example where it isn't clear if a home run would be credited. (Similar to how a batter who reaches second on a throw home, I wonder if a batter could be credited with a triple if a very slow lead runner eludes a tag at home and the batter slides in behind him.)


Remove Lync 2010 Standard

Question: I am trying to remove my single server Lync standard install via the Topology Builder.
By going in to my site -> Standard Edition Front End Servers -> Delete, i get the error A published pool hosting Central Management Service can not be removed
I cant remove the server from the topology so cant run the deployment wizard which will remove the role from the server.
As an edit from a post, I have now done the following:

Lync Control Panel -> Deleted all the Lync users from Lync  ->
commit all
Get-CsConferenceDirectory | Remove-CsConferenceDirectory
Get-CsExUmContact -Filter {RegistrarPool -eq "hqslc1.domain.local"}
| Remove-CsExUmContact
Get-CsRgsWorkflow -Identity:Service:ApplicationServer:hqslc1.domain.local | Remove-CsRgsWorkflow
Get-CsDialInConferencingAccessNumber | where {$_.Pool -eq "hqslc1.domain.local"} |
Remove-CsDialInConferencingAccessNumber
Get-CsCommonAreaPhone -Filter {RegistrarPool -eq "hqslc1.domain.local"} | Remove-CsCommonAreaPhone
Get-CsCallParkOrbit followed by Remove-CsCallParkOrbit -Identity "Home Park Orbit"
Lync Control panel -> Voice Features -> Unassigned Number, delete, commit all
Lync Control Panel -> Voice Routing > Route -> Edit -> Select all -> Delete -> Commit all

Despite the above, I still cannot remove the server or when running the Remove Deployment wizard no changes are made.
Comment: This guy ran into the same thing and has detailed instructions per MS support...find the same error screenshot and follow along: http://terenceluk.blogspot.com/2011/01/step-by-step-instructions-for.html
Answer: You need to delete the pool created before you can run the Topology Builder.
Which is Phase 3 & 4 of the Decommissioning a Deployment guide for Lync:

The following Technet article has all the steps to follow to decomm. your Lync installation, here.
Comment: many thanks, have gone through that and listed the commands thus far, still pulling my hair out :)
Comment: Your steps, along with the tip from @TheCleaner and link http://terenceluk.blogspot.com/2011/01/step-by-step-instructions-for.html sorted me out

Remove Lync 2010 Standard


Extjs Gauge Change ColorSet by value

Question: Is there anyway to change the extjs gauge chart's colorset by changing value?
<code>        var gauge = {
        xtype: 'chart',
        style: 'background:#fff',
        animate: true,
        store: GaugeStore,
        insetPadding: 25,
        axes: [{
            title: 'Performans (%)',
            type: 'gauge',
            position: 'gauge',
            minimum: 0,
            maximum: 100,
            steps: 10,
            margin: 4

        }],
        series: [{
            type: 'gauge',
            field: 'percentagesla',
            donut: 40,
            colorSet:['',''],
            renderer: function (sprite, record, attr, index, store)
            {
                var value = record.get("percentagesla"), color;
                if (value >= 95) { this.colorSet = ['#fff000','ddd']; }
                else if (value < 85) { this.colorSet = ['#ffcc00', 'ddd']; }
                else { this.colorSet = ['#ffaa00', 'ddd']; }
            }
        }]

    }
</code>
Renderer function does not work for setting colorset. How can i handle this problem?
Thanks.
Comment: i think you need to play with the attribute 'fill', see example via EXTJS kitchen sink:  http://dev.sencha.com/extjs/5.0.0/examples/charts-kitchensink/#basic-gauge
Comment: It changes the color of all gauge, but i want change just value part's color, other side color must be the same. ColorSet['#aaa','#ddd'], shortly I want to change #aaa part :)
Answer: use this
<code>renderer: function (sprite, record, attr, index, store) {
                if (attr.fill == this.colorSet[1]) return Ext.apply(attr, { fill: attr.fill });
                var value = record.get("SLA"),
                    color;
                if (value >= 95) {
                    color = "#0000ff";
                } else if (value < 85) {
                    color = "#00ff00";
                } else {
                    color = "#ff0000";
                }
                return Ext.apply(attr, { fill: color });
            }
</code>

Extjs Gauge Change ColorSet by value


IF MAIS SIMPLES NO REACT JS PARA EVITAR REPETIÇÃO DE CÓDIGO

Question: Eu estou iniciando minha caminhada no react e estou fazendo um clone do youtube. Eu cheguei numa parte onde não sei se o que eu fiz é uma  boa ou má prática que gostaria de ajuda de vocês. Seguinte.
Eu tenho um componente que ao ser chamado PODE ou NÃO ser um botão.
Então quando ele é chamado eu o chamo assim:
<SideMenuOptions isButton={true} itemIcon={<HomeIcon/>} itemText={'Ínicio'} />

Se o boleano de botão for "TRUE" significa que ele é um botão, se não, é apenas um campo de texto.
Agora abrindo o código do componente SideMenuOptions nós encontramos:
function isButton(isButton, itemIcon, itemText) {
if (isButton) {
    return (
        <ListItem button>
            <ListItemIcon>{itemIcon}</ListItemIcon>
            <ListItemText>{itemText}</ListItemText>
        </ListItem>
    )
}
return (
    <ListItem>
        <ListItemIcon>{itemIcon}</ListItemIcon>
        <ListItemText>{itemText}</ListItemText>
    </ListItem>
)}

export default function SideMenuOptions(props) {
return (
    <>
        {isButton(props.isButton, props.itemIcon, props.itemText)}
    </>
)}

Ou seja, o componente SideMenuOptions returna uma função, que ao executada ela verifica se a propriedade isButton é verdadeira ou não.
Para um item ser um botão, basta eu informar no  a propriedade Button, mas ela necessariamente precisa ter aqueles childrens.
Eu achei que esse ctrl + c ctrl + v muita repetição de código. Teria uma solução mais elaborada para o problema? Quero muito a ajuda dos senhores nisso!
Answer: No JSX, escrever um atributo omitindo o seu valor, é equivalente a dar a ele o valor true. Ou seja, <ListItem button /> é equivalente a <ListItem button={true} />.
Assim, tudo que é necessário no seu código é fazer
export default function SideMenuOptions({ isButton, itemIcon, itemText }) {
    return (
        <ListItem button={isButton}>
            <ListItemIcon>{itemIcon}</ListItemIcon>
            <ListItemText>{itemText}</ListItemText>
        </ListItem>
    );
}


Convergence of sequence method, Math behind intuition

Question: Now I want to find convergence of a sequence:
$$ \lim_{n \to \infty} \sqrt[n]{4^n + 5^n}$$
Now I am pretty sure I have solved this using logic on inspection:
$4^n \ll 5^n$ as $n\rightarrow\infty$, hence $\sqrt[n]{4^n + 5^n}=\sqrt[n]{ 5^n} = 5$
Now I could go from here with an epsilon delta proof(maybe), but I can't see how I can Mathematically find this value without intuition(that may be wrong).
Any advice would be greatly appreciated!
Note: The title can be edited freely(with relevance of course), I wasn't sure what to label it.
Comment: $5^n< 4^n+5^n<2\cdot 5^n$. Use the Squeeze Theorem.
Comment: @DavidMitra Convergence of a sequence is guaranteed by being monotone and bounded, is that what you are utilising here? Showing bounding?

Also, does this show that it converges to 5 specifically? I can't see it.
Comment: Use ([or first prove](http://math.stackexchange.com/questions/125588/limit-of-21-n-as-n-to-infty-is-1)) the fact that $\lim_{n\rightarrow\infty}\root n\of 2=1$.
Comment: @DavidMitra I understand now, this is an extremely efficient answer!! Thank you!
Answer: In the same spirit as Fermat, rewrite $$4^n+5^n=5^n \Big(1+(\frac{4}{5})^n\Big)$$ So $$ {\sqrt[n]{4^n + 5^n}}= {\sqrt[n]{5^n(1 + (\frac{4}{5})^n})}=5 \sqrt[n]{1 + (\frac{4}{5})^n}$$ Now, consider the Taylor series of $\sqrt[n]{1+x}$ when $x$ is small; it is given by $$\sqrt[n]{1+x}=1+\frac{x}{n}+O\left(x^2\right)$$ Replace now $x$ by $\Big(\frac{4}{5}\Big)^n$ and you finally end with $${\sqrt[n]{4^n + 5^n}} \simeq 5+\frac{5}{n} \Big(\frac{4}{5}\Big)^n$$
Let us try for a few values of $n$. For $n=10$ the exact value is $5.051256749$ while the approximation is $5.053687091$. For $n=20$ the exact value is $5.002866636$ while the approximation is $5.002882304$.
Answer: $$\lim \limits_{n \to \infty} {\sqrt[n]{4^n + 5^n}}=\lim \limits_{n \to \infty} {\sqrt[n]{5^n(1 + (\frac{4}{5})^n})}=5$$
Since $(\frac{4}{5})^{n}$ goes to zero as $n$ tends to infinity. But David Mitra's answer in his comment is more nice!
Comment: I prefer this answer over David's, but only on the basis that I don't see how his proves that it converges to five specifically. Could you perhaps elaborate on his answer?

I didn't think about $(\frac45)^n$ so that was a happy reminder. Thank you!
Comment: @DisplayName use the definition of $e$
Comment: @Display Name First use $\sqrt{ab}=\sqrt{a}\sqrt{b}$ and then the fact that $\lim_{n\to \infty}\sqrt[n]{2}=1$
Answer: Another way: log the expression to get
$$
\frac{\log (5^n + 4^n)}{n} = \frac{\log 5^n + \log (1+(\frac{4}{5})^n)}{n} \sim \log 5 + \frac{(\frac{4}{5})^n}{n} \to_n \log 5
$$
Now exponentiate and get $5$.


`Routing` folder not present inside `Drupal\Core\`

Question: I am trying to port a module from D7 to D8.
Since hook_help() uses routes instead of paths in D8, so the line use Drupal\Core\Routing\RouteMatchInterface; is added at the beginning of the code as mentioned on this page.
But the thing is that no folder named routing exists inside my Drupal\Core\.
Questions.

Am I supposed to add that folder myself?
How will I configure
    RouteMatchInterface file.
Comment: There is no configuration in or for `RouteMatchInterface`. It is an interface. What are you trying to do?
Answer: That is the namespace. It's actual location in the file system is /core/lib/Drupal/Core/Routing. The autoloader knows where to look via the namespace.
Answer: No, you aren't supposed to add any directories: Drupal already comes with the core/lib/Drupal/Core/Routing/RouteMatchInterface.php file containing the PHP interface you are trying to use.
There isn't anything you need to config: Just use the object passed as second parameter to hook_help(). Drupal core's implementations of hook_help() don't usually use that parameter, but system_help() does use it.
case 'system.theme_settings_theme':
  $theme_list = \Drupal::service('theme_handler')->listInfo();
  $theme = $theme_list[$route_match->getParameter('theme')];
  return '
' . t('These options control the display settings for the %name theme. When your site is displayed using this theme, these settings will be used.', array('%name' => $theme->info['name'])) . '
';

$route_match is just an object that allows you to understand exactly for which page the help text is being generated. In the code I shown, it allows to understand exactly for which theme the settings page is shown. system.theme_settings_theme (the value for the first parameter) just tells you the page is the theme settings page (served on /admin/appearance/settings/{theme}), but the exact page could be /admin/appearance/settings/bartik, /admin/appearance/settings/stark, or /admin/appearance/settings/seven (just using some of the themes Drupal core comes with as examples).
Using RouteMatchInterface::getParameter(), or RouteMatchInterface::getRawParameter(), is what you normally do with the second parameter passed to hook_help(). The route name is already passed as first parameter, so RouteMatchInterface::getRouteName() is not providing anything that you don't already have. Eventually, you could get the Route object associated with the page, but I cannot think of any case where that is necessary.


How to tune a Roman water-organ (hydraulis)?

Question: I am trying to reconstruct the tuning of the Roman water-organ (hydraulis) of Aquincum. The original instrument had 13 pipes for each of the 4 registers (three stopped pipe registers and one open pipe register), and it was possible to play one, two, three, or all four pipes corresponding to each key at the same time.
The best description I found of what could be the tuning comes from the booklet of "Apollo & Dionysus" cd (https://www.chandos.net/chanimages/Booklets/DC4188.pdf), which is based on an actual hydraulis reconstruction by Justus Willberg:

The organ is tuned to an ancient tonal system, drawing upon a range of
sources, including Bellermann and Koine Hormasia (Codex Palatinus 281,
et al.). The registers are assigned individual modes (Hyperlydian,
Hyperiastian, Lydian and Phrygian), allowing a specific set of notes
to be played in each register: proslambanómenos, hypáte hypaton,
parypáte hypaton, diápemptos, hypáte, parypáte, khromatiké, diátonos,
mése, parámesos, tríte, paranéte, néte. In today's notation this
corresponds approximately to the pitch series D E F G A B♭ B C' D' E'
F' G' A'. The organ can also be played with all the registers switched
on, which results in a characteristic timbre in which the open
Hyperlydian register dominates.

What I understand with my limited musical knowledge is:

the register of the open pipes (which should be the highest pitched one) was Hyperlydian;
the three registers of the stopped pipes were Hyperiastian, Lydian and Phrygian;
one of the registers (the highest one?) was tuned according to the scale (that I do not recognize) D E F G A B♭ B C' D' E' F' G' A'.

My question is: how was this organ tuned? What were the pitches for each register? It seems they could be played at the same time, but would they sound nice together?

Edit:
As suggested by user Owain Evans, this is the instrument:

However, it can't be the setup presented in Hagel's book since (1) Hagels himself doubts the correctness of Walker-Mayer reconstruction and (2) none of the registers in Hagel's picture (borrowed from Walker-Mayer, actually) has the range proposed by Willberg

from HAGEL, S. (2018). Ancient Greek music: a new technical history. Cambridge, Cambridge University Press, p365.
Comment: Warning :-) -- in the absence of some physical evidence (dug up an ancient set of pipes) or specified pipe lengths & diameters in units we trust, the best you can do is tune the correct **intervals**, not the exact **pitches** .  As you no doubt know,  in just the last few centuries,  middle "A" has moved by at least 10%
Comment: NB: "Iastian" is another name for "Ionian", so hyperiastian is just hyperionian. I think the alleged "modern scale" mentioned from D to A' including a Bb should be temporarily ignored in favor of researching the ancient pitches corresponding to the modes named for each register. It does seem like the modes mentioned in facts 1 and 2 are listed in order from highest register to lowest, but of course there is much overlap (that part of the diagram at the bottom of the question seems somewhat accurate).
Comment: It's in German, but here's a site about a reconstruction done in the 1990s: http://www.hydraulis.de/0496e29a0c08d0302/index.html Also I learned today that pairs of aulos were often stopped (with wax or metal slides) to two different (but related) diatonic modes for a single performance. That caused the burden of the performer having to be careful about certain note combinations, but also allowed flexibility in key and harmony. It could be similar with the hydraulis.
Comment: Maybe The Roman organ of Aquincum https://archive.org/embed/romanorganofaqui0000walc (need to register on archive.org). Has 119 pages, quite alot of images, tuning from a brief glance.
Comment: Thanks, I did not know it was accessible. However, recent scholarship ([_Ancient_ _Greek_ _Music_](https://www.amazon.it/Ancient-Greek-Music-Technical-History/dp/1316610896) by Hagel) seems to reject the musical reconstruction by Walcker-Mayer as wrong
Comment: As far as I can tell, Lydian goes from a modern F to a modern F with a "keynote" of F, while hyperlydian goes from a modern Bb to a modern Bb with a keynote of F also. Which suggest that the modern equivalent of the highest note of the highest set of pipes would be a Bb, not an A. I don't quite understand why an A would be listed as the highest note of a hyperlydian tuning.
Comment: @ToddWilcox, the website you linked is owned by Justus Willberg, and reports (in German) precisely what I quoted in English above: "Dabei sind den Registern einzelne Tonarten zugeordnet (hyperlydisch, hyperiastisch, lydisch und phrygisch). In jedem Register sind folgende Töne spielbar: proslambanómenos, hypáte hypaton, parypáte hypaton, diápemptos, hypáte, parypáte, khromatiké, diátonos, mése, parámesos, tríte, synemméne, néte. Das entspricht in heutigen Noten etwa der Tonreihe d e f g a b h c' d' e' f' g' a'."
Comment: I think your point 3 is incorrect in interpreting then quoted text. My reading is that the notes listed are the entire compass of the instrument and the highest register doesn't start on the D.
Comment: If you look here: https://en.wikipedia.org/wiki/Musical_system_of_ancient_Greece you'll see ancient Phrygian started on a note that is called "D" in many modern texts. That suggests to me that the lowest register of the organ was the Phrygian register and went from the D mentioned in the quote up to probably D'. Next higher would be the Lydian register from F to F', then the hyperionian from G to G', and finally hyperlydian, which is where my theory breaks down. Wouldn't it run from C to C'? What about the Bbs, are they for the Lydian and hyperlydian registers?
Comment: @ToddWilcox "The Roman organ of Aquincum", p. 78, gives that d-a' sequence for the Lydian register (actually, a Lydian/Ipolydian register)
Comment: @ToddWilcox But do you then consider the different tuning of today's music? Singing Bach with a period tuning as compared to a modern tuning are two quite different experiences, the latter being much more strained. Archaeological evidence should provide clues as to what the tuning of the instrument was, and to my knowledge, there is archaeological evidence giving us clues as to the tuning. Have you read https://www.mclerranjournal.com/technology-1/2018/4/14/hydraulis-the-ancient-roman-pipe-organ? Here they touch upon the reconstruction of the hydraulis found at Mt. Olympus.
Answer: In my humble opinion, there is no answer to this question. The tubes recovered in Dion, Greece, or elsewhere, do not provide full information about the tuning system. Reproducing any music score from manuscripts requires a lot of assumptions.
In my humble opinion, the sound of the instrument, its colour, its timbre, are more important than the scales.
I would have tried the well tempered chromatic scale.
Comment: This is okay up until the last sentence. The well-tempered chromatic scale did not exist in ancient Greece.
Comment: Of course! I only wanted to say that I would appreciate the sound of the instrument better over a scale that my ear and mind are well trained.


surface for openCV with Android: already connected

Question: I'm trying to connect my Android app with the OpenCV library and I need to use a native camera for have more control of the camera options. For do it I have found http://nezarobot.blogspot.it/2016/03/android-surfacetexture-camera2-opencv.html, that is what I need.
My problem is that if I use this code, with some small change and when I launch it, my app crash with 3 errors reported:

E/BufferQueueProducer: [SurfaceTexture-0-31525-0] connect(P): already connected (cur=4 req=2)
D/PlateNumberDetection/DetectionBasedTracker: ANativeWindow_lock failed with error code -22
A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x315e9858 in tid 31735 (CameraBackgroun)

I have tried to close the camera before the jni call and I can capture and show only the first frame, but then I need to restart the camera and I can't create the same thread by itself.
Here I take the frame and I send to NDK.
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
        = new ImageReader.OnImageAvailableListener() {

    @Override
    public void onImageAvailable(ImageReader reader) {

        Image image;

        try {
            image = reader.acquireLatestImage();
            if( image == null) {
                return;
            }

            if (image.getFormat() != ImageFormat.YUV_420_888) {
                throw new IllegalArgumentException("image must have format YUV_420_888.");
            }

            Image.Plane[] planes = image.getPlanes();

            if (planes[1].getPixelStride() != 1 && planes[1].getPixelStride() != 2) {
                throw new IllegalArgumentException(
                        "src chroma plane must have a pixel stride of 1 or 2: got "
                                + planes[1].getPixelStride());
            }

            mNativeDetector.detect(image.getWidth(), image.getHeight(), planes[0].getBuffer(), surface);

        } catch (IllegalStateException e) {
            Log.e(TAG, "Too many images queued for saving, dropping image for request: ", e);
            return;
        }
        image.close();
    }
};

and here I manage the camera preview
protected void createCameraPreview() {
    try {
        SurfaceTexture texture = textureView.getSurfaceTexture();
        assert texture != null;
        texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
        surface = new Surface(texture);
        captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        captureRequestBuilder.addTarget(mImageReader.get().getSurface());

        BlockingSessionCallback sessionCallback = new BlockingSessionCallback();

        List<Surface> outputSurfaces = new ArrayList<>();
        outputSurfaces.add(mImageReader.get().getSurface());
        outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));

        cameraDevice.createCaptureSession(outputSurfaces, sessionCallback, mBackgroundHandler);

        try {
            Log.d(TAG, "waiting on session.");
            cameraCaptureSessions = sessionCallback.waitAndGetSession(SESSION_WAIT_TIMEOUT_MS);
            try {
                captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);

                Log.d(TAG, "setting repeating request");

                cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),
                        mCaptureCallback, mBackgrounHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        } catch (TimeoutRuntimeException e) {
            Toast.makeText(AydaMainActivity.this, "Failed to configure capture session.", Toast.LENGTH_SHORT);
        }

    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

Answer: Have you tried that code without your "some small change" first? I have tried that project and it worked well on multiple devices. So it will be useful to first establish if it does not work on your phone at all, or if there is a problem in your modifications.
Comment: Thank you for your answer, I didn't check if the problem was in my modifications, but I found my problem, it was on outputSurfaces, because I have to pass only mImageReader.get().getSurface() in createCaptureSession


About Azure SQL Managed Instance specifications

Question: I'm trying to incorporate the use of Azure SQL Managed Instance in my organization, being one the reason the data virtualization capability that Azure SQL doesn't have.
I was trying the pricing calculator and got confused about two items in its configuration

What is the difference between Backup Storage Layer and Disaster Recovery? Both of them are related to backup, but I'm little confused, specially when it comes to a propper production environment.
Thanks and regards
Comment: Product support/pricing questions are off-topic here. I suggest starting with the docs (or posting to an Azure-specific support forum). Aside from that: this is not a programming question.
Answer: Based on the Azure SQL Managed Instance pricing page, the Backup Storage Tier is the type of storage used for storing automated backups of your databases. You can choose between locally redundant storage (LRS), zone-redundant storage (ZRS), geo-redundant storage (GRS), or read-access geo-redundant storage (RA-GRS). The default option is GRS, which means your backups are replicated to a paired region for disaster recovery purposes. The cost of backup storage depends on the amount of data stored and the type of storage chosen. To help you choose the right backup storage type and reduce costs please read this support article.
The Disaster recovery option is the ability to restore a database from a geo-replicated backup to a different region in case of a regional outage or disaster. This option is only available if you use GRS or RA-GRS for your backup storage tier. The cost of disaster recovery is based on the compute and storage resources used for the restored database in the target region. Here (a Nov 2022 support article) you will find that licensing of geo-redundant Disaster Recovery for SQL Managed Instance (in preview) is free.
In summary, the backup storage tier determines where and how your backups are stored, while the disaster recovery option determines whether and how you can restore your backups to a different region. They are indeed related but they are not the same. In addition, here you will find how to monitor Azure SQL Manage Instance costs.
Comment: Brilliant explanation my friend. ¿What could it be the reason of a intance without the disaster recovery applied being more expensive than one that has it?

Playing around with the calculator, if you chose to have a disaster recovery on your instance, your overall price is lower ... ¿Why?

Perphaps I'm missing something to decide whether to use disaster recovery ..
Comment: Remember with Disaster Recover (because is in preview, you get a discount on licensing (is free).


Integral involving cube root and seventh root

Question: Find the value of $$\int_{0}^{1} (1-x^7)^{\frac{1}{3}}-(1-x^3)^{\frac{1}{7}}\:dx$$
My Approach:
Let $$I_1=\int_{0}^{1} (1-x^7)^{\frac{1}{3}}dx$$ and
$$I_2=\int_{0}^{1} (1-x^3)^{\frac{1}{7}}dx$$
For $I_1$ substitute $x^7=1-t^3$ so $dx=\frac{-3t^2}{7}(1-t^3)^{\frac{-6}{7}}\:dt$ Hence
$$I_1=\int_{1}^{0}\frac{-3t^3}{7}(1-t^3)^{\frac{-6}{7}}\:dt$$ $\implies$
$$I_1=\frac{-3}{7}\int_{0}^{1}(1-t^3-1)(1-t^3)^{\frac{-6}{7}}\:dt$$ $\implies$
$$I_1=\frac{-3I_2}{7}+\frac{3A}{7}$$
where $A=\int_{0}^{1}(1-t^3)^{\frac{-6}{7}}dt$
Similarly using substitution $x^3=1-t^7$ for $I_2$ and proceeding as above we get
$$I_2=\frac{-7I_1}{3}+\frac{7B}{3}$$ where $B=\int_{0}^{1}(1-t^7)^{\frac{-2}{3}}dt$
But we need to find $I_1-I_2$ so got stuck up here
Comment: Thanks all pretty happy to see wonderful methods
Comment: A [related](http://math.stackexchange.com/questions/1438397) question.
Answer: Consider the area in the first quadrant bounded by the curve $x^7+y^3 = 1$.

The curve in the first quadrant can be written as $y = (1-x^7)^{1/3}$ for $0 \le x \le 1$. Hence, the area bounded by the curve is given by $\displaystyle\int_{0}^{1}(1-x^7)^{1/3}\,dx$.
We can also write the curve in the first quadrant as $x = (1-y^3)^{1/7}$ for $0 \le y \le 1$. So, the area bounded by the curve is also $\displaystyle\int_{0}^{1}(1-y^3)^{1/7}\,dy$.
Therefore, $\displaystyle\int_{0}^{1}(1-x^7)^{1/3}\,dx = \int_{0}^{1}(1-y^3)^{1/7}\,dy$, and thus, the difference is $\displaystyle\int_{0}^{1}\left[(1-x^7)^{1/3} - (1-x^3)^{1/7}\right]\,dx = 0 $.
Answer: We can write it as $$I =  \displaystyle \int_{0}^{1}\sqrt[3]{1-x^7}dx-\int_{0}^{1}\sqrt[7]{1-x^3}dx$$
Now Using $$\displaystyle \bullet \int_{a}^{b}f(x)dx = -\int_{b}^{a}f(x)dx$$
So  we get $$I =  \displaystyle \int_{0}^{1}\left(1-x^7\right)^{\frac{1}{3}}dx+\int_{1}^{0}\left(1-x^3\right)^{\frac{1}{7}}dx$$
Now Let $$\displaystyle f(x) = \left(1-x^{7}\right)^{\frac{1}{3}}\;,$$ Then $$f^{-1}(x) = (1-x^3)^{\frac{1}{7}}$$ and also $f(0) = 1$ and $f(1) =0$
So Integral $$\displaystyle I = \int_{0}^{1}f(x)dx+\int_{f(0)}^{f(1)}f^{-1}(x)dx$$
Now let $f^{-1}(x) = z\;,$ Then $x=f(z)$ So we get $dx = f'(z)dz$
So Integral $$\displaystyle I =\int_{0}^{1}f(x)dx+\int_{0}^{1}z\cdot f'(z)dz$$
Now Integration by parts for second Integral, We get
$$\displaystyle I  =\int_{0}^{1}f(x)dx+\left[z\cdot f(z)\right]_{0}^{1}-\int_{0}^{1}f(z)dz$$
So using $$\displaystyle \bullet\; \int_{a}^{b}f(z)dz = \int_{a}^{b}f(x)dx$$
So we get $$\displaystyle I =\int_{0}^{1}f(x)dx+f(1) -\int_{0}^{1}f(x)dx = f(1) =0$$
Comment: This is more or less what I posted, but approaches the problem of showing equality a little differently, using inverse functions... I like it!
Comment: Have you missed a minus in your second equation (the one with bullet)?
Comment: Thanks   Ruslan i have edited it.
Answer: Hint. A straightforward approach is to use the Euler beta function
$$
B(a,b) :=  \int _0^1 x^{a-1}(1-x)^{b-1}dx =\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)},\quad a>0, b>0.
$$ Then you get
$$
\int_{0}^{1} (1-x^7)^{\frac{1}{3}}dt-\int_{0}^{1} (1-x^3)^{\frac{1}{7}}dt=0.
$$
Answer: $$I_1=\int_{0}^{1} (1-x^7)^{\frac{1}{3}}dx$$
substitute $t = 1-x^7$, $\,\,dt = -7x^6dx$, and by extension $\,\,x = \sqrt[7]{1-t}$
$$=-\frac{1}{7}\int_{0}^{1} \frac{\sqrt[3]{t}}{(1-t)^\frac{6}{7}}dx$$
Now integrate by parts choosing the factors $u = \sqrt[3]{t}$ $\,\, u' = \frac{1}{3t^{2/3}}$$\,\,dv = \frac{1}{(1-t)^{6/7}}\,\,$ and $v = -7(1-t)^{1/7}$
$$ = -\frac{1}{7}(-\sqrt[3]{t}\sqrt[7]{1-t})\bigg|_0^1 -\frac{1}{7}\int_0^1 \frac{-7\sqrt[7]{1-t}}{3t^{2/3}}dt$$
$$ = -\frac{1}{7}\int_0^1 \frac{-7\sqrt[7]{1-t}}{3t^{2/3}}dt$$
Finally, subsitute $t = v^3$, $\,\, dt = 3v^2dv$
$$ = \int_0^1 \sqrt[7]{1-v^3}dv$$
$$ = I_2$$
So what we have is
$$\int_{0}^{1} (I_2 - I_2)$$
$$=\int_{0}^{1} 0$$
$$=0$$


Angular app 6 in ASP.NET Core: More than one module matches

Question: Angular v6.1.10 | ASP.NET Core v2.2.102
I am building an Angular app from an ASP.NET Core template.
I want to create a component (fish-form).
In ASP.NET Core 2.0, a simple
ng g component fish-form --module=app.module.shared.ts

Would solve the problem, but with this architecture, as it doesn't have that file, it doesn't work.

I have also tried to create the component using
ng g component fish-form

But I am getting the following error:

Error: More than one module matches. Use skip-import option to skip
  importing the component into the closest module.

Any help is appreciated.
Answer: This fixed the problem:
ng g component fish-form --module=app.module.ts

Answer: You have two options

ng g component fish-form --skipImport=true. This will remove the error, but not import the component.
A better solution though ng g component fish-form --module=app.module.ts


Show that,$\int_0^\pi \left|\frac{\sin nx}{x}\right|\mathrm{d}x \ge \frac{2}{\pi}\left(1+\frac12+\cdots+\frac{1}{n}\right)$

Question: Show that,$$\int_0^\pi \bigg|\dfrac{\sin nx}{x}\bigg|\mathrm{d}x \ge \dfrac{2}{\pi}\bigg(1+\dfrac12+\cdots+\dfrac{1}{n}\bigg)$$
I could not approach the problem at all. Please help.
Comment: The zeros of $\sin nx$, where it changes sign, are $\dfrac{k\pi}{n},\; k = 0,\,1,\,\dotsc,\,n$. Splitting the integral and looking at each part alone ought to help.
Comment: @DanielFischer Let me try...thank you for the hint...
Comment: @DanielFischer I got the representation as you said...but, would I need to evaluate each and every integral or I would need to get another function which looks similar to the above function but is less than or equal to the above expression to get the inequality?
Comment: See http://math.stackexchange.com/a/390841/4583
Comment: @AymanHourieh I would really appreciate it a lot if you could post a solution here without using the summation notion. I face very much difficulty to conceive the representation with summation.
Comment: @Hawk Did you try to expand the sums yourself? Converting from one notation to another is purely mechanical.
Answer: $$
\begin{align}
I &=\sum_{i=0}^{n-1} \int_{i\pi/n}^{(i+1)\pi/n} \frac{|\sin{nx}|}{|x|}\,dx \\
&=\sum_{i=0}^{n-1} \int_{0}^{\pi/n} \frac{|\sin{nx}|}{i\pi/n+ x}\,dx \\
&\gt \sum_{i=1}^{n} \int_{0}^{\pi/n} \frac{|\sin{nx}|}{i\pi/n}\,dx \\
&= \sum_{i=1}^{n} \frac{2/n}{i\pi/n} \\
&= \frac{2}{\pi}\sum_{i=1}^{n} \frac{1}{i}
\end{align}
$$


Does an asymptotic vanishing of Jensen gap imply that the variance tend to zero?

Question: Let $\Omega \subseteq \mathbb{R}^2$ be a nice open bounded, connected domain, having Lebesgue measure $m(\Omega)=1$.
Let $F:[0,\infty) \to [0,\infty)$ be a $C^2$ strictly convex function. Suppose that $F''$ is an everywhere positive strictly decreasing  function, and that $\lim_{x \to \infty} F''(x)=0$.
Let $Y_n:\Omega \to \mathbb [0,\infty)$ be continuous, with constant expectations $\int_{\Omega} Y_n=c>0$, and suppose that
$$\lim_{n \to \infty} \int_{\Omega} F(Y_n)-F(\int_{\Omega} Y_n)=0.$$
Is $\lim_{n \to \infty} \int_{\Omega} (Y_n-c)^2=0$?

If we replace $\Omega$ with an arbitrary probability space $X$, and only require $Y_n:X \to [0,\infty)$ to be measurable, then the answer can be negative, as the following example shows:
Set $F(x) = e^{-x}$. For $n \in \{1, 2, 3, ...\}$ define
$$ Y_n := \left\{\begin{array}{ll}
1 - \frac{1}{\sqrt{n}} & \mbox{ with prob $1-1/n$}\\
1+ \frac{n-1}{\sqrt{n}} & \mbox{ with prob $1/n$}
\end{array}\right.$$
Then

$E[Y_n]=1$ for all $n \in \{1, 2, 3, ...\}$.

$\lim_{n\rightarrow\infty} E[F(Y_n)] = F(1)$.

$\lim_{n\rightarrow\infty} E[(Y_n-1)^2]=1$.

(This example is taken from here.)
The question is whether by forcing $Y_n$ to be continuous, the answer changes.
Answer: This is the kind of problem where continuity alone is unlikely to help. If you have no quantitative control on the continuity (a modulus of continuity, for instance), the functions $Y_n$ can get pretty ugly. In particular, they can go very quickly from one value to another, so that its image distribution can be quite close to whatever you want. I'll give a counter-example on $[0,1]$; Just take a product by $[0,1]$ to get a counter-example in $\mathbb{R}^2$.
Take:
$$F(x) = e^{-x},$$
$$Y_n (x) = \left\{ \begin{align} 1-\frac{1}{\sqrt{n}} & \text{ if } 0 \leq  x \leq 1-\frac{2}{n}, \\
1-\frac{1}{\sqrt{n}}+\frac{2}{3}n\sqrt{n} \left(x-1+\frac{2}{n}\right) & \text{ if } 1-\frac{2}{n} \leq  x \leq 1-\frac{1}{n}, \\
1-\frac{1}{\sqrt{n}}+\frac{2}{3}\sqrt{n} & \text{ if } 1-\frac{1}{n} \leq x. \\\end{align}\right.$$
If I am not mistaken, $\mathbb{E} (Y_n) = 1$ for all $n$. By the dominated convergence theorem, $\lim_{n \to + \infty} \mathbb{E} (F(Y_n)) = F(1) = e^{-1}$. Finally,
$$\mathbb{E} ((Y_n-1)^2) \geq \int_{1-\frac{1}{n}}^1 (Y_n(x)-1)^2 \ dx = \frac{1}{n} \times \left(\frac{2}{3} \sqrt{n}-\frac{1}{\sqrt{n}}\right)^2 \sim \frac{4}{9}.$$
One may notice that the distribution of $Y_n$ is quite close (up to a factor $2/3$, here for convenience) to the counter example you already have; more generally, you can approximate (in the weak sense) as well as you want any distribution on $\mathbb{R}$ by the distribution of a continuous function on $[0,1]$, by generalizing this trick.
Comment: Thanks, that is a very nice answer! I guess that we can also make the $Y_n$ smooth, right? (by smoothing the transitions between the affine parts). So, even with this greater regularity, the variance can be far from zero. I guess that what we really need here is some *uniform* control over the $Y_n$, say e.g. Lipschitz constant bounded from above.
Comment: Yes, a $\mathcal{C}^\infty$ can indeed be constructed in the same way: if you make the transitions fast enough, then they (almost) won't be seen on the distribution (they will affect the values of $Y_n$ on a set of very small measure).


How to test for relationship between cumulative intake and outcome over time in single arm study?

Question: I have a one group trial with n = 100. I want to analyze the relationship between the accumulated amount of drug intake (continuous) and the effect (measured by symptom score).
For example, for different time points for patient 1:
t1: d_amount 10, S_score 50
t2: d_amount 15, S_score 45
t3: d_amount 20, S_score 40

For example, for different time points for patient 2:
t1: d_amount  5, S_score 50
t2: d_amount 10, S_score 45
t3: d_amount 30, S_score 40

How would I construct a (formally correct) hypothesis proving the statement: "There is a significant negative relation between the amount of drug taken (over time) and the symptom score"?
Answer: If we neglect the time variable, the problem can be addressed in a more straightforward way. Your question, both on the title and at the end of your post, relegate the time variable to a secondary position, so I do the same.
If you want to test the correlation between two variables, you can use Pearson's correlation coefficient, or Spearman's rank. You can calculate for each individual a value; then you can test how significant is this value by either

taking a look at the distribution the indicators follow, and calculate the probability of having such a value for the number of points obtained.
doing a Monte Carlo in which you shuffle the values in the data pairs a large number of times, calculate the indicator value for each of these datasets and with this get the distribution of indicator values for datasets with the same properties as yours, but that are by construction not correlated. You can then calculate what is the probability of getting you indicator value as the result of a chance alignment of the points in your shuffled dataset.

Note that these tests can be done individual by individual. You can after evaluate how the correlation in different individuals compares. However, if for each individual you only have 3 datapoints (i.e. pairs drug intake - response) then it will be hard to make any assessment on the correlation significance, because fortuitous alignments for such low number of points are still very likely. If that is the case, you should use the same kind of principle to take a look at how different is the population of correlation coefficients in your sample with those in an uncorrelated population.