Create an Array of NSDates like in Ruby

Question: I want to create an array of NSDates starting from today to next month. This can easily be done in Ruby using Time.now..(Time.now + 30.days)
How can I create an array of dates just like in Ruby in Objective C?
Comment: The answer to that question is only part of the answer to this one. The date calculation part of this question is important, and harder to figure out than the semantics of creating an array from a range of numbers.
Comment: @AndrewMadsen True - retracted.
Answer: Any ObjC solution is unfortunately going to be far more verbose than that Ruby code.
The correct way to make the calculation is with NSDateComponents:
NSMutableArray * dateArray = [NSMutableArray array];
NSCalendar * cal = [NSCalendar currentCalendar];
NSDateComponents * plusDays = [NSDateComponents new];
NSDate * now = [NSDate date];
for( NSUInteger day = 0; day < NUMDAYS; day++ ){
    [plusDays setDay:day];
    [dateArray addObject:[cal dateByAddingComponents:plusDays toDate:now options:0]];
}

To make the procedure more convenient (if you need to do it more than a few times), you could put this loop into a category method on NSCalendar, with NUMDAYS replaced with the argument and substituting self for cal.
Comment: The nice thing about this solution vs some of the others is that it avoids compounded error. i.e. instead of adding one day, thirty times, it adds one day to now, then adds two days to now, and so on. There are cases where that will produce better results.
Comment: Intriguing. Your statement makes me want to go hunting for such cases, @Catfish_Man.
Comment: Try something like calculating successive 2AMs in a US locale (or midnights in a Brazilian locale) across a DST transition. I think all the days after the transition should be off.
Answer: After much downvoting and commenting, here's my REVISED answer...
-(NSDate *)nextDayFromDate:(NSDate *)originalDate {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [NSDateComponents new];
    dateComponent.day = 1;
    NSDate *tomorrow = [calendar dateByAddingComponents:dateComponent toDate:originalDate options:0];
    return tomorrow;
}

NSMutableArray *dateArray = [NSMutableArray array];
NSDate *now = [NSDate date];
[dateArray addObject:now];
for (int i=0;i<31;i++) {
    NSDate *firstDate = [dateArray objectAtIndex:i];
    NSDate *newDate = [self nextDayFromDate:firstDate];
    [dateArray addObject:newDate];
}

What this does is use the NSCalendar API to add a "day interval" to any given NSDate. Add "Now" to the array, then do a loop 30 times, each time using the previous NSDate object as input to the logic.
Comment: Yep, matches mine pretty closely now.
Comment: I think this falls out of that scope. You're handing the system a time interval, and it's spitting out a new date object. If "now==Feb 28th,  leap year", then the system will know that "tomorrow=Feb 29th" and not "March 1st"
Comment: But you're not asking the system for "tomorrow". You're asking the system for a date 86,400 seconds after now, which may well be the same calendar day (or skip one!).
Comment: I see...makes sense. ok, well let's modify the loop to instead ask for "now == today, give me tomorrow. tomorrow = now, give me next day. next day == now, give me next day...
Comment: That's a nice thought, but you'll quickly find that date calculations are really hard because of the many edge cases out there. You're better off using the right API to handle this stuff.
Comment: honestly, who is downvoting all the answers in this question thread?
Answer: There's nothing built in to do this quite as concisely as the Ruby you've posted. Breaking the problem down, you need a way to get the day after a particular date. Here's a function that will do that:
NSDate *CalendarDayAfterDate(NSDate *date)
{
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = 1;

    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:components toDate:date options:0];
}

Next, you need to get an array of days one after the other:
NSDate *today = [NSDate date];
NSMutableArray *dates = [NSMutableArray arrayWithObject:today];
for (NSUInteger i=0; i<30; i++) {
    NSDate *tomorrow = CalendarDayAfterDate(today);
    [dates addObject:tomorrow];
    today = tomorrow;
}

Comment: That's nice of you Josh :). Even the answer fixed to match mine after I commented on it has more upvotes. Oh well...

Create an Array of NSDates like in Ruby


Alternatives to join on Spark dataframe

Question: I have two Spark dataframes that are each 539 million rows and 4 columns. columns A and B are strings and columns C,D, E and F are floats
<code>DF1
-----------------
A      B     C      D
"A1"  "B1"  1.1    1.2
"A2"  "B2"  1.3    1.4

DF2
-----------------
A      B     E      F
"A1"  "B1"  2.1    2.2
"A2"  "B2"  2.3    2.4
</code>
I would like to join DF1 (539 million rows) and DF2 (also 539 million rows). I tried DF1.join(DF2,, "fullouter") on 50 node cluster and 8 GB executor memory. It automatically terminates the cluster with out-of-memory error message.
Are there alternatives to join with rdds, or datasets that are memory efficient than the df.join()?
Comment: I think you haven't mentioned the common key for both the tables.
Answer: Please check the following

Compression as been used.
Join condition is present.
Check you driver program heap memory from the spark UI and change it.
Answer: You also need to check following:
1) How have you partitioned your data
2) how many executors have you assigned based on number of partitions
3) As mentioned above: the driver memory

Alternatives to join on Spark dataframe


Como atualizar uma View?

Question: Tenho uma tabela onde guarda entrada e saida de caminhões. Nessa tabela tem dois campos do tipo Date, quero atualizar os dados desses campos. Estou usando o select a seguir.
<code>  UPDATE V_TPL_ACOMPANHAMENTO SET E_POR = TO_DATE('08/10/18 22:24','DD/MM/YY HH24:MI'),
  S_PORT = TO_DATE('09/10/18 01:55','DD/MM/YY HH24:MI') WHERE COLETA='EDB-TP-32764C'
</code>
Porém quando tento atualizar, aparece a mensagem de erro: ORA-01732: data manipulation operation not legal on this view
Answer: Causa: foi feita uma tentativa de usar uma instrução UPDATE, INSERT ou DELETE em uma view que contenha expressões ou funções ou foi derivada de mais de uma tabela. Se uma operação de junção tiver sido usada para criar a exibição ou a exibição contiver colunas virtuais derivadas de funções ou expressões, a visualização só poderá ser consultada.
Fonte documentação oracle.
Comment: http://www.linhadecodigo.com.br/artigo/2821/trigger-oracle-basico.aspx tente uma INSTEAD OF TRIGGER

Como atualizar uma View?


How to get the average for one column of data in sql server

Question: My goal is List employees that have greater than average education level
Here is what i have
Select  [ED_LVL],
   AVG (ED_LVL) as 'AVG ED_LVL'
   From [Enterprise].[dbo].[Employee]
   Group BY [ED_LVL]

I'm guessing i have to make some type of subquery or partition? not sure how to do this
thanks!
Comment: use "HAVING" clause to filter aggr.
Comment: @yswai1986 - Could you show a sample with `Having`?
Answer: Try this :
Select  *
From [Enterprise].[dbo].[Employee]
WHERE ED_LVL > (Select  AVG(ED_LVL) From [Enterprise].[dbo].[Employee])

Comment: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
Answer: This is how average function can be used:
SELECT AVG(column_name) FROM table_name

Regarding to you question, try this:
Select  * FROM [Enterprise].[dbo].[Employee]
WHERE [ED_LVL]>(SELECT AVG(ED_LVL) FROM [Enterprise].[dbo].[Employee])

Which gives Employee details Whose ED_LVL is greater than average ED_LVL.
Comment: Who asked you for Syntax of `AVG` Function?
Answer: Try this:
select *
from Employee t
where t.ED_LVL >
(
    select AVG(e.ED_LVL) [avg]
    from Employee e
)

Answer: try this !!
 SELECT  [ED_LVL],
    FROM (
      SELECT
         [ED_LVL],
        AVG( [ED_LVL]) OVER () AS  avg_edu,
      FROM [Enterprise].[dbo].[Employee]
    ) s
    WHERE [ED_LVL]> avg_edu


Views math expression or Computed field to find date difference in views

Question: I have two content type, Bill (Type1) and Cash Receipts (Type2), Type2 referencing Type1 when cash is received.
In Type1 I have date field called (Bill Issue date), and Type2 I have date field cash receipt date.
So I want to calculate, different between those two dates. I was trying by creating views with two date (by entity reference relationship), then subtract two filed with math expression field, but it return zero.
Actually, I have no idea whether I was wrong or Its not possible to calculate different between dates with views math expression field?
I think, it can be done with Computed Field, I did one within same content type, but I don't know how to access a field from different content type, please help.
Code that I was used to calculate date for same content type, but how I can access a field from other content type?
If the Machine name of your date-field is 'field_example_date', then the Computed Code (PHP) would be
$startdate = $entity->field_example_date['und'][0]['value']; // Value of start-date
$enddate = $entity->field_example_date['und'][0]['value2']; // Value of end-date

$datediff = strtotime($enddate) - strtotime($startdate);
/* The PHP Function STRTOTIME parses the english textual datetime description
 * into a Unix timestamp
 */

$num_leaves = $datediff/(60*60*24);
/* Since we need the number of days IN-BETWEEN,
 * we divide the resultant difference by 60*60*24 .
 *
 * Incase of counting no.of days "FROM" to "TO" days, add 1 to the above result.
 * $num_leaves = $datediff/(60*60*24) + 1;
 */

 $entity_field[0]['value'] = $num_leaves;

The Display Code (PHP) will have

$display_output = $entity_field_item['value'];

Answer: You can achieve this use a template file, since you can use PHP inside templates in Drupal 7
In your view

Now, add both of your date fields and do this to each of them

In your web directory, go to /sites/all/themes/[yourtheme]/templates folder
Create a file named views-view-fields--[view-name]--[machine-name].tpl.php
EX: views-view-fields--hello-world--block-1.tpl.php
Inside the template file put:
<?php

$date1 = new DateTime('$fields["field_invoice_issue_date"]->content');
$date2 = new DateTime('$fields["field_payment_receipt_date"]->content');
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

?>

Remember to flush/clear the cache to see changes.
Comment: I was trying to follow your each step, but no success.  Its table format, my views name is "date_calculator" and its page view, so I added code into views-view-fields--date_calculator--page.tpl.php on the other hand there no option to add custom date format in view so I added your format from admin/config/regional/date-time and then select it. Filed name is field_invoice_issue_date and field_payment_receipt_date . So what I need to do?
Comment: `I added code into views-view-fields--date_calculator--page.tpl.php` your view name needs to be **views-view-fields--date-calculator--page.tpl.php** I have added your date fields to the code.
Comment: I have updated the code, I noticed I had a minor error.


Why can I create a reference to a value from a post-increment, but not from a pre-increment expression?

Question: % perl -e '$i = 9; $p = \$i++; $q = \++$i; $i = "WTF"; print "$$p $$q\n"'
9 WTF

I was expecting that both work the same and print 9 11, since neither the pre- nor the post-increment could be used as lvalues in perl.
Is this described anywhere, has it any rationale, or it's just a glitch? All I could find was about the magical properties of the increment operator when applied to non-numeric strings, which seems totally unrelated.
Notice that this also applies to decrement operators, it's not a matter of operator precedence (adding parens or writing it as ($p, $q) = \($i++, ++$i) does not change anything) and it's the same behaviour in older versions like perl 5.6.
I'm not asking about workarounds (I know about putting an int between the \ and the ++, or adding a zero, etc).
Comment: Instead of using a workaround to a workaround, do `\( my $anon = $i )` which clearly identifies your intent. Clarity is importing here since this is a really weird thing to do.
Answer: Post-decrement returns the old value of $i, so it must return a fresh scalar and does so.
Pre-decrement returns the new value of $i, so it simply returns $i. There's no point in building a new scalar for nothing.
Comment: Why? It mashes very lithe sense to take a ref to a scalar, and even less to an anonymous one. There's absolutely no point to add all that logic
Comment: Ah yes for `read ARGV`. Still, `$/ = \++$i;` makes no sense. And constant.pm does not use `\++$i`. You then listed reasons for creating constants, but not reasons for using scalar refs, so they're *completely* irrelevant. /// So, while you did managed to come up with a *single* example of useful use of a scalar reference, you have been *unable* to come up with any examples that would benefit at all from changing the current system, much less a reason that would warrant slowing down every Perl program and removing safety constraints.
Comment: Thanks that somehow makes sense implementation-wise, yet it still feels sketchy. Surely they could've caught it at compile time and only built the scalar if needed. Kind of similar cases are the `//`, `&&` and `||` operators.
Comment: slow down a bit with that one ;-) how about setting `$/` to record mode? or creating enum-like constant subs without building strings and evaluating them?. There are *plenty* of uses for refs to anonymous scalars (especially when you're using perl for one-liners and such). But in this case, I would've done the reverse -- I would've allowed for `++`, `--`, `//`, etc to be used as lvalues. Even if `$a++ = ...` does not make much sense with the default operators, it is very useful when `++` is overloaded. But I'll leave it here -- it was not my intention to start a what-if discussion.
Comment: Re "*slow down a bit with that one*", You just listed a two *rare* uses, and both are really bad features that have far better alternatives. So you're effectively jsut repeating what I said: It makes very little sense to use scalar references. // Re "*I would've allowed for ++, --, //, etc to be used as lvalues.*", That needlessly converts compile-time errors into run-time errors. BAD! There's a reason we have rvalues.
Comment: No, they don't have any better alternatives (there aren't actually any practical alternatives), unfortunately. And there are many other uses of a ref for sematic purposes (in core or elsewhere, like it or not). But you're veering this into a philosophical discussion about "good practices" and such -- basically about what *kind* of  inconsistency/non-orthogonality is *good* (as if there were any good kind of it, LOL)
Comment: Setting $/ to a ref and using readline is like using read with a number, except it breaks every other readline in the program. The official way of creating constants is with the constant module, which is better is every way.
Comment: `read` does not work with `ARGV` in the same way `<>` does, and `use constant` does internally the same thing you proscribe. And there are **many** reasons to want to reimplement `constant.pm` (with another name), like fixing its horrible syntax (to make it more enum-like and allowing simply copy-pasting from C headers) and having automatically generate reverse mappings from values to names.


Criando/Visualizando relatório em HTML

Question: Galera, estou com um problema e não consegui raciocinar uma solução ... Pessoal que já usou iReport sabe que tem como fazer agrupamento de forma bem fácil nele... O problema é que agora estou fazendo relatórios em HTML ( na unha rs ), e queria fazer agrupamento por filiais ( como exemplo ):
<code>Filial  001 - LOJA TAL
                              column         column          column         column        column
                              dados           dados            dados           dados          dados
                              dados           dados            dados           dados          dados
                              dados           dados            dados           dados          dados
Total da Filial 001  =        TOTAL          TOTAL           TOTAL          TOTAL         TOTAL

Filial  002 - LOJA TAL
                              column         column          column         column        column
                              dados           dados            dados           dados          dados
                              dados           dados            dados           dados          dados
                              dados           dados            dados           dados          dados
Total da Filial 002  =        TOTAL          TOTAL           TOTAL          TOTAL         TOTAL

Total Geral           =       TOTAL GERAL
</code>
E assim por diante.. no iReport é só colocar um group... Mas agora que to fazendo em HTML, não consigo achar uma solução para meu problema... Pois está repetindo o nome da filial em todas as linhas, e não consegui pensar em como fazer o total para filial e depois o total Geral...
Exemplo :
Digamos que vem os números(resultado da consulta) (1, 1 , 1, 1, 1, 2, 2, 2, 2, 3, 3, 3,) Printar apenas : 1, 2 , 3.
Já tentei pegar os valores da tabela de filiais e comparar com o resultado de filiais que está vindo da consulta, mas não deu certo, continua printando repetidamente.
Por exemplo :
<code> $filias => $this->find(filiais)
 $dadosConsulta['numero_filial'] (este aqui que está vindo repetido, filial para cada resultado)

 if($filiais['numero_filial'] == $dadosConsulta['numero_filial']){
 echo $dadosConsulta['numero_filial'];
 }
</code>
Tentei algo desse tipo acima, mas tambem não deu certo... printava repetido ainda.
Gostaria da ajuda de vocês ! Valeu.
Edit:
Segue imagem.. No final quando mudar de filial de 1 para 2 e 2 para 3, assim sucessivamente, printar Total por Filial, resume-se nisso ! Pois da forma que estou fazendo, está sendo printado depois de todo resultado por vendedor. Várias vezes.
Answer: Se vem tudo em um select só, você pode tentar algo assim:
<code>$filialAnterior = -1;
for/while/foreach (o que vc usar para o loop){
     if($filialAnterior === $dadosConsulta['numero_filial']){
        // escreve dados
        // conta total da filial
     }else{
        // mudou filial
        // escreve total da filial
        // abre cabeçalho da nova filial
        // zera total da filial
        $filialAnterior =  $dadosConsulta['numero_filial'];
     }
}
</code>
Comment: Valeu pela resposta, então... Eu já estou fazendo um loop dentro do loop, o problema é que está vindo os dados assim, exemplo : ( Loja 1, Loja 1, Loja 1, Loja 2, Loja 2, Loja 2, Loja 3 , Loja 3 , Loja 3 e assim por diante ), então se eu comparar filial com filial, ele vai repetir as filiais da mesma forma.
Comment: Seriam 3 níveis? Nível 1: Loja, Nível 2: Filial, Nível 3: Produtos? Seriam 3 loops?
Comment: Sim, acredito que com 3 loops funcionaria (atualizei minha resposta).
Comment: Me avisa se deu certo ok?
Comment: Allan Andrade, tenho uma consulta que traz todos os dados que preciso, e na frente de onde é esses dados ( que filial ), então assim, vem tudo em uma consulta só ! Vou tentar adicionar imagens
Comment: Dá uma olhada na ideia que postei na resposta acima.
Comment: Mas os 3 loops porque ? Sendo que está tudo dentro de 1 array, que é o resultado da consulta. Loja e Filial é a mesma coisa, ou seja, seria 2 loops.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/29158/discussion-between-allan-andrade-and-edson-rodrigues).
Comment: Ok ! Te mandei mensagem lá.
Comment: Allan Andrade, obrigado pela ajuda até agora ! Então, até a parte de só mostrar o nome da filial só uma vez deu certo... agora está faltando apenas o resultado POR FILIAL... Este vem de outra pesquisa, ou se tiver outra forma de mostrar esse resultado por filial, beleza também...
Comment: O resultado por filial está sendo impresso apenas da segunda filial em diante... sendo que o valor da primeira filial, está sendo impresso na segunda filial, e da segunda, na terceira e assim por diante.  Estive tentando resolver, mas não deu certo.

Criando/Visualizando relatório em HTML


Given foci and the ellipse's constant, how can I find the major and minor axes?

Question: Given that the definition of an ellipse is the set of points (x,y) where the distance from focus 1 to (x,y) plus the distance from from focus 2 to (x,y) is a constant, and given that constant, and the positions of the foci, how can I find the lengths of the major and minor axes of the ellipse? I'm struggling to relate these terms. Thanks for your help!
Comment: If $S, S'$ are foci, and $P$ is a point on the ellipse, then $SP+SP' = 2a$ and $SS' = 2ae$, where $e$ is the eccentricity of the ellipse. From these find $e$ and $b^2 = a^2(1-e^2)$
Comment: Can you explain your notation? What is P' ?
Comment: Sorry, it should be $SP+S'P = 2a$
Answer: For convenience, I'll call the distance between the foci $\ell$.
The major axis goes through both foci; if you have the length constant $d$, the two lines it makes covers the distance between the foci once and the distance from one focus to the end of the ellipse twice.  --Which actually means that it covers the semimajor axis (which is distance from center to end, passing through the focus) twice, so the major axis has length of exactly $d$.
The minor axis is slightly harder, being the perpendicular bisector of the major axis.  The extreme point is distance $d/2$ from each focus, and is the hypotenuse of a right triangle that has one base that is the distance between one focus and the center $\ell/2$. ...conveniently, this means that the semiminor axis has length $\sqrt{(d/2)^2-(\ell/2)^2} = \sqrt{d^2-\ell^2}/2$, so the minor axis has length $\sqrt{d^2-\ell^2}$.
Answer: Ellipse property
$$ b^2 = a^2 - c^2 $$
$$ (2b)^2 = (2a)^2 - (2c)^2 $$
Note that since
$$ majoraxis=2a= d_1+d_2 ,$$
$$[minoraxis^2 =(2 a)^2 - (inter-focal distance)^2 ]$$
So
$$ minoraxis^2 = (d_1+d_2)^2 - (inter-focal distance)^2 $$
$$ minoraxis = \sqrt{(d_1+d_2)^2 - (inter-focal distance)^2}.$$


How to modify a commit on a branch that has descendent branches?

Question: Assume I have this history log:
* hash8 (HEAD -> branch_4, origin/branch_4) Message 8
|
* hash7 Message 7
|
* hash6 (origin/branch_3, branch_3) Message 6
|
* hash5 Message 5
|
* hash4 (origin/branch_2, branch_2) Message 4
|
* hash3 Message 3
|
* hash2 (origin/branch_1, branch_1) Message 2
|
* hash1 Message 1

And I want to do some code changes to commit with hash4 and history to look the same. Please note that I have branches in between too, not only commits. How would you do that?
Comment: I already tried that. But the branches are not preserved. Instead, by doing exactly that you end up with two paths: one with the original commits and branches, and another one with only one branch and all the commits with the new changes on hash4.
Comment: Does this answer your question? [How to modify a specified commit?](https://stackoverflow.com/questions/1186535/how-to-modify-a-specified-commit)
Answer: You cannot do this at all.  No part of any commit can ever be modified.
You can do something different, that may—or may not—be good enough.
Given any Git commit, you can:

extract that commit, so that you can work on it
do some work
make a new commit, which will have a different hash ID

and having made that new commit, you can then repeat this.  So, suppose you have this series of commits:
A--B   <-- branch_1, origin/branch_1
    \
     C--D   <-- branch_2, origin/branch_2
         \
          E--F   <-- branch_3, origin/branch_3
              \
               G--H   <-- branch_4, origin/branch_4

(this is the same graph you drew, except that I've used uppercase letters to stand in for the hash IDs, and put newer commits towards the right, rather than towards the top).  It is completely impossible to change any of the existing commits, but we can extract D to a work area, then make changes, then make a new and improved D':
A--B   <-- branch_1, origin/branch_1
    \
     C--D   <-- branch_2, origin/branch_2
      \  \
       D' \  <-- [remember this hash]
           \
            E--F   <-- branch_3, origin/branch_3
                \
                 G--H   <-- branch_4, origin/branch_4

Now that we have D' we copy E atop it, changing one thing—its parent—so as to make E', the same way we copied but changed D to make D':
A--B   <-- branch_1, origin/branch_1
    \
     C--D   <-- branch_2, origin/branch_2
      \  \
       D' \  <-- [remember this hash]
        \  \
         E' E--F   <-- branch_3, origin/branch_3
                \
                 G--H   <-- branch_4, origin/branch_4

We'll need to copy F to F' and G to G' and H to H' as well, for a total of five commits copied to new-and-improved commits:
A--B   <-- branch_1, origin/branch_1
    \
     C--D   <-- branch_2, origin/branch_2
      \  \
       \  \  <-- [remember this hash]
        \  \
         \  E--F   <-- branch_3, origin/branch_3
          \     \
           \     G--H   <-- branch_4, origin/branch_4
            \
             D'  <-- new_branch_2
              \
               E'-F'  <-- new_branch_3
                   \
                    G'--H'  <-- new_branch_4

We now have new branches, which are "just as good" as the old ones (because they have commits that are as good or better, but with different hash IDs).  Now we must discard the old branch names in favor of the new ones, perhaps by renaming the old branches to old_* and the new ones to take out the new_.
(Our old_* names are no longer very useful so we can delete them entirely, sooner or later.)
Finally, our remote-tracking names origin/* are remembering branch names as stored in some other Git, so now we must convince that other Git repository to jettison its copies of those commits and start using our new copies.  To do that, we will need to use git push --force or something similar to send our new commits to that other Git and tell it abandon all the work you used to have, in favor of these new and improved commits.  For instance:
git push --force-with-lease branch_2 branch_3 branch_4

would do the trick (and the --force-with-lease would make sure that their hash IDs, which are in our origin/* names, match up with what we think they do).
To achieve this in realistic situations, use git rebase or git filter-branch or similar
When the number of commits to "improve" like this is small, you can do it one commit at a time, using git cherry-pick, leaving yourself markers: here is where new_branch_3 goes for instance.  When it's large, this is painful.  You will want to automate the process.
Unfortunately, this is tricky.  Fortunately, there are several power tools for this, including git replace.  This lets you insert a graft.  However, grafts do not transfer on clones: whoever clones your repository sees the original, un-grafted history.  Fortunately, git filter-branch or the new git filter-repo can then transform the grafted clone into a clone with a new series of commits, updating branch names en-masse.  See other StackOverflow answers for details.


If $x=y+\sqrt{y^2+1}$
Then how to write $y$ in terms of $x$?

Question: If $$x=y+\sqrt{y^2+1}$$
Then how to write $y$ in terms of $x$? Please tell me some hints
Comment: What have you tried so far? What if you square both sides? x²=... Then solve for y.
Comment: Note that $\log(x) = \sinh^{-1}(y)$ and then $y = \sinh(\log(x))$
Answer: Hint: Just bring $y$ to the other side then square both sides.
$$x = y+\sqrt{y^2+1}$$
$$x-y = \sqrt{y^2+1}$$
$$(x-y)^2 = y^2+1$$
Here, note that $(a\pm b)^2 = a^2\pm 2ab+b^2$, and after necessary simplification, it should be clear enough.
Comment: Would you take a look on my previous OP please?
Comment: Please edit your answer about MY previous OP  then I'll accept it
Comment: Do you mean the previous question you've asked?
Comment: Yesss . That one. Cubic function! How to write y in terms of x in $x^3+2x=y^3+2y-1$
Answer: Hint. Note that $\text{arcsinh}(y)=\log(y+\sqrt{y^2+1})$. See Inverse hyperbolic sine.
Answer: As $(\sqrt{y^2+1}-y)(\sqrt{y^2+1}+y)=\cdots=1,$
$\sqrt{y^2+1}+y=x\iff \sqrt{y^2+1}-y=\dfrac1x$
$x-\dfrac1x=?$
Comment: (+1) This was the approach that came to mind when I saw the question.
Comment: See https://math.stackexchange.com/questions/400403/solve-sqrtx4-sqrtx1-1-for-x/400410#400410   https://math.stackexchange.com/questions/616536/how-to-solve-for-x-in-sqrt4x27-sqrt455-x-4/616537#616537
Answer: I assume that
$x, y \in \Bbb R. \tag 0$
We are given
$x = y + \sqrt{y^2 + 1}. \tag 1$
We observe that this equation implies
$x > 0, \forall y \in \Bbb R, \tag{1.2}$
since
$y^2 < y^2 + 1 \Longrightarrow \vert y \vert < \sqrt{y^2 + 1}; \tag{1.5}$
we proceed:
$x - y = \sqrt{y^2 + 1}; \tag 2$
$x^2 - 2xy + y^2 = (x - y)^2 = y^2 + 1; \tag 3$
$x^2 - 2xy = 1; \tag 4$
$2xy = x^2 - 1; \tag 5$
by virtue of (1.2), we may divide by $2x$:
$y = \dfrac{x^2 - 1}{2x}. \tag 6$
CHECK:
From (6),
$y^2 = \dfrac{(x^2 - 1)^2}{4x^2} = \dfrac{1 - 2x^2 + x^4}{4x^2}; \tag 7$
$y^2 + 1 = \dfrac{1 - 2x^2 + x^4}{4x^2} + 1 = \dfrac{1 - 2x^2 + x^4}{4x^2} + \dfrac{4x^2}{4x^2} = \dfrac{1 + 2x^2 + x^4}{4x^2} = \dfrac{(1 + x^2)^2}{4x^2}; \tag 8$
and again, by virtue of (1.2), we may apply $\sqrt \cdot$ to both sides and find
$\sqrt{y^2 + 1} = \dfrac{1 + x^2}{2x}; \tag 9$
$y + \sqrt{y^2 + 1} = \dfrac{x^2 - 1}{2x} + \dfrac{1 + x^2}{2x} = \dfrac{2x^2}{2x} = x. \tag{10}$


Combining Tables in dplyr

Question: I have a large data set, and I'm trying to create a table that shows the number of observations in each zip code for each year. The tricky part is I need each column to be a year, and the rows to be the number of observations of each zip code in each year. Some zip codes have no observations in one of the years, so there should be some empty slots. I only know how to create three separate tables with the three separate years, which is what the code is for below. Could someone help me basically combine this into one table?
BuildingZipCodes18 <- Data %>%
  filter(year(`Issued Date`) == 2018) %>%
  group_by(`Zip`) %>%
  summarise("2018" = n())

BuildingZipCodes19 <- Data %>%
  filter(year(`Issued Date`) == 2019) %>%
  group_by(`Zip`) %>%
  summarise("2019" = n())

 BuildingZipCodes20 <- Data %>%
  filter(year(`Issued Date`) == 2020) %>%
  group_by(`Zip`) %>%
  summarise("2020" = n())

Answer: Instead of filtering data for each year try using count which will give you number of rows for each Zip code in each year.
library(dplyr)
result <- Data %>% count(Zip, year = lubridate::year(`Issued Date`))

In base R you could use table :
table(Data$Zip, format(Data$`Issued Date`, '%Y'))

Comment: Thank you! The table function printed how I wanted, with each year as a column. However, it prints in a different style. It shows up in the environment as a value instead of data. Is there anyway to get the results of table() to be a data table I can view like count() did.
Comment: @Ben You can do `result <- as.data.frame.matrix(table(Data$Zip, format(Data$\`Issued Date\`, '%Y')))`

Combining Tables in dplyr


How to filter users based on address location?

Question: I have a content type "job". There is a field "location" which contains the zip code of area. Now i want to filter users based on distance from job's zip code. Each user also have a zip code.
I already have a view which is filtering users on different criteria. Is there any way to achieve this in view?
EDIT
here is what exactly i needed.
adding a job should have a field to add the zip code of the location of the job. This should change the way the users are filtered for the job as the customer should be able to filter the users using radius selector for 1 km, 5km, 10km, less than 50 km.
Thanks
Comment: You need to use something that does geolocation/proximity search. I thought Location module did this in 7.
Answer: You can use geolocation_proximity
Answer: I believe this is what you are looking for https://www.drupal.org/node/1944648


Transforming the independent variables is NOT improving fit for conditional logistic regression

Question: I built a conditional logistic regression model for 'guest booking a hotel from the hotel search results page'. In my initial model, I didn't do any transformations to the independent variables. This model fits fine, and I am exploring ways to see if I can improve the fit.
So, later, I tried different transformations (log, normalizing etc.) to the independent variables (distance from search center, rate , reviews, etc.). However, whatever transformations and combination of transformations I try for the independent variables, the model fit is not improving than the initial model (without transformations).
Here is what my data looks like. Instead of using absolute distance or price in below as the independent variable, I am using "distance/(mean distance in the search)". And this transformation is very relevant for the data and assume it should improve the fit atleast slightly. Any help would be greatly appreciated.
Search   Property_id    distance (miles)    price   # of reviews    Booked
1         abc             0.9                  75      125            0
1         ced             1.5                  67      541            0
1         der             2.3                  68      320            1
1         gft             1.1                  85      84             0
2         bcd             3                    70      64              0
2          bcr            2.3                  105      320            1
2          edr            4.4                  98       154            0
2          gft            7.8                 120       27             0
2          frt            6.2                  80       65             0

I have pretty good data size with some 50K searches in my model data.
Comment: (1) What, if any, indication is there of lack of fit in the initial model? (2) No particular transformation is guaranteed to improve fit of course, & if you're trying many transformations wildly in the hope of improving fit, you need to take some measures to avoid overfitting. It'd probably make more sense to use polynomial or spline bases for predictors from the outset. (3) There are so few details in your question that you can't expect more than vague generalities in any answer.
Comment: Thank you @Scortchi . I don't see any lack of fit specifically. I validated the model on a test dataset and results seem to be okay. I am checking on how to improve the performance and if transformations can be helpful.
Comment: @Scortchi, I wrongly assumed that transformations should improve the fit. but however, even some relevant transformations (like dividing the distance of a property by the mean distance of all properties in result set) ,  didn't help.
Answer: It would be helpful to see more data to be clearer on why this is occuring.
With that being said, here is my take on the problems you describe:
1) Have you already checked with a QQ-Plot (if you are using R, input: qqnorm(variable); qqline(variable) the distribution of your model? You need to make sure that the distribution (or the one you transform it to) makes theoretical sense, and you are not just doing so by a trial and error process.
2) A logistic regression, by its very nature, has much less variation in the dependent variable than an OLS regression, since the dependent variable is not interval. In this regard, higher numbers of observations are preferable when running a logistic regression (500 or greater according to Studenmund et. al). Does your dataset have sufficient observations to explain the variation in the dependent variable?
You should think carefully about the above two factors, along with reevaluating whether your independent variables make theoretical sense in the first instance, before attempting to transform data in this manner.
Comment: But a logistic regression does not care about the distribution of the *independent* variables, there is no model fit reason to transform one to normality, or anything else.  What is important in the conditional distribution of $Y \mid X$.
Comment: What exactly are you checking the distribution of, & why, in (1)?
Comment: @Scortchi The distribution of the independent variables in the study. e.g. if the OP is trying to normalise a variable that already follows a normal distribution, then clearly the results will be inaccurate. Therefore, one needs to know the distribution of the variable before attempting to modify the same.
Comment: Thank you Matthew, I misunderstood the question somewhat. To your point, since a logistic regression is not looking at distribution of independent variables as a factor - as you stated, transforming variables in order to improve fit is likely not the best way to go about this.


Is the 25 game suspension for Chris Davis too much?

Question: Chris Davis just got a 25 game suspension for violation of the MLB's drug program for use of Adderall. He had a medical exemption in the past, but for whatever reason did not have one this year.
I could see if it was a PED for a suspension like this, but for Adderall? It might give him better focus, but he clearly had a medical reason to take it. Per the MLB Drug Rules is there much flexibility when it comes to something like this, i.e., previous exemption?
Comment: This seems like an opinion question, and isn't appropriate for the SE system to me.
Answer:
Is the 25 game suspension for Chris Davis too much?

No. This is Chris Davis's second positive test(1).
Section 7.B (below) of the MLB Joint Drug Agreement states that a second stimulant violation is a 25-game suspension(2 - on p.22 of the MLB JDA document).
Comment: I would have thought that the past therapeutic use exemption would have been taken into consideration, but I guess there really isn't much flexibility in the MLB Drug Agreement.
Comment: @JimmyGlenn the first test would have been outside the realm of the therapeutic use exemption as well.


How do I replace a string when altering the output of a view field?

Question: I have some text I'd like to alter in the custom output of a view field.  For example, if the output contains pancakes, I'd like to replace it with waffles.
The following code doesn't work.
<code>{{ field_recipe_prep__value | replace({'pancakes': "waffles"}) }}
</code>
How do I replace a string when altering the output of a view field?
Answer: Remove the <code>__value</code> part.
<code>{{ field_recipe_prep | replace({'pancakes': "waffles"}) }}
</code>


Spring Boot Integration Test started to fail after spring version upgrade

Question: After I upgraded Spring boot version 2.3.1.RELEASE to 2.6.1 for some reason my integration test started to fail due to OutOfMemory error.
Here is my test:
@Sql(
    scripts = [
        "classpath:sql/init_clear.sql",
        "classpath:sql/import/import_entities.sql"
    ],
    executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(
    initializers = [
        PostgreSQLContainerInitializer::class
    ]
)
@ActiveProfiles("dev")
class MyRepositoryTest {

    @Autowired
    private lateinit var repository: MyRepository

    @Test
    fun `Get all by id should work well`() {
        val id: Long = 1
        val entities = repository.getAllById(id)
        assertEquals(1, entities.size)
        assertEquals(id, entities[0].id)
    }

}

The stack trace of the error is the following:
org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 45.
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:63)
    at firstname.lastname@example.com/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at firstname.lastname@example.com/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at firstname.lastname@example.com/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at email@example.com/java.lang.reflect.Method.invoke(Method.java:568)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy2/jdk.proxy2.$Proxy5.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: java.lang.OutOfMemoryError: Java heap space
    at ch.qos.logback.classic.spi.ThrowableProxyUtil.steArrayToStepArray(ThrowableProxyUtil.java:49)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:55)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)
    at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60)

I debugged this issue a little more and found out that the error itself is produced due to work of the ResetMocksTestExecutionListener, to be more precise because it's beforeTestMethod function:
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
    if (MOCKITO_IS_PRESENT) {
        resetMocks(testContext.getApplicationContext(), MockReset.BEFORE);
    }
}

And the real cause is java.lang.IllegalStateException: Failed to unwrap proxied object.
We have an option to stop using mockito in favor of mockk cause we use kotlin in this project but it's too expensive for us to do this in nearest future so it would be nice if there is some fast workarounds.
Thanks in advance for help!
Comment: I ran into the same problem. Maybe you have problem like - https://github.com/spring-projects/spring-security/issues/10419. To make sure, try to comment out the AuthenticationManager bean first.
Answer: Unfortunately the only way to make it work was to exclude mockito-core from dependencies and rewrite all current test cases so they use mockk only.
To exclude mockito from spring boot test starter you need to do the following:
testImplementation("org.springframework.boot:spring-boot-starter-test") {
    exclude( module: 'mockito-core')
}


IF no pandas retornando The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Question: Estou com uma DS com duas colunas, uma com mês de 1 a 12, e outra com ano de 2015 a 2021, e estou tentando criar uma coluna chamada Fiscal Year.
Estou criando uma função para que quando o mês estiver entre 4 e 12 dentro do ano 2017 retornar FY17/18.
def fiscal_year(x,y):
    if ((x >= 4.0) & (x <= 12.0)) & (y == 2017.0):
        return 'FY 17/18'
    else:
        return 'nada'

E quando vou aplicar:
instal_final_csa['Fiscal Year'] = instal_final_csa.apply(fiscal_year(instal_final_csa['MÊS'],instal_final_csa['ANO']))

Retorna o erro:

ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().
Comment: Tente: `instal_final_csa['Fiscal Year'] = instal_final_csa.apply(fiscal_year(instal_final_csa['MÊS'],instal_final_csa['ANO']), axis=1)`. Note que acrescentei o `axis=1`
Comment: Tentei, mas retornou o mesmo erro.
Answer: Consegui fazer por np.select
instal_final_csa2 =instal_final_csa
conditions = [((instal_final_csa2['MÊS'] >= 4 )&(instal_final_csa2['MÊS'] <= 12))&(instal_final_csa2['ANO'] == 2016),
              ((instal_final_csa2['MÊS'] >= 1 )&(instal_final_csa2['MÊS'] <= 3))&(instal_final_csa2['ANO'] == 2017),
              ((instal_final_csa2['MÊS'] >= 4 )&(instal_final_csa2['MÊS'] <= 12))&(instal_final_csa2['ANO'] == 2017),
              ((instal_final_csa2['MÊS'] >= 1 )&(instal_final_csa2['MÊS'] <= 3))&(instal_final_csa2['ANO'] == 2018),
              ((instal_final_csa2['MÊS'] >= 4 )&(instal_final_csa2['MÊS'] <= 12))&(instal_final_csa2['ANO'] == 2018),
              ((instal_final_csa2['MÊS'] >= 1 )&(instal_final_csa2['MÊS'] <= 3))&(instal_final_csa2['ANO'] == 2019),
              ((instal_final_csa2['MÊS'] >= 4 )&(instal_final_csa2['MÊS'] <= 12))&(instal_final_csa2['ANO'] == 2019),
              ((instal_final_csa2['MÊS'] >= 1 )&(instal_final_csa2['MÊS'] <= 3))&(instal_final_csa2['ANO'] == 2020),
              ((instal_final_csa2['MÊS'] >= 4 )&(instal_final_csa2['MÊS'] <= 12))&(instal_final_csa2['ANO'] == 2020),
              ((instal_final_csa2['MÊS'] >= 1 )&(instal_final_csa2['MÊS'] <= 3))&(instal_final_csa2['ANO'] == 2021),
              ((instal_final_csa2['MÊS'] >= 4 )&(instal_final_csa2['MÊS'] <= 12))&(instal_final_csa2['ANO'] == 2021),]
choices = ['FY16/17','FY16/17','FY17/18','FY17/18','FY18/19','FY18/19','FY19/20','FY19/20','FY20/21','FY20/21','FY21/22']
instal_final_csa['Fiscal Year'] = np.select(conditions,choices,default = 'nada')


Search Keywords in MOSS

Question: I'm setting up a new Search Center for our Intranet using MOSS and want to make heavy use of of Keywords and Best Bets.  However two questions about this have me perplexed and I would appreciate any help/guidance?
1)  If you assign a contact to a keyword/best-bet and set a review date, my understanding is that SharePoint will automatically send that contact an email alert when that time comes.  However in my testing just using my account as the contact I have never received one of these.  Am I doing something wrong?
2)  What permissions would a user need to edit/update a keyword they are the assigned contact for?  I assume too that if they have the rights to update one of them then they can probably unfortuantely update them all, correct?
Answer: I spoke with Microsoft about these questions and learned that there is no automated alert or built-in workflow that triggers when a keyword hits its review date.  Also only a site collection administrator can view and update a keyword.  If you want this type of functionality your only choice is to roll your own solution.
Answer:
I cannot get an alert sent on my systems - not really proof of anything though.
The keywords are stored in the site settings, so site collection administrator is going to required. They will also all be able to edit them.

However, you could easily create a list that allows people to add "keywords" and permission it so they can only edit thier own. Add an event handler to modify the actual keywords when an item is added or modified.
Comment: Nat, note that I discovered that keywords are not stored in the site collection but rather the SSP.  You can see this by taking a STSADM backup of the site collection and then restoring it on another place, for which you'll see the keyword collection will be empty.

Search Keywords in MOSS


Topological relation between Complex numbers and R^2

Question: Topologically,are the space of complex numbers and the Euclidean space $\mathbb R^2$ (with the standard topologies) the same?
Comment: In a word, yes.
Comment: Right.So when complex numbers are treated topologically without explicitly mentioning the topology,we assume an open disc to be a basis element,right?
Comment: A topological space is a set and a set of subsets. The set of complex numbers does not refer to a topology, it is a set. One can form different topologies from the same set.
Comment: Usually I'd say yes. At any rate they can trivially be made to be as R^2 is as a set of ordered pairs and C is ... the exact same set of ordered pairs.  Of course, the cautious mathematician is loathe to say yes they are the same as topologies are not inherent in sets and we don't want to give the impression they are.
Comment: It is standard to consider the metric topologies on these spaces when no other topology is mentioned. Nevertheless I would recommend starting your post by stating that these are the topologies in question when posting on MSE, to avoid needless questioning.
Answer: The map $f:\mathbb C\to\mathbb R^2$ given by
$$f(x+iy)=(x,y)$$
is a homeomorphism.


How to know when to use $config or $settings overrides in settings.php?

Question: I want to be able to disable certain options of modules on non-production environments.
For example:

Disable XMLSitemap from running
Set "Read Only" mode for Search API indices to TRUE
Set robots.txt string to
User-agent: *
Disallow: /

How do you know whether you should override $config or $settings in settings.php?
Would it be:
$config['search_api.index.acquia_search_index']['readonly'] = TRUE;

or
$settings['search_api.index.acquia_search_index']['readonly'] = TRUE;

Also, how can you confirm if these overrides are working? Is there an admin overview page that lists these things?
Answer: From settings.php, regarding $settings:

Settings:
$settings contains environment-specific configuration, such as the files
directory and reverse proxy address, and temporary configuration, such as
security overrides.
@see \Drupal\Core\Site\Settings::get()

From settings.php regarding $config:

Configuration overrides.
To globally override specific configuration values for this site,
set them here. You usually don't need to use this feature. This is
useful in a configuration file for a vhost or directory, rather than
the default settings.php.
Note that any values you provide in these variable overrides will not be
viewable from the Drupal administration interface. The administration
interface displays the values stored in configuration so that you can stage
changes to other environments that don't have the overrides.
There are particular configuration values that are risky to override. For
example, overriding the list of installed modules in 'core.extension' is not
supported as module install or uninstall has not occurred. Other examples
include field storage configuration, because it has effects on database
structure, and 'core.menu.static_menu_link_overrides' since this is cached in
a way that is not config override aware. Also, note that changing
configuration values in settings.php will not fire any of the configuration
change events.
Comment: So if you "don't" need to use this feature, is there a section documenting config management strategy per environment?
Comment: I don't know of one, but that doesn't mean it doesn't exist.
Answer: The answer is $config. Module options are configuration and this is what you override in $config.
$settings is the name space for which settings.php is the primary source, so this is not an override.
The question how to tell whether the overrides are working is indeed pointing to a real problem. You can't see the overrides. The admin UI shows the original values and you can even edit and save them, while the overridden configuration is active in the background.
Answer: Your question is not clear, but dev and stage environnemnts have differents settings.php, so you can modify your config in each file as you like, $config contains all globals variables to drupal, and in same time are config variables in data base ...
Comment: Things that are common between environments should go into `settings.php` (and this can be committed to version control, assuming nothing in those settings should be kept private). Things that are unique, like database name, user, and pass, should go into a `settings.local.php` for each enviornment.


Are bimodules over a commutative ring always modules?

Question: Let $R$ be a commutative ring. It is true that every module over $R$ is an $(R,R)$-bimodule. Is the converse true? In other words is it possible that there is an $R$-module where left multiplication and right multiplication do not co-incide?
I thought perhaps a counterexample would be of the following form. If $S$ is an $R$-algebra, if we form the product $S \otimes_R S$ and think of it as an $S$-module where multiplication is given by $s(s' \otimes s'') = ss' \otimes s''$ and $(s' \otimes s'') s = s' \otimes s''s$. If we can pick the right element $s$ it is possible those two tensors are not equal. I cannot find any concrete counterexamples though. If you do this with $\mathbb{Q} \otimes_\mathbb{Z} \mathbb Q$ for example it doesn't work.
Thanks for any help.
Comment: Take $\mathbb{R} \otimes_\mathbb{Z} \mathbb{R}$ and let $\mathbb{R}$ act on each side separately.
Comment: You could also just take $\mathbb{C}$ with the following two module structures: One is given by multiplication and the other one is given by multiplication with the conjugate.
Comment: Even simpler: take a noncommutative ring $R$, and let $I$ be a left ideal which is not a right ideal.
Comment: I don't know either but it's a safe bet that if you're looking for a counterexample you're going to have to pick something less well-behaved than $\mathbb{Z}$ and $\mathbb{Q}$.
Comment: [Related question](http://math.stackexchange.com/questions/184931)
Comment: @MTurgeon I would like $R$ to be commutative if possible!
Comment: @ZhenLin What do you mean act seperately?
Comment: OK I see what you are saying now... it doesn't work with $\mathbb Q$ because the terms are just fractions but if we take an irrational number there is no way we can slide it through the $\otimes$.
Comment: This question is problematic. And why is the "combinatorics" tag included?
Comment: @rschwieb I've no idea. changed it to tensor products.
Answer: As Zhen Lin comments above, the converse is not true.  For another example, suppose $S$ is a ring containing $R$ as a commutative subring such that $R$ is not in the center of $S$.  Then $S$ is naturally an $(R,R)$-bimodule using the ring multiplication on $S$.  But if $R$ is not in the center of $S$ then there exists $r \in R$, $s \in S$ such that $rs \neq sr$.  So the left and right actions don't agree.
For a simple example, take $R$ to be the subring of diagonal matrices in the matrix ring $\mathbb{M}_n(k)$ for a field $k$ and $n \geq 2$.
Answer: Supplementing other answers and comments: first, I would argue against thinking that "left" and "right" have genuine content, but I would argue in favor of thinking of these as notational artifacts of our left-to-right writing system, etc. (I am reminded again of Herstein's advocacy of writing functions on the right of their arguments, at least in English.)
E.g., an $R,S$-bimodule's main property is that the $R$-action and $S$-action commute with each other, and that the order-of-multiplication in $S$ is "backward", so (in English, with left-to-right conventions) an $R,S$-bimodule is equivalently a ("left") $R\otimes S^{\rm opp}$-module, with the "opposite" ring.
It is true that sometimes the notational left and right are mnemonically helpful, but their content should not be over-estimated.
"Even" in looking at $Hom_?(M,N)$ with non-commutative $R$, $S,R$-bimodule $M$, and $R,T$-bimodule $N$, the "left/right" structures might better be called pre-composition and/or post-composition and such, refering to the more basic convention of order of composition of functions: those closest the argument are applied first. Luckily, the $M\otimes_R N$ structures are more directly correctly suggested by left-right conventions, but, still, can be converted to other expressions, as noted above.
Edit: forgot to emphasize that associativity is, or should, if done right, built into all these set-ups. So the $(rm)s=r(ms)$ principle ought not be something one is worrying about in the face of all the other issues.
Answer: A bit more complicated but modern example: let $A$ and $B$ be curved $A_\infty$ algebras or  differential graded curved algebras and $M$ be an $A$-$B$-$A_\infty$-bimodule (dg curved algebras appear naturally in Hochschild theory and theoretical physics).
It follows that $M$ is neither a left $A_\infty$-$A$-module nor a right $A_\infty$-$B$-module due to the inclusion of the curvatures in $A$ and $B$ in the $A_\infty$ module relations.
Even simpler, if $A$ is a dg curved algebra, then it is not a left dg $A$-module, a right dg $A$-module or a dg $A$-$A$-bimodule.
Answer: For a commutative ring $R$, it is not true that every $R$ module is a bimodule. (Are you possibly thinking that modules which are left and right $R$ modules are called "bimodules"? This is not the case...)
Mariano Suárez-Alvarez gave an example here: An $R$ module and $S$ module that cannot be an $R$-$S$ bimodule of a left $R$ right $S$ module that is not an $R-S$ bimodule. In his example he made his $R\neq S$, but I don't see why that is necessary, because he only used dimensionality in his arguments. So, I think you can replace $S$ in the example with another copy of $R$, and still have a counterexample.
It will also show that the left and right actions of $R$ are not the same.
Over any ring it is trivial that any $R-R$ bimodule is both a left module and a right module over $R$. It's just the restriction of the bimodule action to one side.

I misled myself with the first statement, and didn't see the simple claim you were making about $R$ modules. Yes, every $R$ module has the "naive" $R-R$ bimodule structure. Sorry for the distraction! I think the rest of my answer pertains to your question though! It produces separate module actions which do not commute.
Comment: They do! for a bimodule you need (rm)s = r(ms) which are both just equal to (rs)m for modules. Over a commutative ring. Just to remind you I am talking about commutative rings here
Comment: @PaulSlevin Aha, wait, now I see what you meant :) Adding to my answer. I should have seen what you meant earlier. (What I've written here isn't wrong though, by the way.)
Comment: Every module is an $(R,R)$-bimodule by definition of an $R$-module. There is no distinction between left and right multiplication in a module so you automatically get that it is a bimodule
Comment: @PaulSlevin Again, $R-R$ bimodule does not mean "Is a left and right $R$ module". There is an additional requirement that the two actions commute with each other. It may happen in a left-right $R$ module that $(rm)s\neq r(ms)$, and that would prevent it from being a bimodule.
Comment: @PaulSlevin I think there is some confusion of module operations here. There are two actions which we can write on the right side. Using different symbols for the actions, we need to show $(m\ast x)\cdot y=(m\cdot y)\ast x$. The rule $(m\cdot r)\cdot s$ doesn't cover that (right?!). Said another way: If $f:R\rightarrow End(M)$ and $g:R\rightarrow End(M)$ are the module actions, how do you prove that $Im(g)$ and $Im(f)$ commute with each other?


What is the probability of two dice getting a sum of 7 without a two?

Question: I am currently working on conditional probability and I am somewhat confused about how exactly to complete this problem. I know that to find conditional probability that you utilize:
$$P(A|B) = \frac{P(A\cap B)}{P(B)}$$
I also know that there is a $6/36$ chance to roll a sum of 7, and that if you roll a sum of 7 that there is a $4/6$ chance to get a sum without using the number 2. I do not know what else is necessary however in order to finish this problem and to find $P(A|B)$.
Comment: Why does it have to be conditional?  $7=6+1=1+6=3+4=4+3$  How many are there?
Comment: What do think A and B should be - what events?
Comment: Wouldn't it just be $1/9$?  I'm reading it as you can roll a seven using two fair die including 2's, you just are not looking for specifically 5+2 or 2+5 as part of your event.
Comment: @ampage, can you be a little more specific as to what you are looking for?
Comment: @Eleven-Eleven The question asks "A pair of dice are rolled. What is the probability that neither die shows a 2 given that they sum to 7? What is the probability that they sum to 7 given that neither die shows a 2?" It seems to me that the answer would be the same, however, I'm not sure why it would be asked inversely if that were the case.
Comment: Yes, but that's not what you wrote in the title.  In fact, it never says "given" any where in your title.  "What ist he probability of two dice getting a sum of 7 without a 2" is a deviation from the question you have above.   It just seemed unclear to me.
Answer: $B= \{1,3,4,5,6\}^2$.
$A= \{ (i,j) | i+j = 7, i, j \in \{1,2,3,4,5,6\} \}$.
Answer: The Event $E$of rolling two dice that sum to seven not including a sum with summand 2 would be
$$\{(1,6),(3,4),(4,3),(6,1)\}$$
Thus $|E|=4$.
Since the sample space has cardinality $36$, $P(E)=4/36=1/9$.
Answer:
I also know that there is a 6/36 chance to roll a sum of 7, and that if you
  roll
  a sum of 7 that there is a 4/6 chance to get a sum without using the number 2.

So, putting these statements into probability notation, you have,
$$
\begin{split}
P(x_1 + x_2 = 7) &= \frac{6}{36}\\
P(x_1\ne 2 \cap x_2 \ne 2 | x_1 + x_2 = 7) &= \:\frac{4}{6}
\end{split}
$$
So, what you want is $P(x_1 \ne 2 \cap x_2\ne 2  \cap x_1 + x_2 = 7)$ (i.e. the joint probability), so using the conditional probability definition:
$$
P(x_1\ne 2 \cap x_2 \ne 2 | x_1 + x_2 = 7)
= \frac{P(x_1 \ne 2 \cap x_2\ne 2 \cap x_1 + x_2 = 7)}{P(x_1 + x_2 = 7)}
\qquad
$$
and thus,
$$
P(x_1 \ne 2 \cap x_2\ne 2 \cap x_1 + x_2 = 7) = P(x_1\ne 2 \cap x_2 \ne 2 | x_1 + x_2 = 7){P(x_1 + x_2 = 7)}.
$$


Adding "301 Redirect" to a large number of files in IIS 6

Question: I am trying to create a permanent (301) redirect all the files in a directory to a single file within that directory.
For instance, if a user visits site.com/directory/randompage.html, I want them to be redirected to site.com/directory/index.html.
I have tried putting a redirect on the directory and then overriding the redirect on the file level, but IIS does not appear to allow this.
Is there a way to accomplish what I am after? or do I have to create a redirect on a file by file basis?
Comment: What version of IIS are you using?
Answer: For attempted access to files that don't exist you can put a custom 404 error on the directory that redirects the user to the URL for the file you'd like them to access.
If there are other files in that directory you'll have to put redirects on them on a file-for-file basis. That's just the way it is, unfortunately. If you have a lot of files you could script the metabase modification to add the redirect.
Edit:
If you can modify the NTFS ACLs on all those files to disallow the user from reading them, you could also drop a custom 401.3 error page on the directory, too.
If not, then try this:
<code>@echo off
SET SOURCE_DIR=C:\path-to-directory-in-filesystem
SET ADSUTIL=cscript C:\inetpub\adminscripts\adsutil.vbs
SET METABASE_PATH=W3SVC/####/ROOT/path/to/site/directory
SET REDIRECT_URL=/foo/foo.txt

for /f "usebackq delims=" %%i in (`dir /b %SOURCE_DIR%`) do (
 %ADSUTIL% CREATE %METABASE_PATH%/%%i
 %ADSUTIL% SET %METABASE_PATH%/%%i/KeyType "IIsWebFile"
 %ADSUTIL% SET %METABASE_PATH%/%%i/HttpRedirect "%REDIRECT_URL%, PERMANENT"
)
</code>
Set the SOURCE_DIR to the physical path in the filesystem of the directory with the files to be made into redirects. ADSUTIL is probably set right if you're a stock IIS 6 install. METABASE_PATH needs to refer to the site identifier number (### in the sample, get it from the IIS management console for your site) and the path under the root (leave /ROOT/ there-- that needed). Finally, REDIRECT_URL needs to be the URL (can be absolute or relative to the root of the site).
Comment: Thanks!  There are a few thousand files unfortunately.  Can you direct me to a decent resource for scripting the metabase modifications?
Comment: There-- have at.  >smile<
Answer: You should be able to employ a URL rewrite module to do this.  There are 2 that I know of for IIS6 and earlier, IIS7 has it's own module (finally).
You can have a look at Helicon's ISAPI_Rewrite or Ionics Isapi Rewrite (also works with IIS7).  I use Ionics' because it's free, but Helicon's rewrite rules I believe map directly with the mod_rewrite Apache module's rules which is a big win for it in general.
Both have the ability to provide permanent redirects and the rules are regular expression based.  I'll see if I can put together the syntax for a rule that would cover what you want to do and post it shortly.
Answer: Another option (just to have it out there), is you could tell IIS to let ASP.Net handle .html in that site, then create a global.asax file with Application_BeginRequest code that checks the URL and redirects accordingly.
Answer: All that metabase modification- thousands of files you say? You could do this with one wildcard rule in IIRF.
<code>RedirectRule ^/directoryToRedirect/(.*)(?<!index\.html)$  /index.html  [L]
</code>
In english, it says, for any URL in the directory directoryToRewrite, which is NOT index.html, redirect it to index.html .
This works regardless of how many files you have, whether you add new files, remove files, whatever.


Read object from JSON HTTP response

Question: How can I read the 'name' object from the response below:
{ '730':
   { success: true,
     data:
      { type: 'game',
        name: 'Counter-Strike: Global Offensive',
        steam_appid: 730,
        required_age: 0,
        is_free: true,
        controller_support: 'full',
        dlc: [Array],
        detailed_description:
         '
Вышло обновление

https://store.steampowered.com/app/1490530/CounterStrike_Global_Offensive__Operation_Broken_Fang/

Об игре
Counter-Strike: Global Offensive (CS: GO) возрождает ураганную командную игру, впервые представленную еще 19 лет назад.

CS: GO включает в себя новые карты, персонажей, оружие, игровые режимы, а также улучшенную версию классической составляющей CS (de_dust и т.п.).

«Counter-Strike была сюрпризом для игровой индустрии, когда не особо удачный мод стал одним из самых популярных шутеров в мире сразу же после его релиза в Августе 1999 года, — говорит Даг Ломбарди из Valve, — за прошедшие 12 лет, она все еще одна из самых популярных в мире игр, часто появляется на игровых соревнованиях и продана в количестве более 25 миллионов копий по всему миру. CS: GO обещает возродить знаменитый игровой процесс Counter-Strike и предложить его игрокам не только на ПК, но и на консолях следующего поколения и компьютерах Mac».',
        about_the_game:
         'Counter-Strike: Global Offensive (CS: GO) возрождает ураганную командную игру, впервые представленную еще 19 лет назад.
\r\n
\r\nCS: GO включает в себя новые карты, персонажей, оружие, игровые режимы, а также улучшенную версию классической составляющей CS (de_dust и т.п.).
\r\n
\r\n«Counter-Strike была сюрпризом для игровой индустрии, когда не особо удачный мод стал одним из самых популярных шутеров в мире сразу же после его релиза в Августе 1999 года, — говорит Даг Ломбарди из Valve, — за прошедшие 12 лет, она все еще одна из самых популярных в мире игр, часто появляется на игровых соревнованиях и продана в количестве более 25 миллионов копий по всему миру. CS: GO обещает возродить знаменитый игровой процесс Counter-Strike и предложить его игрокам не только на ПК, но и на консолях следующего поколения и компьютерах Mac».',
        short_description:
         'Counter-Strike: Global Offensive (CS: GO) возрождает ураганную командную игру, впервые представленную еще 19 лет назад. CS: GO включает в себя новые карты, персонажей, оружие, игровые режимы, а также улучшенную версию классической составляющей CS (de_dust и т.п.).',
        supported_languages:
         'чешский, датский, нидерландский, английский*, финский, французский, немецкий, венгерский, итальянский, японский, корейский, норвежский, польский, португальский, бр. португальский, румынский, русский, китайский (упр.), испанский, шведский, тайский, китайский (трад.), турецкий, болгарский, украинский, греческий, испанский Лат. Ам., вьетнамский
*озвучивание доступно на этих языках',
        header_image:
         'https://steamcdn-a.akamaihd.net/steam/apps/730/header.jpg?t=1607046958',
        website: 'http://blog.counter-strike.net/',
        pc_requirements: [Object],
        mac_requirements: [Object],
        linux_requirements: [Object],
        developers: [Array],
        publishers: [Array],
        packages: [Array],
        package_groups: [Array],
        platforms: [Object],
        metacritic: [Object],
        categories: [Array],
        genres: [Array],
        screenshots: [Array],
        movies: [Array],
        recommendations: [Object],
        achievements: [Object],
        release_date: [Object],
        support_info: [Object],
        background:
         'https://steamcdn-a.akamaihd.net/steam/apps/730/page_bg_generated_v6b.jpg?t=1607046958',
        content_descriptors: [Object] } } }

I'm not dev by any means so the question for someone might sound simple but it's quite complicated for my eyes :)
I appreciate your time.
Answer: As the property 730 is a number (which is an invalid property name when using dot-syntax), you'll have to use bracket-notation to access it. Then, just follow the nesting through data to name:
response['730'].data.name

Comment: Thank you, I was trying response.'730' but I need to get back to the basics it seems :)

Read object from JSON HTTP response


Como adicionar scroll em ion-tabs com varios tab?

Question: estou desenvolvendo uma app em ionic, com isso, tenho uma pagina com tabs, mas pretendo colocar 10 tabs e não vai caber nos dispositivos, como colocar um scroll horizontal para as tabs?

<code>  <ion-tab title="Home" icon-on="ion-ios-filing" icon-off="ion-ios-filing-outline">
   <!-- Tab 1 content -->
  </ion-tab>

  <ion-tab title="About" icon-on="ion-ios-clock" icon-off="ion-ios-clock-outline">
    <!-- Tab 2 content -->
  </ion-tab>
  <ion-tab title="About" icon-on="ion-ios-clock" icon-off="ion-ios-clock-outline">
    <!-- Tab 3 content -->
  </ion-tab>
  <ion-tab title="About" icon-on="ion-ios-clock" icon-off="ion-ios-clock-outline">
    <!-- Tab 4 content -->
  </ion-tab>
  <ion-tab title="About" icon-on="ion-ios-clock" icon-off="ion-ios-clock-outline">
    <!-- Tab 5 content -->
  </ion-tab>
  <ion-tab title="About" icon-on="ion-ios-clock" icon-off="ion-ios-clock-outline">
  </ion-tab>
</ion-tabs>
</code>
Answer: Ainda está com este problema? Consegui resolver hoje um parecido, no meu as tabs são dinâmicas, o usuário pode adicionar quantas quiser e excluir também.
Para resolver o problema adicionei um tamanho minimo para as tabs e adicionei scroll x da div que fica com as tabs.
<code>.tab-item{
    min-width: 90px;
}
.tabs{
    overflow-x: scroll;
    overflow-y: hidden;
}
</code>


Given that $\tan\left(x-y\right) = k$ and $\tan\left(x\right) = 1$, express $\tan\left(y\right)$ in terms of $k$

Question: Just looking for help on this particular question:
Given that $\tan (x - y) = k$ and $\tan(x) = 1$, express $\tan(y)$ in terms of $k$**
So far I've used the trig identity: $\tan(A±B) = (\tan(A)±\tan(B)) / (1 ∓ \tan(A)\tan(B))$
This got me to $(1-\tan(y))/(1+\tan(y))=k$, but I'm unsure where to go from here and struggle with solving these types of equations. From here, I tried to multiply the fraction by $(1-\tan(y))/(1-\tan(y))$, but this didn't help.
Thanks!
Toby.
Comment: Multiply by $1+\tan y$ on both sides, and solve for $\tan y$, it should be ok
Answer: Hint:
Use the identity:
$$\tan(x-y) =\frac{\tan x - \tan y}{1 + \tan x\tan y} = k$$
Now factorise $\tan y$ out
$$k + k \tan y = 1 - \tan y $$
$$ \tan y (k+1) = 1 - k$$
You can finish it off from here
Answer: Hint: Assuming your equation $$\frac{1-\tan y}{1 + \tan y} = k$$ is correct,
note that you can write
$$\frac{1-\tan y}{1 + \tan y} = \frac{2}{1 + \tan y}-1$$
Replace the LHS of your equation with this. You should see how to isolate $\tan y$ now.
Addendum: Completing since another answer has been accepted.
$$\frac{1-\tan y}{1 + \tan y} = k$$
$$\frac{2}{1 + \tan y}-1 = k\tag{rewrite LHS}$$
This is a very nice form because now "$\tan y$" appears in only one place. We can immediately solve for "$\tan y$":
$$\frac{2}{1 + \tan y}= 1+k\tag{add $1$}$$
$$\frac{1}{1 + \tan y} = \frac{1+k}{2}\tag{div. by $2$}$$
$$1 + \tan y = \frac{2}{1+k}\tag{invert}$$
$$\tan y = \frac{2}{1+k}-1\tag{subtr. $1$}$$
It may be a little nicer to combine these terms:
$$\tan y = \frac{1-k}{1+k}\tag{rewrite RHS}$$
To sum up, our first step put the equation in a nice form. It's nice because you can immediately see that the LHS was created from "$\tan y$" by successively performing the steps "add $1$, invert, multiply by $2$, subtract $1$". So we just need to undo these steps in reverse order on both sides to obtain "$\tan y$" on the LHS, and the RHS becomes whatever it becomes since it's along for the ride.
Addendum 2: The "trick" to nicing up the original form is to note that you can do this sort of thing:
$$\frac{a+b\;\boxed{X}}{c+d\;\boxed{X}}=\frac{a+\frac{b}{d}(dX)}{c+dX}=\frac{a -\frac{b}{d}(c)+\frac{b}{d}(c+dX)}{c+dX}$$
$$=\frac{\left(a -\frac{bc}{d}\right)}{c+d\;\boxed{X}} +\left(\frac{b}{d}\right)$$
All the stuff in parentheses is just some number, and now the "$X$" is by itself in one spot.
Comment: That's the "trick" I allude to above. Let's use "$t$" as shorthand for "$\tan y$". The denominator is $1+t$, so write the numerator as $$1-t=1-\overbrace{(1+t -1)}^{t} = 1-(1+t)+1=2-(1+t)$$ Then the fraction is $$\frac{2-(1+t)}{1+t}=\frac{2}{1+t} - \frac{1+t}{1+t}=\frac{2}{1+t}-1$$ The point is to end up with a constant multiple of denominator in the numerator, so it cancels leaving only a number. The rest of the numerator is also just a number. All of the "$t$" was written as a number plus some multiple of $1+t$ (the multiplier of $(1+t)$ is the original multiplier of $t$ in the numerator).
Comment: (continued) This is really just doing polynomial division $(1-t)\div (1+t)$, which you would write as $(-t + 1)\div (t+1)$. This gives a quotient of $-1$ with a remainder of $2$, that is, $-1 + \frac{2}{t+1}$. Maybe that's the easiest way to think of it.
Comment: In the second step, how did you get (1 − tan(y)) / (1 + tan(y)) = 2 / (1 + tan(y)) −1 ?


Logica de Distribuição Igualada

Question: Queria saber se alguém conhece algum algoritmo de distribuição igualada. Por exemplo eu tenho 10 espaços e tenho 4 a, 2 b, 3 c, 1 d. E tenho que distribuir essas variáveis dentro dessas 10 posições igualmente de modo que elas fiquem uniforme, sem haver repetições das variáveis.

Exemplo : (A-B-C-A-D-C-A-B-C-A)
Answer: Não conheço qualquer solução formal mas se eu fosse "inventar" uma faria o seguinte.
Use um contador para sua lista de variáveis.
Faça um looping na lista, inserindo cada variável na sequeência e subtraindo o contador.
Mas dai acabamos com
A,B,C,D, A,B,C, A,C, A

para seu exemplo.
Porém se tivermos mais A ficaremos com "pares" de A na "cauda".
Para evitar isso você pode checar se a variável anterior é igual à variável sendo inserida.
Se sim, volte para o início da sequência e tente inserir na posição se e somente sim os vizinhos são diferentes.
No caso de termos 11 posições e mais um A a sequência ficaria assim:
A,B, A ,C,D, A,B,C, A,C A

Você pode tentar is inserindo randomicamente na sequência também mas de qualquer forma algo que vejo como problematico nesse tipo de algoritmo é a "parada", saber quando desistir. Por exemplo se você so recebe A não há como fugir de ter A,A,A,A,A...
Edit
Pensando numa maneira puramente randômica:
Para cada variável atribua uma probabilidade dela ser inserida, de início igual à sua distribuição (no exemplo A tem 40% de chance de ser inserido e D 10%).
Tente inserir uma variável randomicamente conforme sua probabilidade, verifique os vizinhos para saber se é possível. Caso seja insira e ajuste a probabilidade (se eu inserir o primeiro como A a probabilidade de próximo muda de 4/10 para 3/9). Caso não seja possível inserir, atribua zero possibilidade para àquela variável e continue. Caso todas as variáveis fiquem "zeradas" verifique se em algum ponto da sequência você um "split" resolve.
O problema não tem solução se houver mais de 50% de um variável. No caso das 10 posições é impossível não haver um par AA se houverem ao menos 6/10 de A.
A,X,A,X,A,X,A,X,A,A

Comment: A condição de parada poderia ser sem posição possível.
Answer: Esse problema me lembra o problema de coloração de grafos, no qual que você tem que colorir um número k de vértices usando um numero n de cores, e vértices vizinhos não podem ter as mesmas cores.
Não saberia dar uma solução de cara, mas tente estudar um pouco a respeito desse algoritmo que com certeza você vai achar uma maneira de resolver seu problema: http://en.wikipedia.org/wiki/Graph_coloring
Comment: Parecido mas o algoritmo de coloração de grafos sempre tem solução. Esse parece mais com o problema da "discrepância de distribuição"
Comment: Acho que nem sempre o problema de coloração de grafos tem solução. Pense num caso em que temos apenas três vértices e duas cores – não existe solução. No problema do autor da pergunta, também é possível chegar num caso sem solução, a meu ver
Comment: Sim, pensei no problema de coloração de mapas, que sempre tem solução com pelo menos três cores. No caso dos vértices acho que tem sempre solução quando cores > arestas
Answer: Eu vejo uma solução com Permutação Simples em Análise Combinatória.
Primeiro devemos obter a combinação dos elementos, no exemplo: A1, A2, A3, A4, B1, B2, C1, C2, C3, D1. Depois basta eliminar os que possuem letras iguais adjacentes.
Bem, a permutação tem ordem fatorial O(n!) (sendo n o número de elementos) e 10! do exemplo iria gerar 3.628.800 de possibilidades.
Entretanto, podemos otimizar o algoritmo gerando apenas as combinações que importam, de duas formas:

Ignorando uma combinação (e todas as combinações derivadas) se a próxima letra repete a atual. Por exemplo, se estamos montando uma combinação e temos A, iremos pular a combinação AA e todas as derivações dela (AAB, AAC, ...).
Ignorando as iterações com letras repetidas. Apesar de termos 4 letras A, não precisamos testar as combinações começando com todas elas. Somente precisamos testar um elemento correspondente a cada letra.

Pra falar a verdade eu não sei fazer a análise da ordem de complexidade dessa otimização, mas o que posso dizer é que quanto mais itens repetidos houverem, menos possibilidades serão testadas e mais rápido obteremos o resultado.
Sendo m a quantidade letras (ignorando a repetição) e n o número total de elementos (contando os repetidos), podemos dizer que, no pior caso, se tivermos um elemento de cada letra (m == n), o algoritmo será efetivamente O(n!). Porém, se tivermos repetição (m < n), a complexidade será maior que O(m!) e menor que O(n!).
Fiz a seguinte implementação em Java:
public class Distribuicao {

    private List<String> combinacoes = new ArrayList<String>();
    private List<String> becos = new ArrayList<String>();
    private long combinacoesTestadas = 0;

    /**
     * Começa pegando as letras uma a uma e combinando o restante.
     * Note que assim já não precisamos verificar as combinações repetidas,
     * já que usamos a chave única do mapa.
     */
    public Distribuicao(HashMap<Character, Integer> itens) {
        for (Entry<Character, Integer> e : itens.entrySet()) {
            trocarECombinar(itens, e, "");
        }
    }

    /**
     * Procura novas combinações, ignorando se repetir a letras
     */
    private void combinar(HashMap<Character, Integer> itens, String prefixo) {
        Character ultimo = prefixo.charAt(prefixo.length() - 1);
        boolean itensSobrando = false;
        boolean encontrouNovaPossibilidade = false;
        //verifica cada letra, sem repetir
        for (Entry<Character, Integer> e : itens.entrySet()) {
            //verifica se ainda há um elemento disponível da letra
            if (e.getValue() > 0) {
                itensSobrando = true;
                //verifica se é igual à anterior
                if (!e.getKey().equals(ultimo)) {
                    encontrouNovaPossibilidade = true;
                    //tenta uma nova combinação com a letra atual
                    trocarECombinar(itens, e, prefixo);
                }
            }
        }
        if (!itensSobrando) {
            combinacoesTestadas++;
            combinacoes.add(prefixo);
        } else if (!encontrouNovaPossibilidade) {
            combinacoesTestadas++;
            becos.add("[prefixo = " + prefixo + ", resto = " + itens + "]");
        }
    }

    /**
     * Decrementa a letra usada, acrescenta a atual no prefixo
     * e tenta recursivamente uma nova combinação
     */
    private void trocarECombinar(
            HashMap<Character, Integer> itens,
            Entry<Character, Integer> e,
            String prefixo) {
        e.setValue(e.getValue() - 1);
        combinar(itens, prefixo + e.getKey().toString());
        e.setValue(e.getValue() + 1);
    }

    public List<String> getCombinacoes() {
        return combinacoes;
    }

    public List<String> getBecos() {
        return becos;
    }

    public long getCombinacoesTestadas() {
        return combinacoesTestadas;
    }

    public static void main(String[] args) {

        //prepara o mapa de teste
        HashMap<Character, Integer> mapa = new HashMap<Character, Integer>();
        mapa.put('A', 4);
        mapa.put('B', 2);
        mapa.put('C', 3);
        mapa.put('D', 1);

        //executa a distribuição
        Distribuicao d = new Distribuicao(mapa);

        //quantidade de combinações testadas
        System.out.println("Combinações testadas: " + d.getCombinacoesTestadas());

        //combinações encontradas
        System.out.println("Combinações encontradas: " + d.getCombinacoes().size());
        for (String combinacao : d.getCombinacoes()) {
            System.out.println("  -> " + combinacao);
        }

        //combinações onde não houve como continuar
        System.out.println("Becos sem saída: " + d.getBecos().size());
        for (String beco : d.getBecos()) {
            System.out.println("  -> " + beco);
        }

    }

}

No exemplo, temos n = 10 e m = 4. Isso é consistente com o retorno do algoritmo:

1074 combinações
462 "becos sem saída", isto é, situações onde não havia letras disponíveis para continuar e o processo foi interrompido

Logica de Distribuição Igualada


ubuntu + hhvm results in my tmpfs is full - 100% used

Question: Ubuntu 14.04, HHVM 3.10.1
Running df -h I can see the following:
Filesystem      Size  Used Avail Use% Mounted on
udev            7.9G  8.0K  7.9G   1% /dev
tmpfs           1.6G  1.6G  8.0K 100% /run
/dev/xvda1      9.8G  2.1G  7.2G  23% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
none            5.0M     0  5.0M   0% /run/lock
none            7.9G     0  7.9G   0% /run/shm
none            100M     0  100M   0% /run/user

What's taking up the full space in tmpfs is actually the file /run/hhvm/hhvm.hhbc which is 1.6 GB currently. Is this healthy? It does not look like it is.
I have found the following, related to the full tmpfs:
https://github.com/hhvm/packaging/issues/132

"On my Ubuntu (14.04) /var/run is a tmpfs mount that's only 400MB in
  size. The hhvm.hhbc file grew to a little over 350MB on one system. I
  think it may make more sense to default to putting this file under
  /var/cache/hhvm instead."

My central path is just as explained, defined to /var/run/hhvm/hhvm.hhbc - but i do not have a /var/cache/ in my filesystem, so i wonder if i really should change the central path to /var/cache/hhvm instead? Also, wouldn't this be bad / not be temporary since tmpfs is mounted to only /run?
I am debugging since my HHVM is crashing periodically, which requires that i run a reboot of hhvm service/remove the hhvm.hhbc before everything works again.
Answer: The hhvm.hhbc file is the hiphop compiled bytecode. From the looks of it, it's getting too big for your tmpfs. You can either change the path to somewhere on /dev/xvda1, or increase the size of your tmpfs partition (if your memory allows for it)
Using the tmpfs path is fast, since the compiled code repo will be read from memory, setting it to an actual on disk file system will slow down the reads.
Comment: What causes the hhvm.hhbc to get bigger and bigger? Seems like there is no limit. If it will stop somewhere in size, how will i determine this size without going to increase > crash > increase > crash to find out the size. Also how can i increase the tmpfs partition? isn't it automatically set


Cloudkit dashboard unexpected server error

Question: When I want to use Cloudkit, I found that I can't manage the data by Cloudkit dashboard. The page tips me a message "Unexpected server error". How can I solve this problem? Here shows this error screenshot.

[Update]
Full error log:

ERROR TITLE Unexpected server error.
IS FATAL true
TYPE server
APPLICATION NAME Dashboard
BUILD NUMBER 15BDev63
TIME Tue Mar 24 2015 08:43:06 GMT+0100 (CET) (1427182986565)
HOST icloud.developer.apple.com
USER AGENT Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2)
  AppleWebKit/600.4.10 (KHTML, like Gecko) Version/8.0.4 Safari/600.4.10
ENVIRONMENT unknown
RECENT LOG MESSAGES Tue, 24 Mar 2015 07:43:06 GMT: INFO: --> Request
  1: GET to
  https://ckdashboardws.icloud.apple.com/bootstrap?request_uuid=e7516168-dcfe-4ed5-aa17-dc3a5a97ffb6,
  headers: Content-Type=text/plain, body: (empty) <-- Response 1: 500
  (294ms), headers: Cache-Control=no-cache, no-store, private,
  Content-Type=application/json; charset=UTF-8,
  X-Apple-Request-UUID=f05681b8-1f1c-4af5-a534-5f6531c5a463 body:
  {"errorReason":"Internal Server
  Error","errorCode":500,"requestUUID":"f05681b8-1f1c-4af5-a534-5f6531c5a463"}
  Tue, 24 Mar 2015 07:43:06 GMT: DEBUG: CloudKit: ErrorCatcher dialog
  invoked. Tue, 24 Mar 2015 07:43:06 GMT: DEBUG: SC.Module: Attempting
  to load 'cloudkit/error_catcher' Tue, 24 Mar 2015 07:43:06 GMT: DEBUG:
  SC.Module: Module 'cloudkit/error_catcher' is not loaded, loading now.
  Tue, 24 Mar 2015 07:43:06 GMT: DEBUG: SC.Module: Loading CSS file in
  'cloudkit/error_catcher' ->
  '/applications/dashboard/15BDev63/cloudkit/error_catcher/15BDev63/en-us/stylesheet.css'
  Tue, 24 Mar 2015 07:43:06 GMT: DEBUG: SC.Module: Loading JavaScript
  file in 'cloudkit/error_catcher' ->
  '/applications/dashboard/15BDev63/cloudkit/error_catcher/15BDev63/en-us/javascript.js'
  Tue, 24 Mar 2015 07:43:06 GMT: DEBUG: SC.Module: Module
  'cloudkit/error_catcher' finished loading. Tue, 24 Mar 2015 07:43:06
  GMT: DEBUG: SC.Module: Evaluating and invoking callbacks for
  'cloudkit/error_catcher'. Tue, 24 Mar 2015 07:43:06 GMT: DEBUG:
  SC.Module: Module 'cloudkit/error_catcher' has completed loading,
  invoking callbacks.
Comment: My issue was fixed. For any others that come across this, try logging into iCloud on a hardware device (not the simulator) with your Apple Developer ID account, you can also try to verify the account (though I had already verified it, it was the logging into the hardware that fixed the issue for me).
Comment: I started getting this issue, have raised it in the dev forums: https://devforums.apple.com/thread/266093?tstart=0 and also filed a bug: http://openradar.appspot.com/20272273
Comment: My problem may stem from the fact that when logging in to the iPhone Simulator (Settings > iCloud), I used my Apple Developer accounts Apple ID. This may have messed things up on the backend that now causes the problem when trying to log into the CloudKit Dashboard.
Comment: The comment above from RogeSoft was extremely helpful when I encountered this today.
Answer: you should be able to just manage your CloudKit data. There have been incompatible changes to the CloudKit containers during the beta's. Is your container created during the beta phase? If you keep having this problem and don't have valuable data in your container, then try resetting it. Click on Deployment and then on Reset development environment
Comment: I afraid that I still have this problem. An alert box popup when I enter cloudkit dashboard. Because of that I cann't do any operation.
Comment: @amergin - ok, interesting to know you switched, am going to keep slogging away with CloudKit/iCloud for now.
Comment: Maybe you could try setting up a new container. If you still have a problem, then I think the only option left is contacting Apple.
Comment: Just to add to this. I got the same issue, unable to access a container. Tried resetting the developer environment in Deployment to no avail. Had to just create and use a new container. Tried contacting Apple but no reply.
Comment: @RIs - sort of got it working by creating a new container but gave up on iCloud. Just using Dropbox now in my app.
Answer: For my case the Apple ID associated with my developer account was not activated for iCloud.  You can determine if it is or isn't by going to https://www.icloud.com and trying to sign in with your developer Apple ID.  If you can't then you won't be able to sign in to the dashboard either.
What I ended up doing was going to My Apple ID (https://appleid.apple.com/) and reverifying my Apple ID address.  Once this was completed I was able to login to both www.icloud.com and the iCloud CloudKit dashboard.
Answer: I just had this problem and looked everywhere for a solution, but had no luck.
Finally, I realised that this started happening immediately after I added a record to the iCloud (CloudKit) database from one of my devices, so I thought deleting all records might work.
This wasn't too easy as I, like you, couldn't log into the dashboard, however I ran the following code snippet in my application for each entity in my database, and that fixed the problem.
func applicationDidFinishLaunching(_ application: UIApplication) {
    let publicDatabase = CKContainer.default().publicCloudDatabase

    let allRecordsQuery = CKQuery(recordType: "ENTITY", predicate: NSPredicate(format: "TRUEPREDICATE", []))

    publicDatabase.perform(allRecordsQuery, inZoneWith: nil) { (records, error) in
        for record in records! {
            publicDatabase.delete(withRecordID: record.recordID, completionHandler: { (deletedRecord, error) in
                if error == nil {
                    print("Deleted " + (deletedRecord?.recordName)!)
                } else {
                    print(error!)
                }
            })
        }
    }
}

Replace "ENTITY" with every type of record in your database and run again.
So if you have just two entities: Pet and Task, first set "ENTITY" to "Pet" and run the application. Then set the "ENTITY" to "Task" and run the application again.
I realise that your question was asked a while ago, but this bug clearly still hasn't been fixed and so I hope my solution helps anybody else who has this problem.
Answer: I was getting this same error message yesterday when trying to access the CloudKit Dashboard. I had previously accessed it with no problem.  After trying several of the above suggestions with no luck, I called Apple.  Apparently it was a system wide problem.  That allowed me to stop messing up my code looking for the problem and just move on to another task. So, if nothing else seems to be working, that might be worth checking.


Complex numbers, absolute value

Question: How can i solve this equation: $ |z+i|=|z-1| $ I have tried$z=x+iy$, $|z|=\sqrt{x^2+y^2}$, $ z=re^{i\theta}$, comparing left and right side, nothing works. I cant come up with the correct answer. Would love some help
Comment: A much easier approach is to note you are looking for all the points equidistant from $-i$ and $1$.
Answer: As pointed out by other users, we can solve this geometrically (they haven't explained how to do so).
You look for all $z$ such that $z$ is equidistant from $-i$ and $1$. As any complex $z$ can be seen as an ordered pair of reals $(\text{Re}(z),\text{Im}(z))$, you may equivalently consider the problem in $\mathbb{R}^{2}$ equipped with the euclidean distance, that is:
$$d\left((x_{1},y_{1})\,,\,(x_{2},y_{2})\right)=\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2}^{2})}$$
And you can see that this distance is the modulus of the complex $(x_{1}-x_{2})+(y_{1}-y_{2})\text{i}$, which is $|z-(x_{2}+y_{2}\text{i})|$ for $z=x_{1}+y_{1}\text{i}$.
You look for all points of $\mathbb{R}^{2}$ equidistant from $(0,-1)$ (which represents the complex $-i$) and $(1,0)$ (which represents the complex $1$).
But the set of points in a plane equidistant from two distinct points is the perpendicular bisector of the line segment determined by these points: in this case, the perpendicular bisector is $y=-x$, wich corresponds to $\text{Re}(z)=-\text{Im}(z)$, namely the set of complex numbers $\{a-a\text{i}\mid a\in\mathbb{R}\}$.
Answer: Your first approach should work. Let $z=x+iy$ so:
$$|x+iy+i|=|x+iy-1|$$
$$\sqrt{x^2+(y+1)^2}=\sqrt{(x-1)^2+y^2}$$
$$x^2+y^2+2y+1=x^2-2x+1+y^2$$
$$2y=-2x$$
$$y=-x$$
So a diagonal line through the origin with slope $-1$.
Answer: Yet another solution is to use the definition of the field norm as $ |z| = \sqrt{N(z)} = \sqrt{z \cdot \bar{z}} $ where $ \bar{z} $ denotes the complex conjugate of $ z $. Squaring both sides, our equation reads
$$ (z + i)(\bar{z} - i) = (z-1)(\bar{z} - 1) $$
$$ z\bar{z} - iz + i\bar{z} + 1 = z \bar{z} - z - \bar{z} + 1 $$
$$ (i+1) \bar{z} = (i-1) z $$
$$ -2\bar{z} = -2i z $$
from which it follows that we are looking at the set of points such that $ \bar{z} = iz $, so conjugation corresponds to a counterclockwise rotation of $ \pi/2 $ radians. This implies that $ \arg(z) = 3\pi/4, 7\pi/4 $ and we are looking at the line $ \Im(z) = -\Re(z) $.
Answer: $z = x + iy$ works fine. If we plug it into the equation and simplify, we get, $x+y = 0$. So $x = -y$ or we can choose our parametric point as $(p, -p)$. We can verify it by pluging it back into the given equation.

Complex numbers, absolute value


How to preserve arguments after calling a function in POSIX

Question: In order to reuse some code and fragment my script I have a function to check some conditions and add arguments to script execution. However, after the function finish the arguments set there are not preserved.
Here is a simplify example of my intention:
#!/usr/bin/env sh

TARGET_FILE="${ENV}.env"

addEnvFile() {
    if [ -f "$TARGET_FILE" ]; then
        set -- "-env=${TARGET_FILE}"
        echo "ARGUMENTS: $*"
    fi
}

sampleFn() {
    # I need the arguments set in the "addEnvFile" function
    echo "CURRENT ARGUMENTS: $*"
}

addEnvFile
sampleFn "$*"

My goal is to have the argument from "addEnvFile" function (-env=dev.env) available to execute commands inside the sampleFn
Comment: `set --` inside a function will modify its own arguments, not the caller's ones.
Comment: yes, that's also my understanding, and that's why I'm asking "how" to do it, maybe there is some other workaround
Comment: Well, the work-around would be to just use `[ -f "$TARGET_FILE" ] && set -- "-env=${TARGET_FILE}"` in the main script, then call `sampleFn "$@"`
Answer: You can have addEnvFile() just echo the args and call it with set -- $(addEnvFile):
#!/usr/bin/env sh

TARGET_FILE="${ENV}.env"

addEnvFile() {
    if [ -f "$TARGET_FILE" ]; then
        echo "-env=${TARGET_FILE}"
    fi
}

sampleFn() {
    # I need the arguments set in the "addEnvFile" function
    echo "CURRENT ARGUMENTS: $@"
}

set -- $(addEnvFile)
sampleFn "$@"

$ file dev.env
dev.env: empty
$ ENV=dev ./args.sh
CURRENT ARGUMENTS: -env=dev.env

Note that I also changed "$*" to "$@", so that it works correctly if you have multiple arguments.
Comment: thanks! that's actually an interesting workaround!