Codigo VBA para deletar linha

Question: Galera, eu tenho um código que verifica a linha se há a palavra ou frase e deleta a linha:
If Mid(Cells(i, 10), 1, 50) <> "Defeito" Then Rows(i).Delete Shift:=xlUp

Porém eu na planilha há frases como "Defeito + banda larga" ou "Defeito tv", gostaria de que o código sempre que verificar que há alguma palavra na frase diferente de "Defeito", por exemplo,"instalação de modem" ou "refeição", ele delete a linha mas deixe as linhas que conter a palavra "Defeito" dentro da frase.
Comment: Coloca um exemplo do dados na tabela, pode ser uma captura de tela
Comment: https://imgur.com/a/6uFqEh2
Comment: é esse ai em cima
Comment: no exmplo acima está deletando tudo que for diferente dquela frase, porém eu gostaria que deletasse somente as linhas em que não houver a palavra "Defeito"
Answer: Consigo pensar em três modos de realizar esta ação:

Funções Excel para manipulação de String InStr() e Len()
Wildcards
Regex

E maneiras diferentes, algumas mais otimizadas para deletar
Funções Excel
Um loop normal em cada linha em que dois fatores são verificados na string.
InStr
Primeiro se ela contém a palavra "Defeito" com a função InStr() e o código InStr(1, ws.Cells(i, 10), "Defeito", 1), que retorna 0 se não houver a palavra e diferente de 0 se houver.
Len
Depois a função Len(), que verifica o comprimento da String, como a palavra defeito sozinha possui 7 caracteres. Então é verificado se o comprimento é maior do que 7 caracteres.
Loop para apagar
Por último se houver a palavra Defeito e se a String for maior do que 7 caracteres, um loop é realizado de trás para frente para deletar cada linha. Este é um processo lento, que para mais do que 10 000 linhas levaria algum tempo.
Dim UltimaLinha As Long, i As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Planilha1")
UltimaLinha = ws.Cells(ws.Rows.Count, "J").End(xlUp).Row
For i = UltimaLinha To 2 Step -1
    If InStr(1, ws.Cells(i, 10), "Defeito", 1) <> 0 And Len(ws.Cells(i, 10)) > 7 Then Rows(i).Delete Shift:=xlUp
Next i

WildCard
Duas maneiras de deletar com WildCard:

Match
AutoFiltro

Match
A Função do Excel Match() é usada junto com WildCard e deletada por loop.
Dim UltimaLinha As Long, i As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Planilha1")
UltimaLinha = ws.Cells(ws.Rows.Count, "J").End(xlUp).Row
For i = UltimaLinha To 2 Step -1
     If Not IsError(Application.Match("Defeito " & "*", ws.Range("J" & i), 0)) Then Rows(i).Delete Shift:=xlUp
Next i

Autofiltro
Dim UltimaLinha As Long, i As Long
Dim ws As Worksheet
Dim RangeFiltrar As Range, RangeVisivel As Range
Set ws = ThisWorkbook.Sheets("Planilha1")
UltimaLinha = ws.Cells(ws.Rows.Count, "J").End(xlUp).Row
With ws
    'Mostra os dados filtrados
    If .FilterMode Then
        .ShowAllData
    End If
    Set RangeFiltrar = .Range(.Cells(1, 10), .Cells(UltimaLinha, "J"))
    RangeFiltrar.AutoFilter Field:=1, Criteria1:="Defeito " & "*", Operator:=xlFilterValues
End With

On Error Resume Next
Set RangeVisivel = ws.Range(ws.Cells(2, 10), ws.Cells(UltimaLinha, "J")).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not RangeVisivel Is Nothing Then
    RangeVisivel.EntireRow.Delete
End If

If ws.FilterMode Then
    ws.ShowAllData
End If

É usado o Autofiltro com wildcard e depois as linhas visíveis são deletadas, este método é mais rápido do que um loop linha por linha.
Regex
As Expressões regulares podem ser usadas, em que um demo no Regex101 pode ser visto e a expressão: Defeito.+
Habilitar o Regex no Excel

RegEx precisa ser habilitado, Habilite o modo Desenvolvedor
Na aba 'Desenvolvedor', clique em 'Visual Basic' e a janela do VBA irá abrir.
Vá em 'Ferramentas' -> 'Referências...' e uma janela abrirá.
Procure por 'Microsoft VBScript Regular Expressions 5.5', como na imagem abaixo. E habilite esta opção.

Código
Neste código a célula é validada por Regex e depois uma Range não contígua é criada e no fim a range inteira deletada.
Este método é mais rápido por realizar a ação de apagar de uma vez só, do que realizar o loop um por um.
Dim UltimaLinha As Long, j As Long
Dim ws As Worksheet
Dim Dados()
Dim strData As String
Dim rng As Range, nova_rng As Range
Set ws = ThisWorkbook.Sheets("Planilha1")
UltimaLinha = ws.Cells(ws.Rows.Count, "J").End(xlUp).Row
'Preenche dados na Matriz Dados

With ws
    Dados = .Range("J1:J" & UltimaLinha).Value2
    Dim objMatches As Object, objRegExp As Object
    Set objRegExp = CreateObject("VBScript.RegExp")
    'Regex
    objRegExp.Pattern = "Defeito.+"
    objRegExp.Global = True
    'Executa Regex
    For j = LBound(Dados) To UBound(Dados)
        strData = Dados(j, 1)
        Set objMatches = objRegExp.Execute(strData)
        If objMatches.Count <> 0 Then
            For Each m In objMatches
                'Realiza ação para cada combinação encontrada
                'Debug.Print strData
                If rng Is Nothing Then Set rng = .Range("J" & j) 'Define o primeiro item da range para não ocorrer erro na função Union
                Set nova_rng = .Range("J" & j)
                Set rng = Union(rng, nova_rng) 'Cria a range não contígua para deletar
            Next m
        End If
    Next j
End With
rng.EntireRow.Delete

Nota:

Apagar/Deletar dados é muito sensível e complicado, pois eles podem ser perdidos para sempre. Sugiro realizar um backup dos dados antigos e criar uma cópia da planilha/dados para testes.
Comment: Somente atualizar para a planilha em que estão os dados utilizados
Comment: Cara na boa, voce é um gênio. o.O
Comment: Para outras maneiras de procurar uma String, ver [esta resposta](https://pt.stackoverflow.com/a/272169/75104)
Comment: Só deu uma duvida, na Set ws = ThisWorkbook.Sheets("Planilha1") eu coloco o nome da minha planilha?
Comment: @typemark isso mesmo, o padrão quando um novo arquivo é criado é Planilha1, por isso uso de exemplo.
Comment: tendi, na mesma linha do codigo, termina em "invalido fora de um procedimento", será que precisa alterar todos os nomes na planilha?  Ou cria-la do zero?

Codigo VBA para deletar linha


Show that $G\neq\bigcup_{g\in G}gHg^{-1}$ for any $H\subsetneq G$

Question: I want to show that for some proper subgroup $H\subsetneq G$ ($G$ finite) we always have $$G\neq\bigcup_{g\in G}gHg^{-1}$$
My attempt so far is letting $G$ act on the set $M$ of its subgroups of order $|H|$ by conjugation: $$\begin{matrix}G.M\end{matrix}\to M\\g.H\mapsto H^g$$
The stabilizer $G_H$ obviously then contains $H$, so $G.H$ is not empty and therefor we have that $|G.H|$ is a non trivial divisor of $|G|$. How do I continue from here?
Answer: HINT: Prove that there are exacty $[G:N[H]] \le [G:H]$ distinct subsets on the right. If the equality holds the intersection of any two must be an empty set. However the identity is in all of them.

$$gHg^{-1} = kHk^{-1} \iff (k^{-1}g)H(g^{-1}k) = H \iff k^{-1}g \in N[H] \iff gN[H] = kN[H]$$ This helps you conclude that the number of distinct subsets $gHg^{-1}$ as $g$ runs through $G$ is same as the number of distinct cosets of $N[H]$. Finally use the fact $H \le N[H]$
Comment: You probably mean that by applying Lagrange's theorem twice to $H\subset N(H)\subset G$ we have that $[G:H]=[G:N(H)]\cdot[N(H):H]$
Comment: @Buh Yeah, that will work
Comment: But then I don't really understand why I would need the identity to get the contradiction. Don't we just have that $|\bigcup_{g\in G}gHg^{-1}|=[G:N(H)]$ by your argument in the hidden box where $[G:N(H)]\neq |G|$?
Comment: You have $[G:N(H)]$ sets on the right with size |H|. On the other side G can be written as $[G:H]$ sets of size |H| by cosets. If the equality holds then the distinct sets on the right has to have empty intersection.
Comment: Alright, thanks!


Can I load a picture into mySQL server-side?

Question: I need to create a simple mySQL database with a field for an image.
Is there a simple example that explains the type of field and how to upload from a directory on the server, etc...?
Thanks.
Erik
Answer: There are two ways (at least) to store images in a database:-

Store a reference to a file on the filesystem
Store them as binary data inside the database

Binary data stored inside databases are known as BLOBS (binary large objects), you can read up more here:-
http://dev.mysql.com/doc/refman/5.0/en/blob.html
Answer: You can use LOAD_FILE function to returns the file contents as a string, e.g. -
INSERT INTO table_name VALUES (LOAD_FILE('img.png'));

Answer: Here is a basic example of BLOB Storage:
CREATE TABLE IF NOT EXISTS `files` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `filename` varchar(255) DEFAULT NULL,
  `ext` varchar(5) DEFAULT NULL,
  `filedata` blob,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;

<?php
$db = mysql_connect('localhost', 'user', 'pass') or die('Could not connect:' . mysql_error());
mysql_select_db('the_database',$db);

if(isset($_FILES['upload'])){

    if (is_uploaded_file($_FILES['upload']['tmp_name'])) {
        $file_parts = pathinfo($_FILES['upload']['name']);

        $file['name'] =$file_parts['filename'];
        $file['ext']  =$file_parts['extension'];
        $file['data'] =addslashes(file_get_contents($_FILES['upload']['tmp_name']));

        mysql_query('INSERT into files (id,filename,ext,filedata) values ("","'.$file['name'].'","'.$file['ext'].'","'.$file['data'].'")',$db) or die(mysql_error());
        $notice="File Uploaded successfully";
    }
}
?>

<title>BLOB Upload</title>

<form method="POST" enctype="multipart/form-data" action="">

BLOB Upload

<input type="file" name="upload" size="40">

<input type="submit" value="Upload">

  <?php if(isset($notice)){echo '
'.$notice.'
';}?>
</form>

Answer: Place the images in folders using fwrite or php GD libary.
Then save the image path in database, possible along with additional information such as size,width,height,name etc to be able to filter/sort them.


Add a Padding inside Children in Flutter

Question: I've a gridview that contains some images.
but you know, it's so close each other and I want give them a space one of other.
but I still cant make them .
I've try to make some experiments.
but it still give me nothing.
the problem is the padding is inside the gridview.
if i put them (all items) in 1 container, 1 container, 1 container etc, there are a lot of container inside the gridview.
`Container(
            margin: new EdgeInsets.all(2.0),
            color: Colors.red,
            padding: EdgeInsets.all(10.0),
            child: GridView.count(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              crossAxisCount: 6,
              children: <Widget>[
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
                Image.asset('images/user.png', width: 30.0),
              ],
            ),
          ),

here the preview: https://i.stack.imgur.com/W0RS5.jpg`
Answer: for the space to each other in gridview set the mainAxisSpacing & crossAxisSpacing properties of gridview ,
GridView.count(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          crossAxisCount: 6,
          mainAxisSpacing: 8.0,
          crossAxisSpacing: 8.0,
          children: <Widget>[
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
            Image.asset('images/user.png', width: 30.0),
          ],
        ),

Comment: thank you so much for your answer. its work for me.
very helpful answer. god bless you thanks :)
Answer: You can add SizedBox between children.
SizedBox(
  width: 200.0,
  height: 300.0,
)

Your code can be edited into
Container(
    margin: new EdgeInsets.all(2.0),
    color: Colors.red,
    padding: EdgeInsets.all(10.0),
    child: GridView.count(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      crossAxisCount: 6,
      children: <Widget>[
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
        SizedBox(width: 10,height: 10,),
        Image.asset('images/user.png', width: 30.0),
      ],
    ),
  ),

Comment: and this answer work for me too. how can I dont think like that. hehe

once again thank you so much. god bless you ::)


How to group row updates based on column values?

Question: I have a table like this
+------------------------------+
| Name,Class,Value,Class_Total |
+------------------------------+
| John  ,A  ,10,        0      |
| Jake  ,A  ,22,        0      |
| Jill  ,B  ,34,        0      |
+------------------------------+

And I would like to run an UPDATE query that populates the Class_Total with the total for each class i.e the result would be
+------------------------------+
| Name,Class,Value,Class_Total |
+------------------------------+
| John  ,A  ,10,        32     |
| Jake  ,A  ,22,        32     |
| Jill  ,B  ,34,        34     |
+------------------------------+

Currently I have this
UPDATE  dbo.Contrived
SET Class_Total = (SELECT SUM(Value)
FROM dbo.Contrived
)

But this puts the total for all classes in the Class_Total not just the class the row belongs to, I need to somehow group the items by class. I know I could do a
WHERE Class ='A'

In the Select but I would like to do it automatically for lots of classes.
Hope that makes sense, thanks.
Answer: You could use a simple sub query:
UPDATE c
SET c.Class_Total = (SELECT SUM(c2.Value)
                     FROM dbo.Contrived c2
                     WHERE c2.Class = c.Class)
FROM dbo.Contrived c

Demo-Fiddle
Answer: Please try using CTE:
;with T as(
    select *, SUM(Value) over(partition by Class) sm
    From dbo.Contrived
) update T set Class_Total=sm


my cocos2d game start, than other music applications stop

Question: When I start my Project game(using SimpleAudioEngine / cocos 3.16_ver / android Build / android Studio 3.0), than other music applications stop(ex. Samsung Music).
I want when i playing the game, listen My Music(not Game Background Music).
i did not modify android source.
How do I fix this?
Answer: This is a bug in 3.16 version.
You should modify code in Cocos2dxActivity.java (cocos2d/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java)
@Override
protected void onResume() {
    Log.d(TAG, "onResume()");
    super.onResume();
    // issue #18465
    AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
    if (!manager.isMusicActive()) {
        Cocos2dxAudioFocusManager.registerAudioFocusListener(this);
    }
    this.hideVirtualButton();
    resumeIfHasFocus();

    Cocos2dxEngineDataManager.resume();
}

https://github.com/cocos2d/cocos2d-x/issues/18465#issuecomment-344135839


Overloaded vector operators causing a massive performance reduction?

Question: I am summing and multiplying vectors by a constant many many times so I overloaded the operators * and +.  However working with vectors greatly slowed down my program.  Working with a standard C-array improved the time by a factor of 40.  What would cause such a slow down?
An example program showing my overloaded operators and exhibiting the slow-down is below.  This program does k = k + (0.0001)*q, log(N) times (here N = 1000000).  At the end the program prints the times to do the operations using vectors and c-arrays, and also the ratio of the times.
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <vector>

using namespace std;
// -------- OVERLOADING VECTOR OPERATORS ---------------------------
vector<double> operator*(const double a,const vector<double> & vec)
{
  vector<double> result;
  for(int i = 0; i < vec.size(); i++)
    result.push_back(a*vec[i]);
  return result;
 }

vector<double> operator+(const vector<double> & lhs,
         const vector<double> & rhs)
{
  vector<double> result;
  for(int i = 0; i < lhs.size();i++)
    result.push_back(lhs[i]+rhs[i]);
  return result;
}
//------------------------------------------------------------------
//--------------- Basic C-Array operations -------------------------
// s[k] = y[k];
void populate_array(int DIM, double *y, double *s){
  for(int k=0;k<DIM;k++)
    s[k] = y[k];
}
//sums the arrays y and s as y+c s and sends them to s;
void sum_array(int DIM, double *y, double *s, double c){
  for(int k=0;k<DIM;k++)
    s[k] = y[k] + c*s[k];
}
// sums the array y and s as a*y+c*s and sends them to s;
void sum_array2(int DIM, double *y, double *s,double a,double c){
  for(int k=0;k<DIM;k++)
    s[k] = a*y[k] + c*s[k];
}
//------------------------------------------------------------------
int main(){
  vector<double> k = {1e-8,2e-8,3e-8,4e-8};
  vector<double> q = {1e-8,2e-8,3e-8,4e-8};
  double ka[4] = {1e-8,2e-8,3e-8,4e-8};
  double qa[4] = {1e-8,2e-8,3e-8,4e-8};
  int N = 3;
  clock_t begin,end;
  double elapsed_sec,elapsed_sec2;
  begin = clock();
  do
    {
      k = k + 0.0001*q;
      N = 2*N;
    }while(N<1000000);
  end = clock();
  elapsed_sec = double(end-begin) / CLOCKS_PER_SEC;
  printf("vector time: %g \n",elapsed_sec);

  N = 3;
  begin = clock();
  do
    {
       sum_array2(4, qa, ka,0.0001,1.0);
       N = 2*N;
    }while(N<1000000);
  end = clock();
  elapsed_sec2 = double(end-begin) / CLOCKS_PER_SEC;
  printf("array time: %g \n",elapsed_sec2);
  printf("time ratio : %g \n", elapsed_sec/elapsed_sec2);
}

I get the ratio of vector time to c-array timeto be typically ~40 on my linux system.  What is it about my overload operators that causes the slowdown compared to C-array operations?
Comment: Lots of copying of vectors.
Comment: You are resizing the vectors; you are not resizing the arrays. Try a fair test.
Comment: Add `-O3` to your compile options.
Comment: If you don't test an optimized build, you're testing something not intended to run quickly. Turn optimizations on and try again.
Comment: What compiler flags did you use?
Comment: debug or release build? You know the result size, so resize the vector, don't use push_back.
Comment: @GManNickG For this program called test.cc I just compiled using g++ -std=c++11 test.cc

nothing special.  Could adding compiler flags help?
Comment: [mcve].  The above code includes overloaded poorly written operators **which you then proceed to not use**.  Please include actual test code, eliminate irrelevant code, and include actual timing results and compiler flags.
Comment: Note that the standard library's `std::valarray` already implements those overloaded operators.
Comment: According to cppreference.com, gcc and clang's versions of the standard library also implement expression templates for `std::valarray`.
Comment: @DanielSchepler , std::valarray worked great!  I knew there must have been something that implemented the operators I wanted.  Thanks again!
Answer: Let's take a look at this line:
k = k + 0.0001*q;

To evaluate this, first the computer needs to call your operator*.  This function creates a vector and needs to allocate dynamic storage for its elements.  Actually, since you use push_back rather than setting the size ahead of time via constructor, resize, or reserve, it might allocate too few elements the first time and need to allocate again to grow the vector.
This created vector (or one move-constructed from it) is then used as a temporary object representing the subexpression 0.0001*q within the whole statement.
Next the computer needs to call your operator+, passing k and that temporary vector.  This function also creates and returns a vector, doing at least one dynamic allocation and possibly more.  There's a second temporary vector for the subexpression k + 0.0001*q.
Finally, the computer calls an operator= belonging to std::vector.  Luckily, there's a move assignment overload, which (probably) just moves the allocated memory from the second temporary to k and deallocates the memory that was in k.
Now that the entire statement has been evaluated, the temporary objects are destroyed.  First the temporary for k + 0.0001*q is destroyed, but it no longer has any memory to clean up.  Then the temporary for 0.0001*q is destroyed, and it does need to deallocate its memory.
Doing lots of allocating and deallocating of memory, even in small amounts, tends to be somewhat expensive.  (The vectors will use std::allocator, which is allowed to be smarter and avoid some allocations and deallocations, but I couldn't say without investigation how likely it would be to actually help here.)
On the other hand, your "C-style" implementation does no allocating or deallocating at all.  It does an "in-place" calculation, just modifying arrays passed in to store the values passed out.  If you had another C-style implementation with individual functions like double* scalar_times_vec(double s, const double* v, unsigned int len); that used malloc to get memory for the result and required the results to eventually be freed, you would probably get similar results.
So how might the C++ implementation be improved?
As mentioned, you could either reserve the vectors before adding data to them, or give them an initial size and do assignments like v[i] = out; rather than push_back(out);.
The next easiest step would be to use more operators that allow in-place calculations.  If you overloaded:
std::vector<double>& operator+=(const std::vector<double>&);
std::vector<double>& operator*=(double);

then you could do:
k += 0.0001*q;
n *= 2;
// or:
n += n;

to do the final computations on k and n in-place.  This doesn't easily help with the expression 0.0001*q, though.
Another option that sometimes helps is to overload operators to accept rvalues in order to reuse storage that belonged to temporaries.  If we had an overload:
std::vector<double> operator+(const std::vector<double>& a, std::vector<double>&& b);

it would get called for the + in the expression k + 0.0001*q, and the implementation could create the return value from std::move(b), reusing its storage.  This gets tricky to get both flexible and correct, though.  And it still doesn't eliminate the temporary representing 0.0001*q or its allocation and deallocation.
Another solution that allows in-place calculations in the most general cases is called expression templates.  That's rather a lot of work to implement, but if you really need a combination of convenient syntax and efficiency, there are some existing libraries that might be worth looking into.
Answer: Edit:
I should have taken a closer look on how you perform the c-array operations... See aschepler's answer on why growing the vectors is the least of your problems.
–––
If you have any idea how many elements you are going to add to a vector, you should always call reserve on the vector before adding them. Otherwise you are going to trigger a potentially large amount of reallocations, which are costly.
A vector occupies a continuous block of memory. To grow, it has to allocate a larger block of memory and copy its entire content to the new location. To avoid this happening every time a element is added, the vector usually allocates more memory than is presently needed to store all its elements. The number of elements it can store without reallocation is its capacity. How large this capacity should be is of course a trade off between avoiding potential future reallocation and wasting memory.
However, if you know (or have a good idea) how many elements will eventually be stored in the vector, you can call reserve(n) to set its capacity to (at least) n and avoid unecessary reallocation.
Edit :
See also here. push_back performes a bound check and is thus a bit slower than just writing to the vector through operator[]. In your case it might be fastest to directly construct a vector of size (not just capacity) n, as doubles are POD and cheap to construct, and than insert the correct values through operator[].


add and remove preassign role to user on completion of user profile

Question: I have created user through admin. Admin Assign specific role to user. But On first time login we want user to complete user profile and then only it will able to access anything else on site. So I want to remove role from user profile if any of field in user profile is empty. And add Pre-assign role again to user after completion of user profile.
Please help. Thanks in advance
Answer: I never did something similar before, but I guess, rules module suits you like nothing else.
First of all you need 2 roles: users who just created and users who filled some profile fields. When admin creates a new user he set first (just created) role.
Then you create a new page view event (in rules core):

Create action load entity by id using site:current-user token (so you can access user profile fields in condition section);
In condition section, Check user role (only for just created);
In condition section, create condition for each profile field you wanna check (not empty or something similar);
Create action to redirect user to edit profile page.

So, each time when new user will load any site page, he will be redirected to edit profile page until he doesn't fill profile fields.
The second event is after profile save, assign new role "Fills some profile fields".
There is no difficult conditions, so I'm sure you can handle this event yourself.
If you need more complex solution, redirect on profile if only user load specific page you can try rules page. If you would like to redirect only once per session, you have to write your own rules condition through rules API or try out this one (never use this before).
I hope this could be helpfull for you, anyway wish you luck to find what you are really looking for.
Comment: Hi @Oleg Sherbakov..Thanks for replay.. I am redirecting user on every login to edit profile page until he finishes his profile. But my concern is if he tries to access some other links on site without completing his profile. That should not happen. I am doing it on Hook_user_login. But for assigning and removing roles, I don't understand which function to user. As it gives error when I use it in Hook_form_alter. Is something else wwe can do?
Comment: You can trigger user login event, instead of page view. Anyway can you give us your code to be more precise.


Deploying a Cloud Function from Cloud Build with --allow-unauthenticated

Question: My goal is to deploy a Cloud Function using Cloud Build.  My cloudbuild.yaml looks as follows:
steps:
- name: gcr.io/cloud-builders/gcloud
  args:
    [
      'functions', 'deploy', 'func3',
      '--region=us-central1',
      '--allow-unauthenticated',
      '--entry-point=helloWorld',
      '--runtime=nodejs8',
      '--source=https://source.developers.google.com/projects/XXX/repos/myfunc',
      '--trigger-http',
      '--firstname.lastname@example.com'
    ]

When I submit the build, the following is logged:
Created [https://cloudbuild.googleapis.com/v1/projects/XXX/builds/5ba01de5-b4ad-4489-b4b9-687d3a6fd8fa].
Logs are available at [https://console.cloud.google.com/gcr/builds/5ba01de5-b4ad-4489-b4b9-687d3a6fd8fa?project=YYY].
------------------------------------------------------------------------------------ REMOTE BUILD OUTPUT ------------------------------------------------------------------------------------
starting build "5ba01de5-b4ad-4489-b4b9-687d3a6fd8fa"

FETCHSOURCE
BUILD
Already have image (with digest): gcr.io/cloud-builders/gcloud
ERROR: (gcloud.functions.deploy) unrecognized arguments: --allow-unauthenticated

To search the help text of gcloud commands, run:
  gcloud help -- SEARCH_TERMS
ERROR
ERROR: build step 0 "gcr.io/cloud-builders/gcloud" failed: exit status 2
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

ERROR: (gcloud.builds.submit) build 5ba01de5-b4ad-4489-b4b9-687d3a6fd8fa completed with status "FAILURE"

As we can see, we fail.  If I remove the line which references --allow-unauthenticated all proceeds correctly.  For completeness, here is the working cloudbuild.yaml.
steps:
- name: gcr.io/cloud-builders/gcloud
  args:
    [
      'functions', 'deploy', 'func3',
      '--region=us-central1',
      '--entry-point=helloWorld',
      '--runtime=nodejs8',
      '--source=https://source.developers.google.com/projects/XXX/repos/myfunc',
      '--trigger-http',
      '--email@example.com'
    ]

I have checked the gcloud documentation on gcloud functions deploy found here and can't see any typos or other trivial errors.  I have been assuming that running gcloud as a Cloud Builder step would be identical to running it manually.
If I run the command manually (including the --allow-unauthenticated) it works without error.  For example, if I run:
#!/bin/bash
gcloud functions deploy func3 \
    --region=us-central1 \
    --allow-unauthenticated \
    --entry-point=helloWorld \
    --runtime=nodejs8 \
    --source=https://source.developers.google.com/projects/XXX/repos/myfunc \
    --trigger-http \
    --firstname.lastname@example.com

... there are no issues.
The core of the question is what might be the issue with the --allow-unauthenticated option within the context of Cloud Build?
Comment: for kicks, try using `gcr.io/cloud-builders/gcloud@sha256:4ea77d19d7336d5a8dc4ae0e609d7f5b45fca067c34b70d7ed6740af229392c6` as the build image. I've seen a couple weird errors like this in the past day.
Comment: I tried the builder using the incantation described where my `cloudbuild.yaml` contained the `--allow-unauthenticated` and this time got no error.  I'm curious as to how you (mr Travis) came to find this recipe and your thinking behind it.  Are we saying that this is simple a *transient* condition and that sooner or later the issue I'm having will just disappear?   Happy to follow y'alls recommendation about the fate of this question.  I'm leaning to deleting it as a *glitch*...
Comment: @Kolban it might still be useful for others facing the same issue, despite it's likely just a temporary issue cause by a) asynchronous versions of the back-ends which they've deployed or b) the image used (rather the second in this case). You still could notify them by opening a ticket.
Comment: It was a total shot in the dark, because that error makes no sense. You appear to be doing everything right AFAIK. It means that the latest gcloud build image has a bug. you can find old versions here: https://console.cloud.google.com/gcr/images/cloud-builders/GLOBAL/gcloud?gcrImageListsize=30
Comment: What are the role granted to cloudbuild service account?
Answer: The error message might be a little misleading:
ERROR: (gcloud.functions.deploy) unrecognized arguments: --allow-unauthenticated

When running  gcloud help functions deploy it lists --allow-unauthenticated as a valid flag:
--allow-unauthenticated
    If set, makes this a public function. This will allow all callers,
    without checking authentication.

As Travis commented... that this could be erroneous behavior isn't something I'd consider as "unlikely", since occasional glitches are nothing special when complex distributed systems are being updated.
Comment: Howdy Martin and thanks for the response.  The unrecognized argument message would seem to indicate that the option `--allow-unauthenticated` is not valid yet when I look at the gcloud functions deploy command, it appears to be present.  The README for the builder claims "Arguments passed to this builder will be passed to gcloud directly, allowing callers to run any gcloud command.".  Are there only a subset of options supported?
Answer: It appears to be a transient issue caused by a faulty gcloud build image.
Use this version for now:
gcr.io/cloud-builders/gcloud@sha256:4ea77d19d7336d5a8dc4ae0e609d7f5b45fca067c34b70d7ed6740af229392c6


EL6/KVM guest dies with "pthread_create failed: Resource temporarily unavailable"

Question: I've got a CentOS 6.5 x86-64 KVM server with a bunch of guest VMs of different breeds, mostly EL5 and EL6. However one and only one of them keeps crashing every couple of days with:
pthread_create failed: Resource temporarily unavailable

Here is the full log from /var/log/libvirt/qemu/vws3-pp.log:
2014-07-24 21:27:27.451+0000: starting up
LC_ALL=C PATH=/sbin:/usr/sbin:/bin:/usr/bin QEMU_AUDIO_DRV=none
    /usr/libexec/qemu-kvm -name vws3-pp,process=qemu:vws3-pp -S -M rhel6.5.0
    -enable-kvm -m 1536 -redhat-disable-KSM -realtime mlock=on
    -smp 1,sockets=1,cores=1,threads=1 -uuid d11de823-8bab-4e8d-8457-61ef7ab877a7
    -nodefconfig -nodefaults -chardev socket,id=charmonitor,path=/var/lib/libvirt/qemu/vws3-pp.monitor,server,nowait
    -mon chardev=charmonitor,id=monitor,mode=control -rtc base=utc -no-shutdown
    -device piix3-usb-uhci,id=usb,bus=pci.0,addr=0x1.0x2
    -drive file=/vm/prod/vws3-pp-disk1.qcow2,if=none,id=drive-virtio-disk0,format=qcow2,cache=writethrough
    -device virtio-blk-pci,scsi=off,bus=pci.0,addr=0x4,drive=drive-virtio-disk0,id=virtio-disk0,bootindex=1
    -netdev tap,fd=22,id=hostnet0,vhost=on,vhostfd=32
    -device virtio-net-pci,netdev=hostnet0,id=net0,bus=pci.0,addr=0x3
    -chardev pty,id=charserial0 -device isa-serial,chardev=charserial0,id=serial0
    -vnc 127.0.0.1:9,password -vga cirrus
    -device virtio-balloon-pci,id=balloon0,bus=pci.0,addr=0x5
char device redirected to /dev/pts/5

pthread_create failed: Resource temporarily unavailable   <====  ### HERE ####
2014-07-29 15:29:52.063+0000: shutting down

There are 8 other VMs on the box and all of them run happily for months, just this one crashes every few days. There is nothing special about this VM - pretty standard LAMP, not overloaded - I can't think of any significant difference between this and the other VMs that exhibit no problems. Some of those are very busy but still rock stable.
Somewhere on the net I found a suggestion to set max_processes = 4096 in /etc/libvirt/qemu.conf and restart the box - done that but it didn't help. The VM crashed again this morning for no good reason.
NEW INFO:
As it turns out the VM always dies while rdiff-backup is running from a remote backup server and in most cases the last log in the rdiff-backup-data/backup.log (on the remote side, ie not affected by the crash) is:
Processing changed file tmp
Incrementing mirror file /extpool/backup/vws3-pp/tmp

Even though /tmp/** is excluded from the backup. It could indeed be failing in /usr which is the next one alphabetically in /, who knows...
Backup runs every night but the VM crashes only about once a week.
What does rdiff-backup do so strange that it makes a KVM gues die with pthread_create failed: Resource temporarily unavailable?
Any ideas?
Answer: Check
cat /proc/`pidof qemu-kvm`/limits

to see if the limits are actually set after restart.
Comment: Yes it's set:
`Max processes  4096  4096  processes`


Dismiss view controller with custom animation?

Question: I am using this line of code to dismiss my view controller self.dismiss(animated: true, completion: nil), but I do not like the current animation. Instead I want to slide from left to right. Below is my attempt to test out an animation, but does not work.
UIView.animate(withDuration: 1.0, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {

        let transition = CATransition()
        transition.duration = 10
        transition.type = kCATransitionPush
        transition.subtype = kCATransitionFromLeft

        self.view.layer.add(transition, forKey: kCATransition)

        self.dismiss(animated: false, completion: nil)
        }, completion: nil)

Comment: I believe what is happening here is that the the view controller is being dismissed at the same time that the animation begins. You could try  moving the self.dismiss(...) to the animations completion block and see if that works. If it doesn't, you can find lots of tutorials online on how to custom segues. I've never done it so I can't give you any pointers myself, but Ray Wenderlich is always a good place to go for in depth tutorials.

https://www.raywenderlich.com/86521/how-to-make-a-view-controller-transition-animation-like-in-the-ping-app
Answer: let transition: CATransition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transition.type = CATransitionType.reveal
transition.subtype = CATransitionSubtype.fromRight
self.view.window!.layer.add(transition, forKey: nil)
self.dismiss(animated: false, completion: nil)


Where is my mistake in converting Cartesian to polar coordinates?

Question: We always believe that $dxdy$ in cartesian coordinate is equivalent to $rdrd\phi$. So let's check:
$x=r\cos\phi$
$y=r\sin\phi$.
I differentiate the equations above to derive $dx$ and $dy$
$dx=dr\cos\phi-r\sin\phi d\phi$
$dy=dr\sin\phi+r\cos\phi d\phi$
then we have
$dxdy=dr^2\cos\phi \sin\phi+rdrd\phi \cos^2\phi-rdrd\phi \sin^2\phi-r^2d\phi^2\sin\phi \cos\phi$
which is not $rdrd\phi$. However, even I neglect the terms with $dr^2$ and $d\phi^2$, I have
$dxdy=rdrd\phi \cos^2\phi-rdrd\phi \sin^2\phi=rdrd\phi(\cos2\phi)$
again I did not reach $rdrd\phi$
Note for those who answered similar questions: Please do not refer again to the Jacobian. I am aware of such answers and I do not oppose them. However, my question is that why we see this inconsistency between different ways of deriving the differentiation.
Comment: because things like dx are not real numbers so you cannot just manipulate them as if they are. Therefore the more reasonable question to ask yourself is why do you even expect this naive substitution to work (and saying that similar trickery works in 1D is of course not a good answer). The fact that you get the wrong answer just goes to show once again that these are not real numbers.
Comment: In this game, the rule is $dr\,d\phi=-d\phi\,dr$ (yes really). It's the calculus of *differential forms*.
Comment: @peek-a-boo is right, [they're not real](https://en.wikipedia.org/wiki/Grassmann_number).
Comment: @peek-a-boo. Sorry  I do not get your point and what I  wrote was based on chain rule for differentiation and it has nothing to do with manipulating symbol dx as a real number. However, even if you think this is my mistake, please clarify why in other cases - for instance if y=g(x) -we could  simply use the same technique to derive dxdy and here we can not?
Comment: @ Angina Seng. It seems so. But why?
Comment: Yes, you did treat them as real numbers when you decided to "multiply" $dx$ and $dy$ together and "expand out the brackets" and regroup the terms in the naive way. One way of answering the question (as written below) is to treat them as differential forms (which are NOT numbers) so the wedge product is anticommutative, and it is precisely this extra minus sign which changes your $-\sin^2\phi$ to a $+\sin^2\phi$, and makes everything work out, to give you $dx\wedge dy = r \, dr \wedge d\phi$.
Answer: An expansion on @AnginaSeng's comment:
If you compare a Taylor expansion $f(x+h)\in f(x)+hf^\prime(x)+\tfrac12h^2f^{\prime\prime}(x)+o(h^2))$ with the chain rule $f(x+dx)=f(x)+dx\cdot f^\prime(x)$, we get $dx^2=0$. If this is to work for all variables, $z=x+y$ gives$$0=dz^2=dx^2+dy^2+dxdy+dydx=dxdy+dydx.$$Really, this all should be written with $dx\wedge dy$ instead of $dxdy$; it's an antisymmetric product called a wedge product. Similarly, $dr^2=0$, $d\phi^2=0$ and $d\phi dr=-drd\phi$. Try it now.
More generally, you can use this idea to derive the Jacobian. For example, in $2$ dimensions a conversion between two coordinate systems looks like$$dx_1dx_2=(J_{11}dy_1+J_{12}dy_2)(J_{21}dy_1+J_{22}dy_2)=(J_{11}J_{22}-J_{12}J_{21})dy_1dy_2.$$
Comment: I agree that neglecting $dr^2$ and $d\phi^2$ is risky, however, as I mentioned in the question,  if I keep those terms, again we do not reach the $rdrd\phi$.
Comment: @SMAblahi There's nothing "risky" about the anticommuting nature of differential forms. You're supposed to do$$(\cos\phi\:dr-r\sin\phi\:d\phi)\wedge(\sin\phi\:dr+r\cos\phi\:d\phi)=(r\cos^2\phi-(-r\sin^2\phi))dr\wedge d\phi=rdr\wedge d\phi.$$
Comment: @ J.G. Thanks for your clear answer. So if I understand correctly, you mean that because the $r$ and $rd\phi$ are located along perpendicular directions, the exterior products like $dr \wedge dr=0$ and the terms with $dr\wedge d\phi$ are not zero. In addition, now I can understand that why $dr \wedge d\phi =-d\phi\wedge dr$.  However, why we should look at deferential terms as some kinds of vectors?
Comment: @SMAbtahi I suppose you can think of them as vectors, albeit not in the eometric sense I think you're imagining: $df(x_1,\,\cdots x_n)=\sum_i\partial_if\cdot dx_i$ is in the span of the $dx_i$. But don't conflate $\wedge$ with the $\times$ in $3$ dimensions; the former doesn't keep us in the same space. That $\wedge$ anticommutes follows from nilpotency, as above.
Comment: @ J.G. I referred to vectors since  $dr$ and $d\phi$ have geometrical meaning. However,  the real question is why we  must use $dx\wedge dy$ instead of $dxdy$ if it is not because of geometry?


What does it mean "arbitrary but fixed" in a proof?

Question: I've read related questions but I couldn't find a clear explanation as to, for example, when one should use "...an arbitrary but fixed...". Does it mean that my variable has a certain property so it's not any variable? but most importantly, When should one use it?
Comment: Could you give an example with some more context?
Comment: The phrase "arbitrary but fixed" means that it is some global constant, but the constant could be anything. As an example, we could say, "Let $A$ be an arbitrary but fixed constant. Then the derivative of $\sin(Ax)$ is $A\cos(Ax)$."
Comment: @Clayton May you tell me when I should used "arbitrary but fixed" instead of just "arbitrary"?
Comment: However, you cannot say in your inductive hypothesis the phrase "suppose for any $k,$ $p(k)$ is true," because this would imply that $p(k)$ is true for all $k,$ which is what you want to prove. However, if your hypothesis is that "fix an arbitrary value $k,$ and suppose that $p(k)$ holds," this is OK, because while $k$ is arbitrary here (meaning it might be any specific choice of $k$), you are only assuming that $p(k)$ is true for one specific value of $k.$
Comment: I'm glad I could help! To link any url, you can write {your text here}(your url here), and replace the {}'s with []'s. This will display "your text here," and when you click on it, it will take you to the url you put inside the parentheses.
Comment: When I read the principle of mathematical induction in "Calculus" by Tom Apostol in the induction step reads: "For an arbitrary but fixed $k$, suppose $p(k)$ and show $p(k+1)$ is true. What does it mean and when should one use it? @StephenDonovan
Comment: To elaborate a little on Clayton's comment, you'd write something like this when you want to prove that a statement holds for all elements of a specific set. For example, you want to prove that for any real number $r,$ the inequality $r^2 + 1\geq 0$ holds, or that for any positive integer $n,$ $1 + 2 + \cdots + n = \frac{n(n+1)}{2}$ is true. Then to do so, you want to consider a general real number $r$ or a general positive integer $n$ and show that the result is true for that general $r$ or $n.$ This would prove that the result always holds, because $r$ or $n$ was completely general.
Comment: See also [this](https://math.stackexchange.com/questions/46726/when-do-i-use-arbitrary-and-or-fixed-in-a-proof?rq=1) question.
Comment: @Stahl In your example "arbitrary" and "fixed but arbitrary" are the same thing, aren't they?
Comment: @Stahl In the linked question I couldn't find an answer.
Comment: Most of the time, I only use "arbitrary" when I plan on using it in a limit or some other operation that involves the parameter changing. I think this is personal preference, though; mathematically, I think the two phrases are interchangeable.
Comment: If they are interchangeable I could, for instance, in an induction proof make my induction hypothesis something like: "suppose for any $k$, $p(k)$ is true"? Because  I've seen videos that emphasize $k$ is not arbitrary since we would be assuming what we are trying to prove?
Comment: @HannyBoy "arbitrary" and "fixed but arbitrary" probably would generally mean the same thing. This agrees with the interpretation in Qiaochu's answer in the question I linked, and I would agree with what's been said here and there that the two are generally interchangeable.
Comment: @Stahl You cleared all of my doubts thus far. You have no idea how grateful I am! :D
Comment: @Stahl May you teach me how to link any questions within a comment, please?
Answer: Suppose that your job is to prove a statement of the form

For all $x \in S$, $P(x)$

where $P(x)$ is some true-false mathematical sentence.
Here's how you start the proof.

Let $x \in S$. We must prove that $P(x)$ is true...

There are a lot of different ways to reword this in natural language, and one of those ways is

For an arbitrary but fixed $x \in S$, we must prove that $P(x)$ is true...

This has the exact same meaning, as far as the mechanics of proof go.
In your particular example (from the comments) of an induction proof, I would myself word it like this:

Let $k$ be a natural number. We must prove that $p(k)$ implies $p(k+1)$. So, assuming that $p(k)$ is true, we must prove that $p(k+1)$ is also true.
Comment: So, since I assume $k$ to be arbitrary if say pick up on the fact that $k+1$ is a natural number, could I suppose what we use for $k$ but IN PARTICULAR for $k+1$? I mean since they're interchangeable I wouldn't think otherwise


Php copy CPU consumption

Question: I am creating a site which allows users to view a file via JavaScript plugin.
To do this, and maintain the security of the file, I will be creating a one time unique copy of the original file, each time the JavaScript plugin is accessed.
The original file is at the maximum 30mb, how will this scale for multiple users of the system? Say if 100 people were to create and access the copy of the file.
Comment: I can't imagine any case where it would be unsafe to use the original file as long as you don't use write accesses?
Comment: @bwoebi What OP mentions might be useful in a scenario where someone would create a service providing music/sounds, but to make sure that they can't just copy paste the URL to the MP3, and then have the MP3 served to them (or share the link to the MP3 file).
Comment: @h2ooooooo mod_rewrite to a central PHP file which can access the other data on the disk?
Comment: @bwoebi Agreed - copy is by no means the way to do this. A rewrite and a PHP verification of eg. a download token is 1000 times better.
Comment: Could you show me an example of this?
Comment: The plugin needs read and write access, but of course this means through direct linkage they will be able to bypass our purchasing process, and download the file for free. The purpose of copy would be to create the file, and then remove it once the user has read it.
Answer: You can do this by creating a htaccess rewrite to refer the user to a PHP script:
RewriteEngine On
RewriteRule ^download/([^/]+) /lib/download.php?file=$1 [QSA]

This will forward any request to yourdomain.com/download/anyfilehere.mp3?one_time_token=ABCDEFG to lib/download.php and set the $_GET['file'] to be anyfilehere.mp3. The one_time_token $_GET parameter will be forwarded, as we used [QSA].
The download.php could simply look something like this:
<?php
    if (!empty($_GET['file'])) {
        if (!empty($_GET['one_time_token'])) {
            if (TokenOK($_GET['one_time_token'])) { //Create a function called TokenOK where you look up the download token in eg. a database
                $fileName = '/var/www/downloadfolder/' . $_GET['file'];
                if (file_exists($fileName)) {
                    ExpireToken($_GET['one_time_token']); //Create a function called ExpireToken where you expire the token in eg. the database
                    readfile($fileName); //Read the file to the user
                    die();
                } else {
                    die('Error: file not found');
                }
            } else {
                die('Error: token is not OK');
            }
        } else {
            die('Error: token is not specified');
        }
    } else {
        die('Error: file is not specified');
    }
?>

Things to consider:

Output a mime header type specifying the content-type of your file
Read this PHP manual entry on readfile
Limit the one time token to only be valid in a certain time frame (and notify your user of this), instead of allowing it to be downloaded only once
How will your system react if the user cancels the download, and therefore can't download it again?
What if the download fails? Do they need to request a new download link?
If it's a streaming MP3 file, make sure that seeking works (it most likely won't if you seek outside where the MP3 has streamed to, as it'll create a new request for the MP3 file)
Comment: @James It shouldn't be too hard to generate a random ID and put it in a database (use `uniqid` if you have to), and then send that ID to the user and use it for the link. Your database should be `id | token | ip | valid` or `id | token | ip | valid_until` based on which approach you use. IP is optional, but might be nice so you can see if one user is downloading the same file a billion times.
Comment: How do I implement the token? Is there a php specific function?
Comment: Thank you very much, love you a lot hahaha :)

Php copy CPU consumption


Re-uploading file with unicode filename creates identical duplicate

Question: I'm running a Django site on a Debian 6 system, with a gunicorn server and nginx 0.7.67 handling static files. The filesystem locale is set to sv_SE.UTF-8.
I got a problem where another user uploaded a file with a filename containing unicode characters. This caused the server to throw a 404 when trying to serve the uploaded file. When I uploaded the same file from my system, the site now serves the file correctly. However, it didn't delete the old file, though they seem to be the exact same file in every regard. Below is the current directory listing.
-rwxr-xr-x 1 www-data www-data 1188260 25 jan 22.53 Läxa 15_geometri.pdf
-rwxr-xr-x 1 www-data www-data 1188260 27 jan 10.45 Läxa 15_geometri.pdf

How can there now be two identical files with the same (apparent) name? What can have been the cause of the 404 in the first place, i.e. what's wrong with the first upload? The URL is the same as before, only now it doesn't throw a 404.
Answer: They have different encodings for filename. What is the output when you do in directory:
$ file -i *

Comment: `Läxa 15_geometri.pdf: application/pdf; charset=binary`
`Läxa 15_geometri.pdf: application/pdf; charset=binary`
Answer: Visually the same unicode string may differ due to unicode normalization. You can check if names are different by  trying to do ls > a.txt and analyzing file as binary data, byte by byte.
PS. I hope ls doesn't perform any unicode normalization itself and delivers filenames "as is"...


About partial derivatives

Question: I'm reading the book "Teichmüller Theory and Applications to Geometry, Topology and Dynamics" by Hubbard and I have the following problem.
I need to compute $$\frac{d}{ds}\frac{\overline{\partial}z+\mu(t+s)\overline{z}}{\partial z+\mu(t+s)\overline{z}},$$ in $s=0$ and where $\mu$ is a Beltrami form on a Riemann Surface $X$ and $t\in[0,1]$. The books says that the complex derivatives are computed with respect to analytic coordinates on $X_{t\mu}$, i.e., with respect to $w=z+t\mu\overline{z}$. Then $$z=\frac{w-t\mu\overline{w}}{1-t^2|\mu|^2},\quad \overline{z}=\frac{\overline{w}-t\overline{\mu}{w}}{1-t^2|\mu|^2},$$ so that $$z+\mu(t+s)\overline{z}=\frac{w(1-t(t+s)|\mu|^2)+s\mu\overline{w}}{1-t^2|\mu|^2}$$
and the ratio of the derivatives becomes $$\left(\frac{\mu}{1-t(t+s)|\mu|^2}\right)\frac{d\overline{w}}{dw}.
$$
I understand all the calculations before the last step, but I think that the ratio of the derivatives will be $$\left(\frac{s\mu}{1-t(t+s)|\mu|^2}\right)\frac{d\overline{w}}{dw}.
$$
What I'm missing?
Thanks in advance !
Answer: For future reference, this is equation 6.6.30 in Hubbard's book on Teichmueller theory Vol. 1.
You are correct, for this equation to be correct is should read:
$$\frac{d}{ds}\left(\frac{s\mu}{1-t(t+s)|\mu|^2}\right)\frac{d\overline{w}}{dw}\Big|_{s=0}=\frac{\mu}{1-t^2|\mu|^2}\frac{d\overline{w}}{dw}.$$
This is a typo, since Hubbard ends up obtaining the correct result on the right hand side of the equation.

About partial derivatives


Module used to redirect pages to SSL

Question: Is or are there currently a module(s) that redirects users of a drupal site to enforce a SSL connection on parts of the website?
Essentially accomplish the following use case:

A user visits a glob pattern: /cart/*, / it enforces https://
  connection as well as redirects any images/javascript to utilize a ssl
  connection.
Comment: there is a d7 dev version of http://drupal.org/project/securepages that might help you out
Comment: @Jimajamma, you should really write that up as an answer so it can be accepted.
Comment: nah, I _try_ to keep link only answers in the comments :)
Answer: Looks like this is currently the canonical answer:
Use Secure Pages

This module makes sure that the user is running on a secure page when
  they create or edit content, view user details, or administer the
  site.

The other part of my question regarding redirecting assets on a page to a secure connection has actually be integrated into drupal core. It was previously a contrib module: http://drupal.org/project/securepages_prevent_hijack

#D7CX: This functionality is in Drupal 7 core so this module will not be ported. Please stay tuned for the securepages port.
This is an add-on to the Secure Pages module that will prevent
  hijacked sessions from accessing SSL pages, yet still allow users to
  stay logged in when browsing non-SSL pages.

Drupalscout looks to have a great site recipe on working with SSL's as well:

The Secure Pages module is a relatively old module and quite popular.
  It's goal is to only make certain pages of the site use HTTPS by using
  two lists of urls which should either by HTTPS or not. The benefit of
  this module is that you can use regular old HTTP for most of the site
  and only encrypt the traffic where you really need it. By default it
  will encrypt traffic for adding content, editing content, anything
  related to users, and for the admin area.
SSL processing is taxing on a server. Using SSL on just the most
  important pages helps make sure that the data sent back and forth on
  those pages is encrypted. However, the session cookie is still
  unencrypted so a user who authenticates over HTTPS and then visits a
  non secure page sends their sesssion identifier in the clear which
  allows for an attacker to steal their session and login to the site
  which gives them the access to the very data that was supposed to be
  protected. This is largely "security theater" but it sure makes people
  feel good.
Pro: Reduces load on server compared to a full SSL solution while
  encrypting important data transmission. Con: Doesn't protect against
  session hijacking so data can still be compromised.

Module used to redirect pages to SSL


changing element.style on the finishing position of a jQuery animated div

Question: I am using a photo album jQuery plugin (Supersized). It includes a thumbnail tray which slides up from the bottom of the screen at the touch of a button, resulting in the following HTML being created onto the div properties and in firebug css 'element.style. property:
style="display: block; bottom: -150px;"

and when caller clicked:
style="display: block; bottom: 0px;"

I am trying to place a footer div at the bottom of the page though, so want to move the finishing position to 'bottom:0px'. I have seen that an extra element.style can be added to local CSS but without a 'before' and 'after' type of selection I don't understand if that can help me. Furthermore I don't find the function in the JS files and from what I understand it can't be accessed anyway. I need to change these to be:
style="display: block; bottom: -150px;"

and when caller clicked:
style="display: block; bottom: 42px;"

Any advice would be most welcome. Thanks
Answer: $('#clickedElement').on('click', function() {
    $('#element').css('bottom', '42px')
});

If i didn't missunderstand you?
Answer: Probably the function which you can not find is jquery .css() function you can read how it works here.
Also if you want to animate some dive you can use jquery .animate() function (docs).
In your case it should looks like:
$('#button').click(function() {
    $('#element').animate({
        $('#element').css('bottom', '42px');
    }, 5000, function() {
    });
});

Where 5000 it's time of your animation in miliseconds.
Comment: Thanks Mateusz, in the end it was hidden in here: $(vars.thumb_tray).stop().animate({bottom : 0, avoidTransforms : true}, 300 );


Limit the number of discount per product to 1, Commerce Discount

Question: I'm trying to make a one time discount for each product of a certain type per customer.
If the user buy a product he will have a discount on it, but he cannot have it a second time.
How can I do that.
So far I couldn't figure out how to limit it for the product itself.
Maximum usage determines how many times a discount may be applied across all customers or to a single customer's orders, which in my case should be empty (unlimited).
Where is the setting to limit the number of use per product to 1?
Is it a rule I need to code?
Cheers
Answer: You could use the Flag module to get this to work, by configuring an appropriate (non-global) flag, which you should then use to (automagically) flag each product by the customer, after such discount was applied (for the first time). To actually flag such products by the customer, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).
Any time a customer buys a product, you can verify if it is the very first time, or yet another time. For this verification, all you'd have to do is use a Rules Condition to check "has this user yes or no flagged this product already (by the flag you created for this purpose)".
If you're not familiar with the Flag module, checkout either of these:

The set of 8 video tutorials about the Flag module.
Flag's Community documentation.
Comment: @GwenM, Flag, ... not Flag***S***, right? And to make it more confusing: questions about the Flag module are tagged with ... FlagS. Ggggrrrrreetings!
Comment: Ahah good to know! Cheers!


How to set the name of DLL from which binary depends?

Question: In my program I'm using libcurl that is built with SSL support. So I have libcurl.dll that depends on libeay32.dll and ssleay32.dll. I need to change the names of libeay32.dll to libeay32_10_x32.dll. How to tell libcurl to use libeay32_10_x32.dll not libeay32.dll?
Answer: This question talks about doing something like this. You have to edit the PE file and change the imported dll name. The one thing that question doesn't address is when the new name is longer or shorter than the original import name. If the length is different you run the risk of killing offsets in your executable that were calculated by the linker.
Given that libcurl is open source your best bet would be to rebuild it linking against your renamed libraries.
Comment: Thank you!
I've successfully rebuilt openssl to produce libs pointing to DLLs with specific names and then used them to build libcurl.


Pegar XHR e setar valores dinamicamente com jQuery Datatables?

Question: Estou usando o plugin Jquery DataTable e ele funciona, com AJAX, basicamente da seguinte forma:
Você recebe um JSON da sua requisição e nele precisam conter estes dois dados: ("recordsTotal", "recordsFiltered") e também todos os dados que serão exibidos na tabela para que ocorra a paginação perfeitamente.
Estou trabalhando, nesta situação, com processamento ServerSide. O negócio é que no sistema que utilizo as informações adicionais (estas de paginação) não vem no corpo do JSON e sim nos cabeçalhos de retorno (situação essa que não posso alterar). Então as minhas perguntas são:

Como faço para capturar estes dados do XHR no retorno pelo DataTable?;
Como faço para setar essas propriedades de ("recordsTotal", "recordsFiltered") com os valores que eu pegar dos cabeçalhos?

Pesquisei bastante e tentei de mil formas possíveis e não consegui ainda chegar na resolução deste problema. O site deles oferece um debug então segue o link do debug da minha DataTable para o caso de alguém precisar: Nele contém também o código que estou utilizando.
Debug do DataTable()
Comment: Pronto, conforme solicitado está publicado :)
Comment: Achou alguma solução? Poste como resposta para ajudar outras pessoas.
Comment: Fiz uma alteração no código do DataTable e enviei para o proprietário pelo github. Ele não aceitou a exibição do XHR neste momento e disse que irá analisar melhor. O jeito foi alterar o meu código de backend mesmo, infelizmente.
Comment: Mas tem como você postar alguma resposta para a pergunta não ficar solta?
Answer: Conforme pedido pelo nosso amigo Maniero estou respondendo a minha pergunta.
Não consegui resolver o problema acima. Fiz um fork do projeto no GitHub, alterei o que eu precisava e encaminhei uma pull request ao desenvolvedor. Ele agradeceu o envio, mas disse que, no momento, ele não pensa em disponibilizar tal recurso e que irá estudar a viabilidade do mesmo no futuro.
A solução foi fazer ajustes no PHP para poder continuar utilizando o DataTable.


Get parent menu item of a current node

Question: I'm trying to get the parent menu item of node I am currently on:
$node_id = // some id
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
$parent = $menu_link->getParent();

but for some reason it always fails with this error:
Error: Call to a member function getParent() on array

When I inspect $menu_link I can clearly see it is there:

Also the method of getParent() seems to be correct: Docs
Would appreciate any help!
Comment: Maybe related: https://drupal.stackexchange.com/questions/183201/get-menu-link-siblings
Answer: I think you need to reset the collection first, as the ::loadLinksByRoute() annotation states that it returns an array of MenuLinkInterfaces[].
See /core/lib/Drupal/Core/Menu/MenuLinkManagerInterface.php:

  /**
   * Loads multiple plugin instances based on route.
   *
   * @param string $route_name
   *   The route name.
   * @param array $route_parameters
   *   (optional) The route parameters. Defaults to an empty array.
   * @param string $menu_name
   *   (optional) Restricts the found links to just those in the named menu.
   *
   * @return \Drupal\Core\Menu\MenuLinkInterface[]
   *   An array of instances keyed by plugin ID.
   */
  public function loadLinksByRoute($route_name, array $route_parameters = [], $menu_name = NULL);

So do something like:
/** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
// Reset collection by retrieving the first item.
$menu_link = reset($menu_links);
// Now call the parent method.
$parent = $menu_link->getParent();

Comment: Seems like it has to do with that `reset()` returns `false` if the array is empty.
Comment: got it working, thanks for the answer, the `reset()` helped.
Comment: thanks for your answer, appreciate it. Now I'm getting a new error: `Error: Call to a member function getParent() on bool`. Do you have a second idea?
Comment: I think you are right about that. I guess you first need to double check that it is indeed returning an array of objects and not an empty array.

Get parent menu item of a current node


Looking for a good Mini - Panels tutorial

Question: There are lots of good to tutorials for view and panels, but I'm having trouble finding specific information on how to properly use mini panels. Does anyone know of a good tutorial or explanation of how it works? again I've seen to referenced a bunch of times as a possible solution to certain problems, but never really understood how to use it.
(D7 panels 3 would be ideal)
Comment: Asking for tutorials is off topic here on DA.
Answer: I have not found a tutorial specifically for mini-panels, but it works similarly to page panels.  nodeone.se has an excellent tutorial on using Page Panels (Page Manager & Panels modules enabled).
Mini Panels are closely related , but behave more like blocks.  When you define a mini-panel it will be available in the panels UI for placement as well as in the admin/structures/blocks form.  The major difference from blocks is that mini-panels are smart.  They can take context from the node, user and other sources and display accordingly.  They also connect to a View.
There is one thing to observe when defining a mini-panel.  The UI is slightly different from Page Panels and the first time I used them, I could not figure out how to add content to one.  To access the "content" and other setting forms select the Panels breadcrumb  menu at the top.
Comment: Thanks, I think the point of confusion was show to get to the settings and content portion of the mini-panel, I would got to "edit" and only see the overview, once I noticed the breadcrumbs I understood, The UI is different from a regular panel so it a wee bit confusing
Comment: I entered an issue at Drupal/Panels about this yesterday.  Hopefully they will make it a bit clearer in the next go-around.
Answer: Although for panels2, here is a basic tutorial for minipanels.
Current panels adds some stuff, but the idea is illustrated well.


useSelector of React Redux don't update state of store on expo react-native

Question: I made the same model on the web and it worked, I tried to use shallowEqual of Redux as second parameter of useSelector function, also the  _.isEqual of lodash libary as there on the Redux documentation in Hooks section but don't worked.
Expected behavior:

On dispatch action the components with useSelector must bring the updated state.

What happens:

The components brings the initial state empity.
versions:
"Expo": "~37.0.3"
"react-native": "37.0.1",
"react-redux": "^7.2.0",
"redux": "^4.0.5"

EDITED:
I tried to reproduce the structure similar to the snack that also reproduced the same problem, here is the link: https://snack.expo.io/@danieltfischer/useselector
Comment: your state is only updated on handleSubmit. It should be empty unless you call handleSubmit.
Comment: I called handleSubmit function, when I back to Dashboard screen the state keeped empty. Also on the log nothing changed.
Comment: Are you using the state you get from useSelector somewhere, how are you determining that it's not bringing the latest state?
Comment: Danyal, I am. I pass the state as "data" to the FlatList component where it also receives "data" as property. I used the useSelector on the form and on the dashboard and put a log to make sure they would receive the updated status and also as I said I am using the state in a flatList component that was to render the items coming from the state
Answer: I have looked at your code, and I found one bug.
You are not exporting your action type string constant from the actions folder:
// What you are doing
const CREATE_MED = 'CREATE_MED';

// What you need to be doing
export const CREATE_MED = 'CREATE_MED';

After I fixed this, the app is working, as soon as I dispatch the action it brings back the latest state for me and updates the flatlist too.
Try making this change and see if it fixes it.
The reason it wasn't working is because every time the reducer function is called the CREATE_MED action constant is undefined, so it always went to the default options which was returning the previous state.
Comment: I was even ashamed. Thank you very much, it was a silly mistake I didn't realize,
Comment: I had copied eslintrc.json from another project and forgot to activate it at the beginning of the project, silly error... I already added your answer as a solution. Thank you again!
Comment: I'm glad it fixed the bug, try to use `Redux Devtools`, this kind of bugs are easily caught in it. and I think using something like ESLint auto catches these kind of import/export bugs.  You can mark this answer as the solution, thanks. :)


Some "facts" on oriented angles in the Euclidean affine space of dimension 2

Question: Let $\mathcal{E}^2$ be an Euclidean affine space of dimension $2$ oriented by $R=(O,B=\{u_1,u_2\}$.
Let
$$\mathcal{r}=\{P \in \mathcal{E}_2 \text{ such that } \overrightarrow{AP} \in \langle u \rangle \}$$ and
$$\mathcal{s}=\{P \in \mathcal{E}_2 \text{ such that } \overrightarrow{BP} \in \langle v \rangle \}$$
be two lines of $\mathcal{E}_2$.
Let $\alpha$ be the angle between r and s and $\beta$ be the angle between $s$ and $r$.

Then I've been given the following facts (without any proof):

$\alpha$ depends on the orientation of $\mathcal{E}_2$ and on the reciprocal orientation of $r$ and $s$ and on the order in which you pick the lines. Furthermore, if you change the orientation of $r$, then, $\alpha' = \alpha + \pi$
$\alpha + \beta = 2 \pi$
$ \cos \alpha = \cos \beta$ and depends only on the orientation of $\mathcal{E}_2$ and on the reciprocal orientation of the lines
$|\cos \alpha |= |\cos \beta|$ depends only on the orientation of $\mathcal{E}_2$.
$ \cos \alpha = \cos \beta = \frac{u \cdot v}{\lVert{ u }\rVert \lVert{ v }\rVert  }$, where $u \cdot v$ is the scalar product of $u$ and $v$.

My question is:

The statements are clear, but surely the proofs don't seem obvious to me; how does one prove them?
Answer: We are in the vector plane $E$.
Part 1. Orientation. If $B,B'$ are two bases of $E$, then let $[B,B']$ be the matrix s.t. its $i^{th}$ column is the decomposition of the $i^{th}$ vector of $B$ in $B'$. We consider the equivalence relation: $B\sim B'$ iff $\det([B,B'])>0$; $\sim$ has two classes, that is, the possible $2$ orientations of $E$. According to the definition, if $\{u,v\}\sim B'$, then $\{-u,v\}\not \sim B'$ and $\{v,u\}\not \sim B'$.
Part 2. If we define a scalar product on $E$, then the orthogonal group is defined and we can define an orthonormal basis $B$ of $E$. Now we can define the angle $(u,v)$ between $2$ unitary vectors $u,v$: $(u,v)=\mathcal{O}$, where $\mathcal{O}\in O^+(2)$ satisfies $\mathcal{O}u=v$ (such $\mathcal{O}\in O^+(2)$ is unique and, moreover, its associated matrix $O$ only depend on the orientation of the chosen basis $B$). There is $\theta\in\mathbb{R}/2\pi\mathbb{Z}$ s.t. $O=\begin{pmatrix}\cos(\theta)&-\sin(\theta)\\\sin(\theta)&\cos(\theta)\end{pmatrix}$. We use the notation $(u,v)=O_{\theta}$; note that $O_{\alpha}\circ O_{\beta}=O_{\alpha+\beta}$.
If $(u,v)=O_{\theta}$, then $(v,u)={O_{\theta}}^{-1}=O_{-\theta}$, $(-u,v)=O_{\theta} \circ O_{\pi}=O_{\theta+\pi}$.
Assume that we choose another orientation for $E$; it is equivalent to say that in $B=[x,y]$, we change $x$ with $-x$. Then the matrix associated to $\mathcal{O}$ becomes $\begin{pmatrix}\cos(\theta)&\sin(\theta)\\-\sin(\theta)&\cos(\theta)\end{pmatrix}$, that is $O_{-\theta}$.
About the scalar product, $<u,v>=<u,O_{\theta}u>=<x,O_{\theta}x>=\cos(\theta)$. And if $u,v$ are not unitary, then $<u,v>=||u||||v||<\dfrac{u}{||u||},\dfrac{v}{||v||}>$.


Cauchy but not rapidly Cauchy

Question: I want to show that the sequence $\{\frac{(-1)^n}{n}\}$ is Cauchy but not rapidly Cauchy. Here is the work I done so far. I am curiously if I made any errors.
Consider the normed linear space $\mathbb{R}$ with the norm of the absolute value. Let
$$
\{f_n\}=\left\{\frac{(-1)^n}{n}\right\}=\left\{-1,\frac{1}{2},\frac{-1}{3},\ldots\right\}.
$$
Suppose $\{f_n\}\rightarrow 0$. Let $\epsilon>0$ and $N\in\mathbb{N}$ such that $n\geq N$. We want to show $|f_n-0|<\epsilon$ in order to prove the convergence of $\{f_n\}\rightarrow 0$.
Consider
\begin{eqnarray*}
\left|\frac{(-1)^n}{n}-0\right| &<& \epsilon\\
\left|\frac{(-1)^n}{n}\right| &<& \epsilon\\
\left| \frac{1}{n} \right| &<& \epsilon\\
\frac{1}{n}&<& \epsilon
\end{eqnarray*}
Therefore $n>\frac{1}{\epsilon}$. Let $N=\frac{1}{\epsilon}$. Then $n>\frac{1}{\epsilon}$ implies $|f_n-0|<\epsilon$, meaning $\{f_n\}\rightarrow 0$. Since $\{f_n\}$ converges in $\mathbb{R}$,  $\{f_n\}$ is Cauchy.
Now we want to show that $\{f_n\}$ is not rapidly Cauchy. In other words, we want to show that for $\{f_n\}$ there is not a convergent series of positive numbers $\sum_{k=1}^\infty \epsilon_k$ for which
$$
|f_{k+1}-f_k|\leq \epsilon_k^2.
$$
Consider $|f_{k+1}-f_k|\leq \epsilon_k^2$.
\begin{eqnarray*}
|f_{k+1}-f_k| = \left| \frac{(-1)^{k+1}}{k+1}-\frac{(-1)^k}{k} \right| &\leq& \epsilon_k^2\\
\left|\frac{k(-1)^{k+1}-(k+1)(-1)^k}{k(k+1)} \right|&\leq& \epsilon_k^2
\end{eqnarray*}
Suppose $k$ is even. Then
$$
\left|\frac{-k-(k+1)}{k(k+1)} \right| = \left|\frac{-2k-1}{k^2+k} \right| \leq \epsilon_k^2
$$
Suppose $k$ is odd. Then
$$
\left|\frac{k+(k+1)}{k(k+1)} \right| = \left|\frac{2k+1}{k^2+k} \right| \leq \epsilon_k^2
$$
Therefore
$$
\frac{2k+1}{k^2+k} \leq \epsilon_k^2
$$
So $\epsilon_k=\sqrt{\frac{2k+1}{k^2+k}}$. Consider $\sum\limits_{k=1}^\infty \sqrt{\frac{2k+1}{k^2+k}}$. Notice $\sqrt{\frac{2k}{k^2}}=\frac{\sqrt{2}}{k}\leq\sqrt{\frac{2k+1}{k^2+k}}$ and $\sqrt{2}\sum\limits_{k=1}^\infty\frac{1}{k}$ diverges by the $p$-series since $p=1$. Therefore by the comparison test, $\sum\limits_{k=1}^\infty \sqrt{\frac{2k+1}{k^2+k}}$ diverges. Thus $\{f_n\}$ is not rapidly Cauchy.
Comment: Is there a question somewhere?
Comment: Did I make any mistakes in my argument?
Comment: I am not sure my divergent argument is correct.
Answer: Your argument looks correct, although it's a bit long and drawn out. I might argue this way: From your definition we have $f_k$ rapidly Cauchy iff
$$\sum_{k=1}^{\infty} |f_{k+1} - f_k|^{1/2} < \infty.$$
(Never heard of "rapidly Cauchy" before). Now
$$f_{k+1} - f_k = \frac{(-1)^{k+1}}{k+1} - \frac{(-1)^{k} }{k} = (-1)^k\left ( -\frac{1}{k+1} -\frac{1}{k} \right ).$$
So $|f_{k+1} - f_k| = 1/(k+1) + 1/k > 1/k.$ Thus $|f_{k+1} - f_k|^{1/2}> 1/\sqrt k.$ Since $\sum_k 1/\sqrt k = \infty,$ $f_k$ is not rapidly Cauchy

Cauchy but not rapidly Cauchy


AttributeError: 'Directores' object has no attribute

Question: Estou tentando obter um valor de uma classe bem simples, porém estou com  um problema que não consigo resolver. Segue os códigos abaixo:
Classe principal:
from directores.directores import Directores
# A classe Directores encontra-se em directores/directores.py

def main():
    print (Strings.start_description)

    # Sobrescrever arquivos encontrados
    arcpy.env.overwriteOutput = True

    # Criando todos os diretรณrios
    directores = Directores(Parameters.main_folder + r"\\")
    print(directores.getInput_folder_SRTM())

A classe Directores:
class Directores(object):

    def __init__(self, main_folder):
        # Diretórios secundários de entrada - INPUT
        self.input_folder = main_folder + r"\Input\\"
        self.input_folder_SRTM = self.input_folder + r"SRTMs\\"

    def getInput_folder_SRTM(self):
        return self.input_folder_SRTM

Com o seguinte erro:
Runtime error
Traceback (most recent call last):
  File "<string>", line 50, in <module>
  File "<string>", line 36, in main
AttributeError: 'Directores' object has no attribute 'getInput_folder_SRTM'

Em cada pasta criei um arquivo vazio __init__.py
Se precisar de mais alguma informações estarei a disposição. E se me derem algumas dicas também agradeço muito!
Comment: Não temos como testar seu código, pois há dependências que não estão explícitas na pergunta, tal como `String`, `arcpy` e `Parameters`, porém, num teste básico, removendo essas dependências, seu código não reproduziu o erro citado: https://repl.it/@acwoss/SweetAdorableInterface. Poderia, então, [edit] e criar um [mcve] que demonstre o erro?
Answer: A chance aí é que você tenha outra versão desse projeto, com outra pasta directores que contenha uma versão antiga do código, e ao fazer o import você esteja trazendo o arquivo dessa outra pasta.
Tente colocar essas linhas no início do seu arquivo que você chama de "classe principal":
from directores import directores as directores_module
print (directores_module.__file__)

Isso vai imprimir o caminho do arquivo directores.py que ele está importando.
Agora, o problema pode nem ser esse, mas vamos aproveitar para as demais dicas que você pediu:

Use Python 3. Não faz sentido começar um projeto com Python 2.7 hoje - é uma versão da linguagem com 10 anos de idade, e que sai de uso em um ano e 2 meses. Você perde várias melhorias - principalmente no tocante a tratamento de texto acentuado. Mesmo que você precise de Python 2.7 para outros fins no mesmo computador, o uso de virtualenv permite que você tenha projetos de Python 2 e Python 3 em paralelo na mesma máquina sem nenhuma ambiguidade
Use seus nomes com consistência. O guia de estilos de Python recomenda que se use nomes "snake_case": isso é, palavras em nomes de funções e variáveis são separadas com "_" - e apenas nomes de classe em "CamelCase". Você não é obrigado a seguir as convenções de estilo - mas misturar underscore com camel case dentro dos mesmos nomes (sério, dói os olhos só de olhar)
Se você está usando strings prefixadas com "r", não precisa dobrar as \\ para separar diretórios - uma única \ é o suficiente. Mas melhor ainda, em Python você pode usar a barra pra frente para separar diretórios - / mesmo no Windows. É uma forma mais universal e seu código não fica dependente de sistema. Melhor ainda: use Python 3.7 (vide dica 1) e use a pathlib em vez de strings para caminhos de diretórios. https://docs.python.org/3/library/pathlib.html
Não use "getters" e "setters" se você não vai fazer nada com o valor dentro desses métodos. Em Python todos os atributos são públicos, exceto por convenção. Se tudo que seu método getInput_folder_SRTM vai fazer é devolver self.Input_folder_SRTM, não tem por que chamar o método - acesse o atributo direto na instância com directores.Input_folder_SRTM no seu outro módulo. Se você quiser transformar/filtrar o valor quando ele for setado, ou transforma-lo quando for usado, use property para escrever o getter e o setter - mas perceba que legal: você pode se preocupar com o property só numa outra faze do seu projeto e acrescentar getters e setters sem mudar nada do código que use o atributo.
Use um gerenciador de versões de código, como o git e ambientes isolados, como o virtualenv. Pode ser que seu problema não seja o que  mencionei acima - mas está com bastante cara de ser devido a versões antigas do projeto espalhados pelo computador. Com git acaba esse problema de ter várias versões do mesmo código em pastas diferentes, conforme você vai aprendendo a usa-lo. E com o virtualenv você isola exatamente quais pacotes e módulos estão instalados para cada projeto de Python - evitando interferências entre versões diferentes.


Bash: How to convert a number into a month string?

Question: I want to map, for example, 4 to 'Apr' (3 character abbrev of the name of the month)
Answer: Try this :
MONTHS=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

echo ${MONTHS[3]}

Or as per @potong's suggestion (to have a 1-1 correspondence between month number and index)
MONTHS=(ZERO Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

echo ${MONTHS[4]}

Comment: Maybe `MONTHS=( dummy Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)` would be more intuitive as then `4` maps to `Apr`.
Comment: I pick this answer because it is simpler
Answer: #! /bin/bash
case $1 in
  [1-9]|1[0-2])     date -d "$1/01" +%b ;;
  *)            ;  exit 1
esac

Answer: A locale-sensitive result can be gained like this; put the number into the month-position of the date, passed as date to be output to date, and choose an arbitrary year and day (keep away from the 50ies and the far future, and avoid days much greater than 20). It hasn't to be the actual year:
i=10; date -d 2012/${i}/01 +%b

Here, with locale de_DE, I get as result:
Okt

(I didn't choose April, because it is the default for date to take the current month, so with a bad formatted -d -date, you get April, even if i=10. I know it, because I experienced it. And furthermore: The german name for April is April, so it wouldn't serve well as example for the finer details, which follow just now:)
i=10; LC_ALL=C date -d 2012/${i}/01 +%b

this reveals the month in an international standard style.
The advantage of the solution is, that it will survive revolutions, which rename the months to Brumaire, Obamer or internationalization attemps (Mär, Mai, Okt, Dez in German, i.e.).


Handling Events in MVVM

Question: So this is my first MVVM application. I have a "shell" view model named MainWindowViewModel for the main window that basically splits the view into two pages: MainWindowRibbon and MainWindowFrame. The MainWindowViewModel stores both pages as properties, which I plan to use databinding to update in the UI. Here is some of the code for reference:
MainWindowView xaml~
<Grid>
    <Frame Content="{Binding MainWindowRibbon}" Grid.Column="0" Grid.Row="0"/>
    <ScrollViewer>
        <Frame Content="{Binding MainWindowFrame}"/>
    </ScrollViewer>
</Grid>

MainWindowView code behind~
    public partial class MainWindowView : Window
{
    public MainWindowView()
    {
        InitializeComponent();
        mainWindowViewModel = new MainWindowViewModel();
        DataContext = mainWindowViewModel;
    }
    public MainWindowViewModel mainWindowViewModel;
}

MainWindowViewModel code~
        public MainWindowViewModel()
    {
        //MainWindowRibbon and MainWindowFrame are declared as public Page properties
        MainWindowRibbon = new MainWindowRibbonView();
        MainWindowFrame = new WelcomePageView();
    }

The MainWindowRibbonView, like the MainWindowView, instantiates the MainWindowRibbonViewModel.
My trouble comes when I wish to use an event within the MainWindowRibbonViewModel that will call for the MainWindowViewModel to reassign the MainWindowFrame page. I do not know how to connect the button command of the navigation bar I have created in the MainWindowRibbonView to cause an event or change in the MainWindowViewModel.
I do not know if the way I have organized this is ideal. Please let me know if I need to revise.
If somebody could help me determine the best approach, or even just a functioning one, I would be very grateful.
P.S.
Sorry if the naming conventions aren't the greatest.
Edit:
Lesson learned: listen to Joe.
Comment: I think you misunderstand what the `Frame` is.  It's a `ContentControl`.  You do not set its `Content` to some type of UI element.  Instead you set it to hold an instance of some view-model (e.g. `PersonViewModel`).   The UI for it comes in XAML;  You lay out a default `DataTemplate` for that view-model class-type.   The `DataTemplate` has UI controls that bind to that view-model's properties. So that whenever the `Content` property is set to an object of that type, defined in the `DataTemplate`, then it will show the UI you've laid out in the  `DataTemplate`, property bound.
Comment: You might want to read this:  https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/data-templating-overview
Answer: I suppose it depends on what kind of button you are using in your navigation bar.  is it a RadioButton?  A RibbonToggleButton?  Is it a regular button binding to an ICommand?
Since you called your Navigation Bar a "Ribbon", let us suppose it is a RibbonToggleButton (which is still basically a CheckBox).  If it is checked, you show some view-model your "page 1".   If it is not checked, you should another view-model representing your "page 2"
Let us also suppose your view's ribbon is up top.  So you have two rows:  the Ribbon row and the content row.
I might rewrite your MainWindow to look like this, (note the IsChecked property to some boolean property in your view-model like so:)
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <ToggleButton Content="Show Page 1" IsChecked="{Binding ShowPage1}"/>

    <ScrollViewer Grid.Row=1>
        <Frame Content="{Binding CurrentViewModel}"/>
    </ScrollViewer>
</Grid>

And I might write your view-model like this:  (Note that I assume it implements INotifyPropertyChanged and I call a function RaisePropertyChanged that I do not show.
public class Page1ViewModel {}  // Fill this out with Page 1 properties
public class Page2ViewModel {}  // Fill this out with Page 2 properties

// MainWindowViewModel.  Implements INotifyPropertyChanged.  Implementation
// is not shown here.

public class MainWindowViewModel : INotifyPropertyChanged
{
    private Page1ViewModel = new Page1ViewModel();
    private Page2ViewModel = new Page2ViewModel();

    public MainWindowViewModel()
    {
        _currentViewModel = Page1ViewModel;
        ShowPage1 = true;
    }

    private object _currentViewModel;

    // The current contents of the main frame.

    public object CurrentViewModel
    {
        get => _currentViewModel;
        set
        {
            if (value == _currentViewModel)
                return;

            _currentViewModel = value;
            RaisePropertyChanged();
    }

    // Should CurrentViewModel be page 1 or page 2?

    public bool ShowPage1
    {
        get => return _currentViewModel == Page1ViewModel;
        set
        {
            if (value == ShowPage1)
                return;

            CurrentViewModel = value ? Page1ViewModel : Page2ViewModel;
            RaisePropertyChanged();
        }
    }
}

Note that I am not showing you any of the properties of Page1VieModel or Page2ViewModel nor have I shown you the implicit DataTemplates I assume you will write for them.
Also I am assuming that your navigation bar (and MainWindowView in general) have a DataContext that is already set to the MainWindowViewModel
The implemention with a command button or a RadioButton would be quite different.
Comment: Thank you Joe for your thorough response. After reviewing, I decided to incorporate the "MainWindowRibbon" (which does not involve ribbon toggle buttons, which I may investigate now, but it was just unfortunate naming. I used regular buttons using ICommand in an ItemsControl template.) into the mainwindow. I suppose my greatest question now is how does the Content property access a xaml, with code behind, with a viewmodel class? i.e. what is the object type of the viewmodel? Sorry if I'm being a noob right now.
Comment: Are you suggesting that I create a datatemplate in the main xaml for each page? Sorry, I have most of the dots connected but not all
Comment: In answer to your second question, yes, I am suggesting you create a `DataTemplate` for each page.  The `DataTemplate` really *is* the page, at least in UI terms.  Meanwhile, the `Content` of each page is some sort of view-model object that, by itself, has no UI (e.g. some view-model class in your project).  This allows you to later add in new page types if you wish without changing the mechanism.  Basically you have to stop thinking of "content" in terms of UI/Controls and start thinking of it in terms of view-models.  DataTemplating translates the latter into the former.
Comment: WPF is meant to work this way, with templating.  You mentioned you used an `ItemsControl`, right?  Well that control works the same way except, instead of managing one `ContentControl` it manages many.  You bind an `ItemsControl` to a list of view-models somewhere stored in your code.  It shows you a list of `ContentControls`, one for each item in your list.  It has an `ItemTemplate` property that is the `DataTemplate` used to convert each list item into a UI.  So again, the items in your list are not UI controls, they're view-models.
Comment: Fantastic thank you so much, man. Now for the fun part of reworking the whole project :) Shouldn't be too bad though. Thanks again.

Handling Events in MVVM


How to use percentage padding top and bottom in React Native?

Question: I am trying to achieve dynamic padding top and bottom. I am aware that paddingTop and paddingBottom with % will use the width of the container and I am fine with that.
Unfortunately when I do set the paddingTop to any value with %, it sets the paddingBottom to the same value. Basically paddingTop: '5%', paddingBottom: '0%' will give me equal 5% paddings on both sides.
If I set paddingBottom to any % value - it's just being added to the value that came form the top. So: paddingTop: '5%', paddingBottom: '10%' results in paddingBottom equal to 15%...
I checked the same solution in a web project and there it works as expected.
The snack presenting the problem:
https://snack.expo.io/BJ9-2t8LB
The problem is on both Android and iOS.
How to solve it?
Answer: Apply the value to the child container to be applied, not to the parent container.
I have modified the answer according to the conditions you want. You should send Bottom's territory to the parent's container. Because they interact with each other in their child's container, they must be independent.
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.wrapper}>
        <View style={styles.inner}>
          <View style={{ backgroundColor: 'yellow' }}>
            <Text>TOP</Text>
          </View>
        </View>
        <View style={{ backgroundColor: 'red', }}><Text>BOTTOM</Text></View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  wrapper: {
    flex:1,
    paddingLeft: 24,
    paddingRight: 24,
    backgroundColor: 'green',
    paddingBottom:"5%"
  },
  inner: {
    flex:1,
    justifyContent: 'space-between',
    backgroundColor: 'blue',
    marginTop:"10%"
  },
});

Comment: Yeah, now you hit another variation of the problem here - the red box is not on the bottom. In this version there is a padding at the bottom equal to the marginTop height...
Comment: Should red be at the bottom of blue?
Comment: Yes, as per the web example in the snack. If you look on the code there is nothing adding any extra space there.
Comment: @Michal I've set the terms for you. Please look at the modified answer.
Answer: That is strange behavior, you should bring it up as an issue to react-native.
In the meantime, a workaround would be applying marginTop and marginBottom to the inner View, instead of paddingTop and paddingBottom to the wrapper View.
Answer: const styles = StyleSheet.create({
  ayz:{
    marginTop:"15%",
    backgroundColor:'pink',
    alignItems:'center',
    justifyContent:'center',
  },
  asd:{
    color:'white',
    fontSize:50,
    fontWeight:'bold'
  }
});

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Dificuldades ao pegar valores dentro de array

Question: Estou fazendo um código onde seleciono informações do banco e alimento uma array, na sequência estou tentando utilizar o conteúdo dessa array para comparar com outras informações e processar o restante do código.
Porém estou tendo dificuldades pra pegar os dados de dentro da array, abaixo meu código:
<?php
    $fuso    = mktime(date("H")-3, date("i"), 0);
    $hoje    = gmdate("Y-m-d", $fuso);
    //$resultado_array = array(); //sem o array
    $agendamentos = $dbh->query("SELECT * FROM agenda WHERE data_agendamento='$hoje'");
    while($row = $agendamentos->fetch(PDO::FETCH_ASSOC)) {

        if ($row['hora_agendamento'] == "08:00:00") { //agora com $row
            echo '
';
            echo '' . $row['hora_agendamento'] . '	';
            echo '' . $row['id_paciente'] . '	';
            echo '' . $row['observacao'] . '	';
            echo '' . $row['id_agendamento'] . '	';
            echo 'Editar	';
            echo '
';
        }
        else {
            echo '
';
            echo '08:00:00	';
            echo '	';
            echo '	';
            echo '	';
            echo 'Editar	';
            echo '
';
        }
        if ($row['hora_agendamento'] == "09:00:00") { //agora com $row
            echo '
';
            echo '' . $row['hora_agendamento'] . '	';
            echo '' . $row['id_paciente'] . '	';
            echo '' . $row['observacao'] . '	';
            echo '' . $row['id_agendamento'] . '	';
            echo 'Editar	';
            echo '
';
        }
        else {
            echo '
';
            echo '09:00:00	';
            echo '	';
            echo '	';
            echo '	';
            echo 'Editar	';
            echo '
';
        }

    } //while agora só termina aqui

    echo '

';
?>

No if caso encontre dentro da array a string ali determinada ele deveria preencher os dados abaixo, mas logo ao começar o if já apresenta o erro:

Notice: Undefined index: hora_agendamento in
  C:\wamp64\www\agendamentos\index.php on line 29

Claramente porque não estou conseguindo pegar os dados dentro da array, como proceder?
Comment: Mas a ideia era construir uma tabela com todos os agendamentos que tem hora `08:00` ? Ou apenas o primeiro ?
Comment: Todos, mas vai ter só 1 agendamento, não vou permitir mais de 1 agendamento no mesmo horário no mesmo dia. Nesse código ele tá sendo só um parâmetro pra quando encontrar na array esse horário, ele preencher a tabela com o restante dos dados daquela linha da array.
Comment: ja tentou usar o var_dump para verificar como ficou a estrutura do seu array??

Tente executar assim logo depois do while:
`var_dump($resultado_array);`  e veja o q retorna, se mesmo assim não encontrar o caminho para pegar o seu array, edita sua pergunta com o resultado do var_dump.
Comment: `hora_agendamento` não é um valor index da array. Valor index de uma array é um número (0, 1, 2, 3...).
Answer: O que está a tentar fazer não faz muito sentido. Está a guardar as linhas todas que vem da tabela num array:
while($row = $agendamentos->fetch(PDO::FETCH_ASSOC)) {
    array_push($resultado_array,$row); //<- aqui com array_push

Mas depois utiliza como se fosse apenas um objeto normal e não um array:
if ($resultado_array['hora_agendamento'] == "08:00:00.00000") {

Para utilizar como um array tem de especificar a posição, por exemplo:
if ($resultado_array[0]['hora_agendamento'] == "08:00:00.00000") {

Repare que indiquei posição 0 com [0].
Mas isto cria-lhe outro problema pois ou apenas usa o primeiro (e pode até nem existir!) ou tem de utilizar novamente outro while para utilizar as várias linhas. Melhor é mesmo utilizar o while que já tinha inicialmente e aplicar a lógica e escrita lá:

            Hora
            Paciente
            Observação
            Agendamento
            Editar

<?php
    $fuso    = mktime(date("H")-3, date("i"), 0);
    $hoje    = gmdate("Y-m-d", $fuso);
    //$resultado_array = array(); //sem o array
    $agendamentos = $dbh->query("SELECT * FROM agendamentos WHERE data_agendamento='$hoje'");

    while($row = $agendamentos->fetch(PDO::FETCH_ASSOC)) {

        if ($row['hora_agendamento'] == "08:00:00.00000") { //agora com $row
            echo '
';
            echo '' . $resultado_array['hora_agendamento'] . '	';
            echo '' . $resultado_array['id_paciente'] . '	';
            echo '' . $resultado_array['observacao'] . '	';
            echo '' . $resultado_array['id_agendamento'] . '	';
            echo 'Editar	';
            echo '
';
        }
    } //while agora só termina aqui

    echo '

';
?>

Comment: Meu código era exatamente assim(editei o post principal lá), porém como tu pode ver, quando existe if e else, quando o resultado se encaixa no else o código repete várias vezes o resultado, veja só quando não há registros para a hora 09:00:00: https://imgur.com/a/WMRaD
Comment: @FernandoGross Não pode estar dessa forma. Tem que ser o primeiro `if` para `"08:00:00"` depois `else if` para `"09:00:00"` e depois então o `else` normal. Essa seria a forma de fazer se quiser ter 2 casos e um terceiro para tudo o resto. Mas no seu código nem sequer consegui perceber a diferença entre os vários casos, pois parecem me iguais à exceção da hora. E a hora já é mostrada na tabela, logo o `if` nem parece ter sentido.
Comment: Meu deus, sou retardado haha... A ideia desses else if é preencher a tabela com os horários que tem dados no banco e os que não tem gerarem linhas em branco, depois ao clicar editar eu vou abrir um modal ou algo do tipo pra inserir um agendamento novo naquele espaço desocupado, por agora ele não faz muito sentido mesmo, e foi o jeito mais prático que eu achei pra fazer uma agenda que encaixasse no meu plano, pode haver outro jeito, mas usando o que eu sei aparentemente é isso aí.