Admin theme creation in Drupal

Question: I am new to drupal and I have a task to create a custom admin theme. I read a lot of tutorial to how to create a theme in drupal and I am familiarize with that. But never see how to create a new admin theme. I also wanted to customize the default <input type ="text"....> fields with custom css.
Thank you in advance.. :)
Comment: @NikhilM is right, there is no user/admin theme in Drupal. But in case you want to create a theme, that controls only admin display, where admin works, not the front end of website. You need to make any custom theme and set it **Administration theme**
Comment: FYI, there is nothing like `admin theme` and `user theme`, when you create one theme, you can use it on the whole site. `` can be customised with `input[type="text"]`. Also this is a good place to start https://www.drupal.org/documentation/theme
Comment: @Nikhil M thank you for your quick response. Its ok for me. But my doubt is how can I style my admin in a different way? I just try with style.css and its work, fine. But I don't know its the right thing. Is there any additional css need to modify the admin page?Especially the forms?
Comment: Why reinvent the wheel? That being said, if I had to do this, I would create a sub-theme of a really good existing Admin theme such as Adminimal, Seven, or Rubik.  That way you are up and running with all the admin theme features and then it's a simple matter of theming.
Comment: +1 @DannyEnglander, Thats good and well for a fresher as me. Now I follow the same
Answer: For Admin Theme

Create a custom drupal theme (its already answered).
Bring it to your drupal site.
Go to Home » Administration » Appearance, Select your theme in Administration theme select box and save
Answer: Create A Custom Theme/New theme (Drupal Tutorial)
This one shows how to create a Custom Theme for your drupal site.

Create custom.info file
Enable the theme
Create page.tpl.php and style.css file
Bring in the Drupal
Some refining
The final files

1. Create custom.info file

Create a folder custom in your sites/all/themes folder
Inside it create a file custom.info with these lines:

**name = Custom Theme
core = 7.x
engine = phptemplate**
2. Enable the theme

Go to Appearance and click 'Enable and set default' for the Custom Theme

3. Create page.tpl.php and style.css files

Create a folder templates in your sites/all/themes/custom folder
Inside it create a file page.tpl.php
Inside the page.tpl.php we create our html document for the layout.

4. Bring in the Drupal

Let's do the navigation first.
Go to Structure | Menus and add our navigation links in Main menu

for more details

Admin theme creation in Drupal


Count agrupando por semana

Question: Tenho uma tabela no MySQL e estou tentando agrupar ela por semana(pode ser semana do ano)
Select count(id),month(data_tarefa), year(data_tarefa) from tarefas group by mes, ano

Assim funciona legal, mas eu precisaria agrupar por semana, pesquisei e não achei uma função para retornar a semana do ano, se alguém tiver alguma dica agradeço.
Comment: de uma olhada aqui http://www.w3resource.com/mysql/date-and-time-functions/mysql-week-function.php
Comment: Tentei isso, mas não pareceu funcionar pra mim, de qualquer forma obrigado
Answer: Há uma função do MySQL que te dá uma concaternação entre o ano e a semana do ano, chamada YEARWEEK(). Use-a para ter o que você quer.
SELECT count(id), YEARWEEK(data_tarefa) anosemana
FROM tarefas
GROUP BY anosemana;

Count agrupando por semana


Relation between reciprocity laws and split places

Question: Let $F$ be a (totally real if necessary) number field and $E$ a (totally imaginary if necessary) quadratic extension of $F$.

Why are half the places of $F$ split in $E$?

I mainly do not grasp the relation between splitting and the reciprocity laws, I would like to relate it to the Hilbert symbol $(a,b)_v$, so that the product formula $\prod_v (a,b)_v$ for suitable $a,b$ would give the result.
So, is there any mean to characterize the splitting places by a property like $(a,b)_v = 1$?
Answer: The answer to your first question is supplied by Kronecker's density theorem: in a finite extension $L/K$ of number fields with normal closure $N/K$, the Dirichlet density of primes that split completely in $L/K$ (or, equivalently, in $N/K$) is given by $1/(N:K)$. The proof is easy, but involves the fact that the Dedekind zeta function $\zeta_F(s)$ of number fields $F$ has the property that
$(s-1)\zeta_F(s)$ has a finite nonzero limit as $s \to 1$. It is a special case of the better known Frobenius density theorem.
In the quadratic case $L = K(\sqrt{\alpha}\,)$, a prime ideal ${\mathfrak p}$
with odd norm splits if and only if $(\alpha/{\mathfrak p}) = 1$. You can express this Legendre symbol in terms of Artin symbols and then in terms of norm residue symbols, and the product formula allows you to write it as a product of symbols away from ${\mathfrak p}$;  I do not know, however, what you actually mean by the second part of your question.


URL_STRING não se preenche corretametne

Question: Estou com um problema na classe de consumo do meu WebService rest. No projeto existem apenas duas classes, a MainActivity está funcionando corretamente, mas a classe de consumo (ConsumoWS) não está entendendo meu método para preencher a url/uri que é enviado ao WS.
MainActivity:
package com.example.testedosbotoes;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity{

ConsomeWS post;
String nome;
String enderecoOI = "El/oi";
String enderecoOO = "El/oo";
static String enderecoGO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button bt09 = (Button) findViewById(R.id.id_btnovehoras);
        Button bt10 = (Button) findViewById(R.id.id_btdezhoras);

        bt09.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                MainActivity.setendereco(enderecoOI);

                  post=new ConsomeWS();
                  post.execute();
                nome = new String (post.getnome());
                if (nome !=null) {

                Toast.makeText(MainActivity.this, "começou", Toast.LENGTH_LONG).show();

                }

            }

        });

        bt10.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                MainActivity.setendereco(enderecoOO);
                post=new ConsomeWS();
                post.execute();
                nome = new String (post.getnome());
                if (nome !=null) {

            } else {
                Toast.makeText(MainActivity.this, "nao começou", Toast.LENGTH_LONG).show();
            }
        };
        });

    }

    public static void setendereco (String endereco){

        enderecoGO = endereco;

    }

    public static String getendereco() {

        return enderecoGO;
    }

}

ConsomeWS:
package com.example.testedosbotoes;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class ConsomeWS extends AsyncTask<Void, Void, String>{

    static String endereco;
    private static final String URL_STRING = "http://192.168.1.5:8080/"+endereco;

    String nome;

    @Override
    protected String doInBackground(Void... params) {

        endereco = MainActivity.getendereco();

                Log.i("hhhhhhhhhhhhhhhhhh", "solicitar endereco" + endereco);

        try {

            String resultado = consultaServidor();

            return interpretaresultado(resultado);

        } catch (IOException e) {

            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return null;
    }

        private String consultaServidor() throws IOException {

            InputStream is = null;

            try {
                HttpClient httpclient = new DefaultHttpClient();

                Log.i("IIIIIIIIIIIIIIIIIIIIIIIII", "solicitar endereco" + URL_STRING);

                HttpGet httpget = new HttpGet(URL_STRING);

                Log.i("JJJJJJJJJJJJJJJJJJJJJJ", "solicitar endereco" + URL_STRING);

                HttpResponse response = httpclient.execute(httpget);

                HttpEntity entity = response.getEntity();

                InputStream webs = entity.getContent();

                Reader reader = new InputStreamReader(webs);
                char[] buffer = new char[3999];
                reader.read(buffer);

                return new String(buffer);

                } finally {

                    if (is !=null){

                        is.close();
                    }

                }
        }

            private String interpretaresultado(String resultado) throws JSONException {

                JSONObject object = new JSONObject(resultado);

                return object.getString("resposta");

        }

            @Override
            protected void onPostExecute(String result) {

                setNome(result);

            }

            public void setNome(String result) {

                this.nome = result;

            }

            public String getnome(){

                return this.nome;
            }

}

Erro do logcat:
08-09 13:47:32.052: D/gralloc_goldfish(2570): Emulator without GPU emulation detected.
08-09 13:47:58.742: D/AndroidRuntime(2570): Shutting down VM
08-09 13:47:58.742: W/dalvikvm(2570): threadid=1: thread exiting with uncaught exception (group=0xb4a87ba8)
08-09 13:47:58.752: E/AndroidRuntime(2570): FATAL EXCEPTION: main
08-09 13:47:58.752: E/AndroidRuntime(2570): Process: com.example.testedosbotoes, PID: 2570
08-09 13:47:58.752: E/AndroidRuntime(2570): java.lang.NullPointerException
08-09 13:47:58.752: E/AndroidRuntime(2570):     at java.lang.String.<init>(String.java:443)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at com.example.testedosbotoes.MainActivity$1.onClick(MainActivity.java:39)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at android.view.View.performClick(View.java:4438)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at android.view.View$PerformClick.run(View.java:18422)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at android.os.Handler.handleCallback(Handler.java:733)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at android.os.Looper.loop(Looper.java:136)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at java.lang.reflect.Method.invokeNative(Native Method)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at java.lang.reflect.Method.invoke(Method.java:515)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-09 13:47:58.752: E/AndroidRuntime(2570):     at dalvik.system.NativeStart.main(Native Method)
08-09 13:47:58.762: I/hhhhhhhhhhhhhhhhhh(2570): solicitar enderecoEl/oi
08-09 13:47:58.762: I/IIIIIIIIIIIIIIIIIIIIIIIII(2570): solicitar enderecohttp://192.168.1.5:8080/null
08-09 13:47:59.112: I/JJJJJJJJJJJJJJJJJJJJJJ(2570): solicitar enderecohttp://192.168.1.5:8080/null
08-09 13:48:00.582: I/Process(2570): Sending signal. PID: 2570 SIG: 9

Observem que o logcat aponta que a URL_STRING está incompleta T_T (192.168.1.5:8080/null) quando deveria constar (192.168.1.5:8080/El/oi).
Answer: Resolvido!
Fiz a seguinte alteração na Classe, e funcionou \o/:
public class ConsomeWS extends AsyncTask<Void, Void, String>{

private static final String URL_STRING = "http://192.168.1.5:8080/"+endereco();

String nome;

private static String endereco() {
    String ender;
    ender = MainActivity.getendereco();
    Log.i("IIIIIIIIIIIIIIIIIIIIIIIII", "e ai" + ender);
    return ender;
}

@Override
protected String doInBackground(Void... params) {

    try {

        String resultado = consultaServidor();
        return interpretaresultado(resultado);

    } catch (IOException e) {

        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    return null;
}

    private String consultaServidor() throws IOException {

        InputStream is = null;

        try {
            HttpClient httpclient = new DefaultHttpClient();

            HttpGet httpget = new HttpGet(URL_STRING);

            Log.i("JJJJJJJJJJJJJJJJJJJJJJ", "solicitar endereco" + URL_STRING);

            HttpResponse response = httpclient.execute(httpget);

            HttpEntity entity = response.getEntity();

            InputStream webs = entity.getContent();

            Reader reader = new InputStreamReader(webs);
            char[] buffer = new char[3999];
            reader.read(buffer);

            return new String(buffer);

            } finally {

                if (is !=null){

                    is.close();
                }

            }
    }

        private String interpretaresultado(String resultado) throws JSONException {

            JSONObject object = new JSONObject(resultado);

            return object.getString("resposta");

    }

        @Override
        protected void onPostExecute(String result) {

            setNome(result);

        }

        public void setNome(String result) {

            this.nome = result;

        }

        public String getnome(){

            return this.nome;
        }

}

Logcat: 08-10 11:28:25.476: I/JJJJJJJJJJJJJJJJJJJJJJ(995): solicitar enderecohttp://192.168.1.5:8080/El/oi

XD.
Só que agora tem outro erro T_T

URL_STRING não se preenche corretametne


How to compress/minimize size of JSON/Jsonify with Flask in Python?

Question: I'm sending a huge JSON string (with jsonify in Flask) to my webpage pretty often, so I would like to reduce the data. The easiest option is probably to remove all line breaks and space characters, but just to give you an example of this:
Normal jsonify: 361KB
Removing all line breaks and space characters: 118KB (wow).
Zip the original file: 35KB (double wow).
So I basically wonder if there is an easy way to come close to the 35KB. I couldn't find  a solution so far which I could easily implement in python and javascript (to decompress).
Right now, I send around 4-5MB of data every second, which is - you guessed right - a "little bit" too much.
Answer: Old question but I was searching for this and it was the first result on Google. The link to the answer of Leon has a solution not for Flask and also it is old. With Python 3 now we can do all in few lines with the standard libraries (and Flask):
from flask import make_response, json
import gzip

@app.route('/data.json')
def compress():
    very_long_content = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
    content = gzip.compress(json.dumps(very_long_content).encode('utf8'), 5)
    response = make_response(content)
    response.headers['Content-length'] = len(content)
    response.headers['Content-Encoding'] = 'gzip'
    return response

With gzip.compress we have directly a byte string compressed and it is required as input a byte string. Then, as the link from Leon, we make a custom response saying that the content is a gzip so the browser will decompress by itself.
For decoding in Javascript using a JQuery ajax request there isn't any particular difference from a standard request:
$.ajax({
    url: '/data.json',
    dataType: 'json',
    success: function(data) {
        console.log(data);
    }
})

Note that this snippet compress and then send the long content. You should consider the amount of time that it takes to compress the content (especially in this case that we have very long content), so be sure to set an appropriate level of compression that doesn't require more time to compress + send than send the long content as it is.
My use case was that I sent the big content from a slow connection, so I had all the benefits to compress the content before send it.
Comment: In addition I also added a check that the request can handle gzip in a response:
`if 'gzip' in request.headers.get('Accept-Encoding','').lower()`
Comment: +1 to checking to make sure that the time for compression doesn't actually increase the load time. I implemented this and it actually increased the load time by 200ms!
Answer: Web requests do support GZip and you could implement it in python.
Here is someone who asked that exact question.
How to use Content-Encoding: gzip with Python SimpleHTTPServer
According to the flask-compress repo

The preferred solution is to have a server (like Nginx) automatically compress the static files for you.

But you can do it in flask: https://github.com/colour-science/flask-compress.
If you go the gzip route you will not need to remove line breaks and white space, but if you still want to then according to the flask documentation you can disable pretty print by setting JSONIFY_PRETTYPRINT_REGULAR to false.
Comment: Yes, I just found the DevTools - another reason why Chrome is awesome. There I could see that a 100KB response was only 16.8KB with the easy flask-compression extension. AWESOME. Thanks a lot.
Comment: Thank you very much for this great response - from the description it seems to me like flask-compress would be perfect, but since it's so simple to integrate I have no Idea if it is actually working.
Is there any way to test how much data is actually send / if the compression works?
Comment: If the url is publicly visible you can use something like http://checkgzipcompression.com/ otherwise using Chrome you can open developer tools and inspect your network traffic. The response should contain a header entry `Content-Encoding` which is set to `gzip`
Answer: If you're looking for a library to help serve compressed content via Gzip (or Brotli), try flask-compress. It's very simple; this might be all you need to do:
from flask import Flask
from flask_compress import Compress

app = Flask(__name__)
Compress(app)

Answer: Inspired by Ripper346's answer, but rather than manually writing it for all routes/views. It is just better to add a snippet(compared to external dependency on a library), which will compress the response before sending it out.
Add the following to your app file, or wherever suited(eg. gzip_compress.py):
import gzip
from io import BytesIO
from flask import request

class GzipCompress:
    def __init__(self, app, compress_level=9, minimum_size=100):
        self.app = app
        self.compress_level = compress_level
        self.minimum_size = minimum_size
        self.app.after_request(self.after_request)

    def after_request(self, response):
        accept_encoding = request.headers.get('Accept-Encoding', '')

        if response.status_code < 200 or \
           response.status_code >= 300 or \
           response.direct_passthrough or \
           len(response.get_data()) < self.minimum_size or \
           'gzip' not in accept_encoding.lower() or \
           'Content-Encoding' in response.headers:
            return response

        gzip_buffer = BytesIO()
        gzip_file = gzip.GzipFile(mode='wb',
                                  compresslevel=self.compress_level,
                                  fileobj=gzip_buffer)
        gzip_file.write(response.get_data())
        gzip_file.close()
        response.set_data(gzip_buffer.getvalue())
        response.headers['Content-Encoding'] = 'gzip'
        response.headers['Content-Length'] = len(response.get_data())

        return response

And then in your app:
from flask import Flask
from gzip_compress import GzipCompress

app = Flask(__name__)
GzipCompress(app)

You can set your gzip compression level and the minimum response size for compression to kick in. It includes other checks for gzip support and response codes.
Comment: Cool if you want to compress all the routes. Also, you could think about making a static function on GzipCompress to use it only when you want to compress sometimes. You will have all in one place
Answer: Spinoff of suvigyavijay's answer, without using awkward classes, io.BytesIO(), or gzip.GzipFile (he did a lot of heavy lifting though, props).
Note. This applies to all requests, I think.
import flask, gzip

app = flask.Flask(__name__)

@app.after_request
def compress(response):
  accept_encoding = flask.request.headers.get('accept-encoding','').lower()
  if response.status_code<200 or response.status_code>=300 or response.direct_passthrough or 'gzip' not in accept_encoding or 'Content-Encoding' in response.headers:  return response
  content = gzip.compress(response.get_data(), compresslevel=9)  # 0: no compression, 1: fastest, 9: slowest. Default: 9
  response.set_data(content)
  response.headers['content-length']   = len(content)
  response.headers['content-encoding'] = 'gzip'
  return response

Answer: The selected answer talks about Flask-Compress which is great at compressing. However, you may see that your JSON is still not stripped of new lines and indentation (esp when you're checking the output in debug mode).
Since JSONIFY_PRETTYPRINT_REGULAR is deprecated, to get this to work in the later Flask versions (2.2+), set:
app.json.compact = True

It took me some time to find this setting, so adding this here to avoid having to search for it.


How to prove perfectness of semidirect product of Lie algebras?

Question: Consider a semisimple Lie algebra S and a vector space V - considered as Abelian Lie algebra - with a non-zero irreducible representation $$\rho: S \rightarrow End(V).$$
$L$ and $V$ are finite-dimensional over the base field $\mathbb{R}$ or $\mathbb{C}$.
Then the semidirect product
$$L:= V \rtimes_\rho S$$
is a perfect Lie algebra, i.e. $[L,L]=L$.

How to prove this result?
Comment: Hints: What is $[S,S]$? What is $[S,V]$? conclusion?
Comment: @YCor I know $[S,S]=S$ and $[S,V]=V$. But given $(v,s)\in L$ and knowing $s=[s_1,s_2]$ how to find $v_1,v_2\in V$ with $\rho(s_1)(v_2)-\rho(s_2)(v_1)=v$?
Comment: check out the definition of $[L,L]$: it is by definition the set of sums of elements in the image of the bracket map, not only the image itself. So the problem is easier than you thought.
Comment: @YCor I apologize, but even with your hint I do not recognize the solution: My problem is the representation of a given element $v\in V$ by using fixed(!) elements $s_i$ from L.
Comment: No, your problem is "how to prove that $L$ is a perfect Lie algebra" (which means that every element is a sum of finitely many commutators). If your problem is whether every element of $L$ is a single commutator, or anything else, this is more difficult and you should edit your question.
Comment: @YCor I agree: My problem is perfectness, which means to represent an element $(v,s)$ as a sum of commutators. But to start, I assume $s=[s_1,s_2]$. How to represent an element $(v,s)$ as a sum of commutators, using $s_1$ and $s_2$?
Comment: You have $[S,S]=S$ and $[S,V]=V$, so $[S+V,S+V]=S+V$, that's it. What you're trying to prove is more complicated.
Comment: @YCor Thanks, I was lacking the equivalence of $\rho(S)(V)=V$ and $[S,V]_L=V$.
Answer: Solution thanks to the comments of @YCor:
Assume $L=V \rtimes_{\rho}S$. Then
$$L=V+S$$
with $S\subset L$ subalgebra and $V\subset L$ ideal. By definition of the commutator in $L$ holds
$$[S,S]_S=[S,S]_L.$$
Semisimpleness of $S$ implies
$$S=[S,S]_S.$$
Moreover
$$\rho(S)(V)=[S,V]_L.$$
Irreducucibility of $\rho \neq 0$ implies
$$V=\rho(S)(V)=[S,V]_L.$$
Then
$$L=S+V=[S,S]_L+[S,V]_L\subset [L,L]_L$$
The other inclusion is obvious.


Error installing homebrew in Apple M2 MacBook Pro

Question: I am trying to install the HomeBrew on my AppleM2 MacBook Pro 16GB / 256SSD
Step1: Download and install the Xcode 14.2
Step2: Download and install the Command Line Tools for Xcode 14.2.dmg file from the developer's site, i.e https://developer.apple.com/download/all/
Step3: I am trying to run the below command to install the homebrew in my MacBook Pro M2
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Step4: Then I am facing the below ERROR
curl: (28) Failed to connect to raw.githubusercontent.com port 443 after 75223 ms: Operation timed out.
I am not able to install cocoapods without fixing this home-brew installation error.
System Info:
MacBook Pro M2,
macOS Ventura 13.1,
Xcode 14.2,
Xcode command line tools 14.2.

Thanks in advance.
Answer: I am just changed my Internet connection and then I am tried then its working fine.
Cause: Due to low bandwidth / low service of my current internet provider.


Why does deploying to one app pool affect CPU usage of other?

Question: This is not an issue but I am asking out of curiosity as I didn't expect this behavior.
On the server, I have two copies of the web app. One copy at location dir1 is used mainly for testing and debugging purposes. The other at dir2 is the production site.
Earlier, both were using the same app pool. I changed it so that now the test one uses an app pool called testAppPool while the other uses DefaultAppPool.
Now, whenever I deploy a new build to test, the cpu usage of the w3wp.exe process of the DefaultAppPool also goes up. Why does this happen? Aren't they different processes and not be affected by changes in other?
Comment: is is the test dir a child dir of the production dir?
Comment: no, in fact they are on different drives.
Comment: no, they are under different virtual directories.
Comment: I believe that the DefaultAppPool gets restarted. One of the reasons is that many files get's changed.
Comment: Can you check if the application pool is restarted?
Comment: No, the app pool is not restarted. e.g. DefaultAppPool has memory usage of around 800,000K once at steady state. This does not change, but cpu goes up, remains up for a while alongwith test app pool(which gets recycled as expected) and then returns back to normal.
Comment: How many CPU's does your box have? Are you sure that there isn't a call in one app to the other?
Comment: Box has 2 cpu's. But how does that make a difference? Why would CPU usage of other worker process go up and not other processes? Call from one app to other, well I am not to sure what you mean by that. As I said, both are essentially the same code.
Comment: If the CPU is hyperthreaded then the CPUs/cores are not necessarily independent. If one app calls another (i.e. maybe you make a specific request for a resource within the app like a handler or similar, and it's configured to go to www.myapp-live.com rather than www.myapp-test.com, then loading one would also involve loading the other, if that makes sense?
Answer: In fact, a Virtual Dir in the prod also pointed to the test folder. This I found out today and that seems to be a reason.


Erro ao enviar requisição ajax

Question: estou fazendo um cadastro via ajax, e estou recebendo o seguinte erro:
Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.
Não realiza o cadastro, segue meus códigos:
var dataString = $(this).serialize();
                $.ajax({
                    url: "<?= BASE; ?>/modulos/index.php",
                    type: 'POST',
                    cache: false,
                    crossDomain: true,
                    dataType: 'jsonp',
                    data: 'action=enviar_ordens&' + dataString,
                    beforeSend: function (data) {
                        $('.msg_error').html('
Aguarde estamos enviando seu pedido...
');
                        $("#btn_order").attr('disabled', true);
                        $('#btn_order').text("AGUARDE UM MOMENTO...").attr({
                            title: "Aguarde... Enviando pedido!"
                        });
                    },
                    success: function (data) {
                        if (data.code == 'success') {
                            $('.msg_error').html('
' + data.msg + '
');
                            $("#btn_order").attr('disabled', false);
                            $('#btn_order').text("Enviar Pedido").attr({
                                title: "Enviar Pedido"
                            });
                        } else {
                            $('.msg_error').html('
' + data.msg + '
');
                            $("#btn_order").attr('disabled', false);
                            $('#btn_order').text("Enviar Pedido").attr({
                                title: "Enviar Pedido"
                            });
                        }

                    },
                    error: function (data) {
                        console.log(data);
                    }
                });

No meu PHP coloquei isto:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

Gostaria de saber se existe uma solução simples para corrigir e como eu faço?
Att,
Alisson
Answer: No PHP: /modulos/index.php deve mudar de:
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

Para:
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, X-Requested-With');

Pois o X-Requested-With é um header gerado pelo Ajax do jQuery, e como provavelmente você esta acessando de diferentes domínios este header precisará ser informado.

Adicional não diretamente relacionado a solução do problema com CORS
Vale notar que talvez nem precisaria passar os headers de Access-Control-*, pois acredito que seu Ajax e seu PHP estejam no mesmo host, mas talvez você tenha ajustado a constate BASE de maneira errada, então se o seu BASE:
 http://site.com

Mas estiver tentando acessar o site via
 http://www.site.com

Já vai falhar, precisoando configurar os Access-Control-*
Se o problema for isto, como www. e sem, então seria mais interessante configurar BASE para www. e impedir que os usuários acessem sem www., usando .htaccess para isto, por exemplo:
RewriteEngine On

# Adiciona www. no prefixo do domínio
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Comment: a minha constante BASE eu coloco sem o www. e está configurado com https://,
Comment: Sumiu os erros, mais agora minha requisição não funciona
Comment: @AlissonMaciel "não funciona" é bastante ambiguo, não concorda? Dá uma olhada no console do navegador e veja se ocorreu algum erro.
Comment: Bom, troquei o header que vc informou no php, removi o crossdomain, removi o cache e mudei o datatype para json, e agora voltou a funcionar, mesmo com a contante do jeito que está. Eu suponho, que o problema foi realmente o header, e como eu modifiquei o codigo jquery, para tentar corrigir, deu problema, mais eu tinha que mudar apenas o header e deixar o codigo como estava, enfim, voltou a funcionar e obrigado pela solução!

Erro ao enviar requisição ajax


What would be a good soloing/improvising strategy over "Comfortably Numb"

Question: I'm trying to figure out some strategy in the chorus section (the major sounding part), but am a bit confused.
Let's assume the chords in the background are D A in setion 1 and C G in section 2.
When playing over those changes i figured out that playing all the time in D major doesn't work (i guess because "C" is out of the triad) so i thought it's a key change in section 2 - and the obvious solution seemed to be: switch to C major. But it doesn't sound right.
What is it supposed to be in section 2 (C G)? G major/D mixolydian? Oddly enough target notes sounding best over this progression are not the root notes but 5th's: G (over C chord) and D (over G chord). Why is that?
Answer: There's some harmonic analysis of the part (chorus or 1st solo) in this video:

I personally agree with the commenters who argued that the best interpretation is actually

Ⅰ (D)
Ⅴ (D)
Ⅰ (D)
Ⅴ (D) - Ⅰ ⁄3 (G)
Ⅳ (G)
Ⅰ (G)
Ⅳ (G)
Ⅰ (G)

D
A
D
A - G ⁄B
C
G
C
G

instead of the rather more obvious

Ⅰ (D)
Ⅴ (D)
Ⅰ (D)
Ⅴ (D) - Ⅴ ⁄3 (C)
Ⅰ (C)
Ⅴ (C)
Ⅰ (C)
Ⅴ (C)

D
A
D
A - G ⁄B
C
G
C
G

Why? Admittedly it seems odd to not just say the modulation is a simple shift by a whole step down, seeing as both the chords and most of the melody notes can indeed be read that way. However,

A modulation from D-major to G-major is Co5ths-wise closer than a modulation from D-major to C-major. In fact it's basically the closest modulation you can possibly have: a dominant-to-tonic relationship. Thus, if all the notes that are sounding are consistent with either interpretation, then D→G is the "path of least resistance" way to hear it.
The melody does not exactly move a step down. The difference is just in one tone, but a crucial one: the very last of each line. That's in the first two lines of the chorus on the dominant's third, i.e. the main leading note that's a big part of characterising a dominant, but in the 3rd line it instead ends on the fifth, which is an open, voice-leading wise neutral tone.
I'm not completely sure if I'm hearing this right, but I think the accompaniment does contain an F♯ which fits in G-Major but not in C (unless it's Lydian). By contrast, in the first half those strings do not play a G♯ (they continue the same motiv instead of adding a new one on the last beat)

1st line:
X:1
L:1/8
M:C
K:D
%%score T1 T2 B
V:T1           clef=treble
V:T2           clef=treble
V:B            clef=bass
% 1
[V:T1] z2 d(d d2)  c(d   | d2)  cd  z e z (e | e2) c2 z4             | z8 |
[V:T2] afed  afed     | afed    afed    | aedc      aedc       | aedc    aedc |
[V:B]  D,8                | z4      D,4                | A,,8       | z8 |

3rd line:
X:1
L:1/8
M:C
K:G
%%score T1 T2 B
V:T1           clef=treble
V:T2           clef=treble
V:B            clef=bass
% 1
[V:T1] z cb,(c c2)  b,(c   | c2)  b,c  z d z ("!"d | d2) z2 z4             | z4 z3 b, |
[V:T2] gedc gedc | gedc gedc | gdcb, gdcb, | gdcb, g,b,d"!"f |
[V:B]  C,8                | C,8                | G,,8       | G,,8 |

Especially the second point is not very strong at all, and I don't say that the D-C interpretation doesn't make sense, however the D-G one does explain why you find it doesn't sound right to improvise over the second half in C-Ionian.
Comment: The transcription I have shows F# over the C major chord so whether you think of it as the IV of G or C Lydian it fits with the original one way or the other; not so thinking of it as C Ionian. Gilmour also avoids playing D over the C chord but often lands on D when the G comes around, which I only mention as a soloing strategy not as analysis. He seems to keep pretty well to pentatonic shapes in the recorded solo.
Answer: @leftaroundabout already mentioned the analysis on 12tone's YouTube channel. Here's a version of what I wrote in the comment section there - elaborating on something someone else wrote.
The core of the issue is this: two plain major triads that are a 5th apart do not determine a scale! This type of ambiguous harmonic pendulum, that can be either V-I or IV-I, is actually quite common in rock music.
I want to argue that the chorus in Comfortably Numb is basically a clever play with exactly that ambiguity. Since the harmony is ambiguous, we need to look at melodic elements for extra hints. In Comfortably Numb the vocals contain some pointers.
From a classical perspective, the vocals pretty much place the progressions D-A in D-major and C-G in C-major, as the relavant leading tones C# and B appear whereas G# and F# are absent. In more detail, during the C-G part the melody centers around C, the other notes being B and mostly D. There we have the leading tone in C-major and G is nowhere in sight. So all signs point to C as the tonic.
It's also interesting to note that the melody during the G-chord emphasizes D and never hits G. This roots the G-chord back to D-major and makes it a solid pivot from C-major to D-major. This is actually a fairly standard example of a modulation where a V becomes a IV. The slow pace of the music makes it extra smooth here - and generelly helps losing track of tonalities. The modulation from D to C is also driven melodically. The first time around, the melody ends on C# and instead of resolving up to D it resolves down to C. Other times it ends on E, which is already in C-major, but the C# is kind of implied by it's previous appearances.
While this "classical" analysis seems rather straight forward, there is one important thing that rock music tends to avoid: dominant seventh chords, the real driving force in classical music. And it's hard to argue that F wound sound anywhere near "right" over the G chord in Comfortably Numb. Maybe over C, if at all, but F# just seems to work better. (By the the way, I do not hear an F# played in the music.)
So let's take an even closer look at the C-G part. In fact, the use of B is rather subtle and you mainly notice C and D, the latter being the dominant tone during the G-chord - double entendre intended. Just before the chord changes to G, the vocals hit C and D (ignoring a brief detour over B). And since we're looking at a plain G-major triad - as opposed to, say, a dominant seventh chord - this may leave the impression of the root motion of a standard IV-V-I cadence in G-major.
To sum up, the vocal line during the C-G part is actually worse than ambiguous: it subtly points either way. Very clever! :-)
So what's going on? Hard to say. I'm personally leaning toward V-I in C Lydian. But another set of ears connected to another brain with different musical expectations might very well come to a different conclusion.
Comment: Interesting because to me the presence of B and D point to G tonality despite B being the C leading tone. Also the vocals don't have an F# but neither do they have an F natural so you could say the F# is never challenged in the listeners tonal memory but the C of course is. Finally during the solo there are definitely F#s, and G is a close key than C. But regardless I think for soloing it doesn't matter as much whether you're thinking G Ionian or C Lydian as long as you use those notes and focus on Ds when the G chord comes around.
Answer: If not a key change, then maybe a borrowed note.
Let's say you play the minor scale for a second. If you dig down one half-step below the root, that will be a borrowed-note (the 7th from the major scale). Metallica does this all day long. This also makes it harmonic/melodic minor for a second. In short, it's just a bunch of words for the same thing.
Or maybe a hybrid scale (when you commit to borrowed notes). Check out the modified blues scale (Velvet Revolver's "Slither").
I don't know the song, so I'm just throwing a few things out there.


How many fully diminished 7 chords do you get out of the harmonic minor scale?

Question: It is supposed to be only the 7th degree that gives us the fully diminished 7th chord but when I took a closer look today at the 2nd degree of the harmonic minor scale (Locrian 6) it seems to have an enharmonic equivalent of the a fully diminished 7th chord. The only difference is that the bb7 degree is a 6 in the Locrian 6 scale. So even though you spell this chord differently, isn't it still a full diminished 7 chord?
Answer: Well, a diminished vii evenly divides the 12-note octave into 4 parts.  Therefore, WHENEVER you have ANY dim 7 chord, you automatically have another 3.  So in C minor:
vii dim7 = b d f a♭
ii dim7 = d f a♭ c♭
iv dim 7 = f a♭ c♭ e♭♭ (or you can call it e♯ g# b d but then it's not really a 4 chord of c)
vi dim 7 = a♭ c♭ e♭♭ g♭♭ ( or g# b d f)
Comment: Exactly. All four inversions of a fully-diminished seventh chord are enharmonically equivalent (which is why the spelling is so important). thus, there are only three enharmonically unique such chords.
Answer: The 4 note chord based on the second degree of the harmonic minor scale is not diminished. It's m7♭5. Often referred to as half-diminished. But not fully diminished.
Let's take A harmonic minor. from 2nd note - B, D, F, A. Bm7♭5. To be Bdim., it would need the notes B, D, F, A♭. That Bm7♭5 may also be known as Dm6 in a different inversion.
Comment: A harmonic minor from second note also has notes B D F G#.. G# is enharmonic to Ab. I know this is spelt differently but how different is it really?
Comment: Count up in 3rds. B, D, F, A. Diminished, like a lot of other chords, have their intervals each one third apart from its neighbour. There is no Ab in that key anyway. The note numbers for the chord you reference are 2, 4, 6, 8. Not 2, 4, 6, 7.
Comment: Ok let me try this another way... play the notes B D F G#... what do you hear?
Comment: Obviously a fully diminished chord. Would you name Co as C, Eb, Gb, A?
Comment: no but would you stil be Tim if I had a nickname for you? What I am saying is, in practice isn't it the same thing?
Comment: I would only answer to Tim! No, in practice it isn't the same thing. A diminished chord needs each of its letter names to be the next-but-one from the list we call the scale. You're taking 'random' notes to make what sounds like a diminished chord, but certainly wouldn't be written on the stave as such. And, what should that 'A' note be called in Co?
Comment: Not random notes, those notes don't exist everywhere in that order, they exist in certain special places only. We write music on a stave to interpret what is heard/played so why does writing now dictate what the chord is or what it sounds like?
Answer: There are actually 3 different dim7 chords like the viidim7 in minor built by 4 minor thirds. After 3 semitones they are repeated  - if you consider the black and white keys on the piano.
To each tone of the 12 tones you can build a secondary vii7 dim (like there are secondary fifths in chord progressions). Theoretically there are 12 viidim7 - or even more if you regard the equivalent keys like F#/Gb or d#/eb ... etc.
But practically there are only 3 (and their inversions) to learn.


Automatic note splitting - missed stems

Question: Why are some stems missing?
\version "2.22.1"
\include "changePitch.ly"

nl = \break

chord_a = \relative c''' {<e gis c>}
chord_b = \relative c'' {<fis b d>}

root = {c d e f fis gis ais b}

motif_a = \relative {
\modalTranspose e e \root \chord_a
\modalTranspose e d \root \chord_a
\modalTranspose e c \root \chord_a
\modalTranspose e b, \root \chord_a
\modalTranspose e ais, \root \chord_a
\modalTranspose e gis, \root \chord_a
\modalTranspose e fis, \root \chord_a
\modalTranspose e f, \root \chord_a
}

motif_b = \relative {
\modalTranspose fis fis \root \chord_b
\modalTranspose fis gis \root \chord_b
\modalTranspose fis ais \root \chord_b
\modalTranspose fis b \root \chord_b
\modalTranspose fis c' \root \chord_b
\modalTranspose fis d' \root \chord_b
\modalTranspose fis e' \root \chord_b
\modalTranspose fis f' \root \chord_b
}

rhythm = {
c8 c4
}

iaa = \new Staff
\new Voice
\with {
\remove "Note_heads_engraver"
\consists "Completion_heads_engraver"
\remove "Rest_engraver"
\consists "Completion_rest_engraver"
}

{

\key c \major
\time 2/4
\ottava1
\changePitch \rhythm \motif_a \nl \ottava0
\changePitch \rhythm \modalTranspose e e, \root \motif_a \nl
%\changePitch \rhythm \modalInversion e'' e'' \root \motif \nl
%\changePitch \rhythm \retrograde \modalInversion e'' e'' \root \motif \nl

}

iab = \new Staff
\with {
\remove "Note_heads_engraver"
\consists "Completion_heads_engraver"
\remove "Rest_engraver"
\consists "Completion_rest_engraver"
}
{
\ottava1
\changePitch \rhythm \motif_b \nl \ottava1
\changePitch \rhythm \modalTranspose fis fis' \root \motif_b \nl
}

\bookpart {

\header {

dedication  =  \markup { \with-dimensions #'(0 . 0) #'(0 . 0) \with-color #(rgb-color 1 0.99 0.94) \filled-box #'(-10000 . 10000) #'(-10000 . 10000) #0 }
title = \markup { \vspace #4 \fontsize #1 \override #'(font-name . "Consolas") \eyeglasses }

}

\score {
\new GrandStaff
<<
\iaa
\iab
>>

\layout {}

\midi{ \tempo 4 = 120 }

}

}

\paper {
indent = 0\mm
left-margin = #21
right-margin = #21
markup-system-spacing.basic-distance = #30
}

Comment: I found resolution! I'm sorry.
`code
    \layout {
    \context {
    \Voice
    \remove "Note_heads_engraver"
    \consists "Completion_heads_engraver"
    \remove "Rest_engraver"
    \consists "Completion_rest_engraver"
    }
    }
`
Comment: If you can remove the parts of the code that aren't required to demonstrate the problem, it will make it much easier to diagnose.
Comment: @semiono Yes, either that or `\new Staff \new Voice \with { ... }`. The problem here is that most engravers handling such stuff sit on Voice level, so when the heads are created on Staff level the engravers acknowledging heads won't see them.
Answer: You add a Completion_heads_engraver to the Staff in \iab instead of adding it to a Voice context.  This results in the completed NoteHead grobs getting produced at Staff level where they escape notice of the Stem_engraver that sits at Voice level and does not get to see grobs emitted at Staff level.
You just need to write things for \iab like you did for \iaa, namely adding an extra \new Voice before the \with clause substituting the normal notehead engravers.

Automatic note splitting - missed stems


How to deal with "import cycle not allowed" while trying to install gonum?

Question: I'd like to use the gonum libraries for go in order to experiment with some neural network stuff but I cannot go past the install process...
I'm running the command found on the official gonum website :
go get -u -t gonum.org/v1/gonum/...

But it gives me :
import cycle not allowed
package gonum.org/v1/gonum
    imports runtime
    imports internal/bytealg
    imports internal/cpu
    imports runtime

Do you know what could be a reason for such a problem?
In case you need my go env in order to help me out, here it is :
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/me/go"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT="1"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

I'm running go 1.6.2.
Comment: Per the README, "Gonum supports and tests on the three most recent minor versions of Go." The current release is 1.12 so you may run into issues with versions older than 1.10, which you are far behind. Try updating Go and see if that helps.
Comment: Thanks a lot, your comment made me realize the issue : I had the package go-golang installed (from apt-get ) and it was used instead of the released version I got from the go website so I was using an old version of go which didn't allow me to import gonum. I just had to remove the go-golang package to make it work (I also took the time to upgrade the go version I was using).
Thanks a lot @Adrian !
Answer: As Adrian told in the comments, the issue was that the go version I was running was too old for gonum to install correctly. This was due to the fact that the go-golang package installed on my computer via apt-get was giving me the 1.6 version of go. By removing the package and making sure I had a recent go release installed on my computer I managed to install gonum.


How do I set an empty link title in a menu item?

Question: I'm using a fontawesome icon in a menu (with the tbmegamenu module) and I want to remove the text. Drupal forces me to enter something,   doesn't work so as a temporary solution I put at dot .
How can I remove the dot without resorting to very dirty CSS tricks?

See also the actual HTML at the website.

Entering an empty string in the menu title would be the cleanest way to get to a solution now.  Maybe it's possible with a hook that lets me put <none> in the menu title?
Answer: No need to resort to "dirty CSS tricks", you can just use clean CSS:
a.class {
  display: inline-block; // Or block if it makes more sense for your layout.
  text-indent: -9999em;
}

This is the correct way to handle it, as you can include proper text as your link (e.g. "Home"), so you're not alienating users with screen readers, etc.
Comment: Unfortunately that makes the home icon disappear as well.
Comment: ah, because it's using awesomefont, so the image is part of the text. duh. Can't you use a regular bg image? Or you could have a :after {content: ... position: absolute}
Comment: Right, I guess your icon's in a ``/`` tag or something? General wisdom would be to put that as a background image on the `` itself. You'll either need to use CSS to solve it (absolute position on the `` tag within the ``, for example), or you'll need to change the markup so you can better target the `` and its contents with CSS. There's no half-measure, Drupal won't be able to provide you with a solution unfortunately
Comment: maybe position: absolute on the  ?
Comment: @donquixote Yeah that would work, but we're more into the realms of "tricks" with that I think :)
Comment: actually what i tried jus tnow and worked was float:left and text-indent:0 on the , and text-indent:-1000px on the
Comment: You guys might be interested in [this answer](http://stackoverflow.com/a/12783507/2317532), which aims to replace the `-9999em` hack, which is ugly (and you know it!)  :p
Answer: What about

    This is the homepage

Comment: This would be the ideal solution, but I imagine there'll be some coding involved to override fontawesome's theme functions
Comment: It's a good solution but that leaves open where to put it. Now it's using TB Mega Menu but the idea is to get rid of that bloat.
Answer: If you use Icon API and Icon API:Menu submodule, You can just put <none> in the text field of the menu item.
fontawesome icons are available in the menu item properties with this module.
Answer: You can use FontAwesome menu icons module in Drupal 8.
After enable it, you get new options in each menu-item edit page:

A field for setting a fontawesome icon writting the code (fa-user, fa-sign-out,...)
Another field ("FontAwesome Icon - Appearance") where you can select "Without text" for an empty title.


Toda função retorna um objeto em Python?

Question: Em Python, é comum afirmar que todos os tipos de dados são objetos. Uma prova disso é que a própria referência da documentação afirma que "Todos os dados em Python são representados por objetos".
Sabendo que as funções sempre retornam algo (None, quando o retorno não é definido), seria correto afirmar que as funções são um tipo de objeto, que podem ou não realizar uma tarefa, mas que obrigatoriamente possuem um objeto como retorno?
Answer: Tem duas perguntas aí.
Toda função retorna um objeto, mesmo quando retorna None, ele é um objeto. O conceito matemático de função é sempre resultar em algo e Python respeita isso.
Quanto a uma função ser um objeto costuma ser mais complicado. Dentro da especificação da linguagem ela é. Pela característica dinâmica da linguagem você pode mudar tudo nela.
Essas linguagens, geralmente chamadas de script estruturam objetos como dicionários e por isso possuem bastante flexibilidade. Muita gente não sabe disto.
Algumas linguagens são tão flexíveis que tratam a própria função como um objeto. Eu sabia de algumas, mas não sabia de Python, agora sei graças ao hkotsubo abaixo.
E é um pouco estranho uma função não realizar uma tarefa. Até é possível fazer isso, mas não costuma fazer sentido em uma aplicação. Até pode fazer sentido em algum experimento ou um caso que tem a obrigação de ter a função por alguma razão que será chamada (portanto o nome tem que estar disponível) e tem um cenário que não deveria executar nada, mas não seria o normal na maioria dos cenários de uso da mesma função.
Comment: @Maniero, voce diria que as identity functions da programacao funcional (que simplesmente retornam o argumento recebido) realizam uma tarefa ou não?
Comment: O [Data Model do Python](https://docs.python.org/3/reference/datamodel.html#user-defined-functions) diz que "*A user-defined function **object** is created by a function definition*".

E em vários pontos usa-se o termo "*function objects*" para se referir às funções.

Eu entendo então que funções são objetos sim.
Tanto que elas têm um método (`__call__`) e podem ter atributos: https://ideone.com/A2RHI4
Comment: Eu concorco com você quando diz que uma função não é um objeto. Do meu ponto de vista, funções seriam semelhantes a loops e condicionais, ou seja, uma estrutura que te permite coordenar as instruções do código, por exemplo, receba estes parametros, realize estas tarefas e retorne estes valores, Você concorda ? Porém, de acordo com o que observo, o correto seria que funções são um tipo de objeto que retorna outro objeto. E referente a realizar tarefas, um função pode ser declarada sem argumentos ou instruções e mesmo assim ela,por padrão, vai retornar None. Estou correto ?
Comment: @LuisJr. não diria que são bem iguais. Está correto na última afirmação.
Comment: @bfavaretto boa questão, eu teria que analisar mais profundamente.
Comment: @hkotsubo é verdade, dei uma consertada.
Comment: @hkotsubo E da mesma forma que as funções, os dicionários também podem ser considerados objetos. Eu acredito que essa flexibilidade permite enormes contribuições para a propria linguagem, porque se todos os tipos são objetos e você tem acesso aos construtores, você pode debugar e melhorar a linguagem com mais liberdade. Eu me considero novato em programação e te agradeço muito pelo comentário, expandiu minha visão.


Complex Integral $\int_{-\infty}^{+\infty}\frac{e^{(-A\sqrt{x^2+B}+Cix)}}{\sqrt{x^2+B}}$

Question: I am confused calculating the below integral:
$$\int_{-\infty}^{+\infty}\frac{e^{(-A\sqrt{x^2+B}+Cix)}}{\sqrt{x^2+B}}dx$$
Where A, B, C are real and A and B are positive. I don't think I can use roots of the denominator and calculate residue at those points. Please let me know if you need further information. Thank you !
Edit: Bases on what suggested (Thanks to Zachary), I changed my focus on calculating below integral:
$$\int_{-\infty}^{+\infty}e^{(-A\sqrt{x^2+B}+Cix)}dx$$
where I considered $Cix=cos(Cx)+isin(Cx)$ considering even/odd function properties, I ended up with:
$$2\int_{0}^{+\infty}e^{(-A\sqrt{x^2+B})}cos(Cx)dx$$
At this point, I applied a change of variables as $x'=\sqrt{x^2+B}$, doing so, I come up with below:
$$2\int_{0}^{+\infty}e^{(-A\sqrt{x^2+B})}cos(Cx)dx=2\int_{0}^{+\infty}e^{(-Ax')}cos(C\sqrt{(x'^2-B)})\frac{x'}{\sqrt{x'^2-B}}dx'$$
Then, I was thinking of changing another variable $x''=sin(C\sqrt{(x'^2-B)})$ to get:
$$2\int_{0}^{+\infty}e^{(\frac{-A}{\sqrt{C}}(\sqrt{arcsin(x'')^2+BC}))}dx''$$
Not sure, if it makes sense, please advise, Many thanks.
Comment: How about taking $-\frac{d}{dA}$ of your integral, which lets you compute a simpler integral in exchange for solving a separable differential equation?
Comment: Call your integral $I(A)$. Then differentiating under the integral sign, you obtain that $-I'(A)=\int_{-\infty}^\infty dx\, \exp\left(-A\sqrt{x^2+B} +Cix\right)$.
Comment: Probably, I should use the same contour ?? as https://math.stackexchange.com/questions/2261015/calculate-int-infty-infty-frac-coskx-sqrtx2a2-dx?rq=1
Comment: Hi Zachary, Thanks for your comment. Unfortunately, I cannot envision what you mean by taking $-\frac{d}{dA}$, I appreciate if you can elaborate more on that.
Comment: Ah I get what you mean. Let me see if it works. Thanks
Comment: I am now working on that but whether or not it works, I should admit, your idea was brilliant. Thanks
Answer: This is not a complete answer, but a long comment on an upper  bound that I found for your integral. Let $B=u^2$. Indeed, substituting $ x\mapsto u\sinh z$ (as done similarly here), $-I'(A)$ reduces to
$$2u\int_0^\infty\cos\left(uC\sinh z\right)e^{-Au\cosh(z)}\cosh(z)\,dz$$
This is roughly the Fourier Transform of the second modified Bessel function's  "density". Indeed, this function has the integral representation
$$K_1(x)=\int_{0}^\infty e^{-x\cosh(z)}\cosh(z)\,dz.$$
The triangle inequality tells us that
$$-I'(A)\le 2u\,K_1(Au).$$
We know that $-I'(A)>0$ from the integral, as well as $\lim_{A\to\infty} I(A)=0$. Hence, integrating, you find that
$$I(A)\le 2K_0(Au),$$
where $K_0(x)$ is the second modified Bessel function of null order. This shows you (although we could have seen this above) that $I$ is best viewed as a function of the dimensionless parameter $s=Au$ (as well as of $uC$ but we will ignore this dependence here).
In particular, you now know that
$$I(s)=\mathcal{O}\left(\frac{1}{\sqrt{s}}e^{-s}\right)\qquad \text{as } s\to\infty$$
thanks to the asymptotics of the Bessel functions.
I am not sure about the existence of a closed-form, but if I find one I will edit my answer.


AWS S3DirectoryInfo Delete() not deleting

Question: I have a pretty straight forward call to delete a folder and all its contents from S3.
The Call
var response = gfAwsClient.S3DeleteEvent(Globals.globalEventPathAWS, "fgevents-lowres-dev", clouddir);
The method is:
public async Task<string> S3DeleteEvent(string basedirectory, string bucketName, string folderName)
            {
                if (folderName != null)
                {
                    var dirInfo = new S3DirectoryInfo(client, bucketName, basedirectory + folderName);
                    dirInfo.Delete(true); //set to true to delete everything inside too
                }
                return null;
            }

The value of the concated basedirectory + folderName = "/Events/01/999/001/"
And the value of dirInfo = {fgevents-lowres-dev:\/Events/01/999/001/\}
It executes, but nothing seems to happen, I get no errors thrown, and I don't even see how to return a good or bad response back.
Comment: Try `Events/01/999/001/` or `/Events/01/999/001` or `Events/01/999/001` (in that order) instead of `/Events/01/999/001/` - does that fix anything?
Comment: Yup that was it.  The leading / I had in the beginning was screwing it up.
 It's Events/01/999/001
Comment: You're welcome :) enjoy using AWS and .NET!
Answer: It does not want the leading "/" as the root.
So for the path I used:
Events/01/999/001

The full call is:
    string basedirectory = @"Events/01/";
    string folderName = @"999/001";
    string pathToDelete = Path.Combine(basedirectory, folderName);
                    var dirInfo = new S3DirectoryInfo(client, bucketName, pathToDelete);
                    dirInfo.Delete(true); //true deletes all files and current folder


Exibir Toast em classe que não é da activity

Question: Gostaria de exibir um Toastquando o usuário fizer logout.
Tenho esta estrutura:

Dentro de ConexaoFirebase, tenho um método chamado logOut:
public static void logOut() {
    firebaseAuth.signOut();
}

e dentro da classe PerfilActivity, tenho um método que chama o logOut():
private void eventoClicks(){
    btnLogOut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ConexaoFirebase.logOut();
            finish();
        }
    });
}

Gostaria que toda vez que fosse feito logout, fosse exibido um Toast, então tentei o seguinte:
Dentro de ConexãoFirebase, criei um método chamado alert:
private void alert(String s) {
    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}

e dentro de logOut chamei o alert passando a mensagem que quero que seja exibida, mas meu código ficou com erro:

Qual a maneira correta para fazer exibir a mensagem?
Sei que poderia fazer o Toast dentro de CadastrarActivity, mas gostaria de fazer dentro da classe ConexaoFirebase.
Comment: A questão é que o `Toast` vai ser exibido numa `Activity` ainda que o ponto de partida no mesmo não seja uma `Activty`. Logo apenas tem de passar o contexto dessa `Activity` onde quer lançar o `Toast`
Comment: Passe o `context` para os métodos `logOut` e `alert`: Ex: `ConexaoFirebase.logOut(context);`. e também `alert(context, "Mensagem");`
Comment: Poderia me dar um exemplo melhor? ainda não manjo de programação.
Answer: public static void logout(Context ctx) {
    auth.signOut();
    alert(ctx, "...");
}

private void alert(Context ctx, String s) {
    Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
}

O método logout recebe o parâmetro Context e depois passa para o método alert que vai exibir o seu Toast. Basicamente, todo Toast vai necessitar de um Context para poder ser exibido.
ConexaoFirebase.logout(getApplicationContext());
Answer: para criar um toast fora de qualquer activity ou seja em uma clase separada mas que vai ser chamada pela activity so basta usar na activity uma variavel publica do tipo context x:exemplo
basta chamar na clase
nome_da_activity act = new nome_da_activity();
toast.maketext(act.x, msg, toast.length_long).show();
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Variável estática em Python

Question: Vim do Java. Tenho uma variável numa classe que preciso mudar em mais de um método.
Tentei colocá-la global, mas consome muito recurso.

Como implementar isso?
Seria a mesma forma que uma variável estática em Java?
Como modificar var de outra classe no Django?
var = 0
def metodo1():
var += 1
def metodo2():
var += 10

[Resolvida]
Obrigado pela resposta do colega abaixo. Resolvi da seguinte forma:
Criei uma classe 'estática':
class Modulo(object):
    andamento_processo = 0
    def processo(self):
        self.andamento_processo = 1

Agora eu instancio ela da outra classe e altero o valor quando precisar, é literalmente como se fosse uma variável estática (do java)!
class NovaClasse:
    Modulo.andamento_processo = 10

Comment: Cuidado com varíaveis criadas no corpo de classes em Python: são atributos da _classe_ e não atributos das instancias, como em Java. O exemplo acima e da resposta funcionam, mas funcionariam sem as variáveis de classe - recomendo deixa-las de fora se não forem exatamente o que você quer. (E não, uma variável "global" em Python é apenas um atributo do objeto módulo, não é algo tão "terrível" como uma variável global em C. Ter uma classe só para ter um atributo que você pode modificar pode ser uma prática ruim em Python. Ou pode ser uma boa no caso de vários grupos de variáveis no mesmo módulo
Answer: A Orientação a Objeto no Python é um pouco diferente. Se você cria uma variável ela por padrão fica acessível. A diferença é a seguinte: Se a variável for acessada por uma instância do objeto, ela é atributo do objeto, caso contrário ela é atributo da classe.
Exemplo:
class A(object):
   variavel = 1

Dessa forma é de objeto:
objeto = A()
objeto.variavel

Dessa outra forma já seria um artificio bem parecido com o do Java (como você quer):
A.variavel

Para tentar deixar mais claro, imagina que sua classe tem um inicializador que muda o valor da variável de 1 para 5. Quando chamar o primeiro código que mostrei vai ser retornado 5, se o segundo código for chamado, vai retornar 1.
#!/usr/local/bin/python2.7

class A(object):
  variavel = 10

  def __init__(self):
    self.variavel = 15

print A.variavel #resultado 10
print A().variavel #resultado 15

Fonte para mais informações:
Static variables and methods in Python

Variável estática em Python


How to access the parent collection in a each closure?

Question: I'm looking from something that to replace the *parent*.
%w[apple apples].each do |w|
   next if *parent*.includes? w + "s"
   puts w
end

# output: apples

Comment: you could try a different enumerable function than each, find_all would work well for you here: `%w(apple apples).find_all{|fruit| fruit if fruit.match(/s$/)}`
Comment: @Jed: That doesn't do the same thing. (Also the `fruit if` part is unnecessary)
Comment: @sepp2k, sorry forgot 'puts' in the block which is why you would need the postfix if,( `...find_all{|fruit| puts fruit if fruit.match(/s$/)}`
Comment: @Jed: But then the result of `find_all` will just be the empty array.
Answer: There's no way to do that. You'll have to give the collection a name first:
fruits = %w[apple apples]
fruits.each do |w|
   next if fruits.includes? w + "s"
   puts w
end

Comment: `Object#tap` (v1.9+) may effectively name the collection, but it does restrict the scope of the variable: `%w[apple apples].tap { |f| f.each { |w| puts w unless f.include? w + "s" } }`.
Answer: each is a convention, there is no concept of a "parent collection" for blocks in general or ones passed to each in particular. Just name it, eg
(parent = %w[apple apples]).each do |w|
  next if parent.includes? w + "s"
  puts w
end

You could add a different method to pass a parent,
eg
module Each2
 def each2
   each { |elem| yield(self, elem) }
 end
end

include Each2

%w[apple apples].each2 do |parent, w|
  next if parent.includes? w + "s"
  puts w
end

But this is pretty silly.


Parâmetros para regras de negócio cadastrados no banco de dados

Question: Boa noite,
Recentemente me deparei com uma situação que me deixou muito em dúvida, é módulo de um sistema que calcula o valor a ser pago por um serviço e para isso todas as regras estão expressas em uma tabela no banco de dados, para exemplos vamos imaginar a tabela abaixo.

Vamos imaginar que são muitas regras que estão cadastradas e que esses são parâmetros para verificar se o valor a ser pago pelo serviço é inteiro ou apenas a metade, quero a opnião sobre como vocês implementariam tal caso.
O que que já passou na minha mente ?
Implementar um objeto RegraDeCalculo e no método calcularPagamento do objeto Servico ele iria receber como parâmetro o RegraDeCalculo, exemplo:
<code>$servico = new Servico(etc...);
$valorServico = $servico->calcularPagamento($regraDeCalculo);
//$regraDeCalculo consegue consultar o banco em busca da regra específica para o serviço
</code>
Realmente estou bem perdido já agradeço qualquer ajuda.
Answer: Expressar regras de negócio em colunas de uma tabela no banco de dados não é uma boa prática. Se você precisar mudar algo na regra, irá ter que mudar a estrutura de seu banco e isso provavelmente quebrará seu código.
Acredito que você esteja indo pelo caminho certo. Eu separaria as regras por tipo em uma classe a parte, com métodos com uma única responsabilidade cada, de modo que se você precisar mudar algo, você só vai precisar alterar uma ou outra linha de código.
Comment: Muito obrigado, tirou minha dúvida.


Mikrotik simple queue

Question: We're a tiny newbie internet provider and we use mainly mikrotik (SxT 5) for our clients.
We use PPTP tunnels to establish connection and offer internet.
We want to limit the upload speed, so we are gonna use a simple queue to do it, the question is.  What is best to establish the queues on our edge router for all of our clients, or to implement the simple queue on each client antenna (SxT 5)?
What are the pros and cons of each set up?
Many thanks
Comment: PPTP is insecure and should not be used any longer. Not an answer to your question, but worth mentioning.
Answer: It depends how many clients are you talking about?
having all queues in one router is easier to config and maintain.

But Queuing consume some CPU, resulting reduction of performance in large
  scales.

Another disadvantage is you have to limit based on IP, but on client side you can limit based on ports.
(due to the fact that if you just limit by port on your side (infrastructure side) you might limit your access to the SXT client router)
Sometimes ago, we had similar "mikrotik connected clients" (around 20 of them) and we preferred to do it on the edge side (last mikrotik conneceted to the client).

Mikrotik simple queue


How to get experience as a young conductor?

Question: Firstly, sorry if this question is off topic. I thought this would be the best place to post it.
I'm a teenage composer. I've written a few orchestral pieces before, and I also am fluent at playing a  variety of instruments. I'm interested in getting into conducting, however, I see no way that anyone would allow me to lead a volunteer orchestra without any previous experience (with no degree etc.).
Am I just trying too much too soon? Should I give up hope, or should I ask some volunteer orchestras around if they would consider me as a conductor? We have several adult and youth orchestras in the surrounding area. Is there any way to get experience in conducting without a degree in music?
Comment: Do you currently have any music tuition? For instance at school or college? If so, anyone who conducts a choir or instrumental ensemble at such an institution may be able to help you best. Often orchestras, choirs or other ensembles have SECTIONAL rehearsals, where a small part of the group rehearses separately; this could be a good starting point. But, I must stress, you really need to learn how to conduct first. As I say, you wouldn't expect to turn up and play violin in an orchestra if you had never had any violin lessons...
Comment: You don't need to "lead" an orchestra initially. Firstly, you need to learn how to conduct, in just the same way you would learn to play an instrument. Then you can gradually build experience, by conducting small, medium, then larger ensembles. Think of it this way: you wouldn't learn how to play an instrument by turning up with that instrument at an orchestral rehearsal and asking to play a concerto with them...
Comment: Practically speaking.. would I just ask to help out with a small ensemble? I mean, since most already have conductors.. how do I go about that practically?
Answer: Certainly don't give up hope! If you are excited about conducting, then you are already on your way to being a conductor. Realistically, though, learning to conduct is similar to any other musical discipline; you need to study how to do it. This doesn't mean you need a music degree though. If you already know of adult and youth orchestras, ask to sit in on on rehearsals, to experience the process of conducting and rehearsing an orchestra. Also, you should get in contact with the conductors of these orchestras, either for advice about study, or to take private tuition. Lastly, orchestral conducting may not be the easiest route into conducting for you. You can learn a lot about conducting by directing much smaller, chamber ensembles. Choral conducting may offer a route into gaining conducting experience, too.
You will learn how to conduct far more easily if you take conducting lessons. As soon as you start doing this, you should aim to put your skills into practice; you could even start by asking a couple of fellow musicians to allow you to conduct them playing duet music. Sure, they could probably do this on their own, but in such a situation you would be asking them to respond to your musical interpretation, performance instructions, and ideas in rehearsal. No ensemble is too small for you to start learning to conduct...
Answer: Have you NOT approached local orchestras already?  Come on - as God said to the man who prayed for a lottery win: "Give me some help!  BUY a lottery ticket!".
You could start by joining as a player.  Then ask if they'll let you run through one of your compositions.
Music is a profession where a degree is only relevent when applying for a teaching post.  Mostly, you just have to be able to do it.


Checking if personal contact form exists

Question: I am using a custom user-profile.tpl and I want to add a 'contact user' link to the viewed users personal contact page.
How can I check that the user in question has a contact page enabled? Is there a variable I can look at, or maybe a db query that can be run?
I am not using tabs on the user profile page.
Thanks,
Paul.
Answer: This is taken from contact.module:
<code>function _contact_personal_tab_access($account) {
  global $user;

***snip***

  // If the requested user has disabled their contact form, or this preference
  // has not yet been saved, do not allow users to contact them.
  if (empty($account->data['contact'])) {
    return FALSE;
  }

***snip***

  return user_access('access user contact forms');
}
</code>
You should be able to see in the user object whether or not they have they are allowing people to contact them. This will also be empty if they don't have a contact form.


Absolute Block Behaviour

Question: I have the following HTML snippet:
Block 1:

Block 2:

Block 1 is an ordinary absolute positioned DIV, while in block 2, the same DIV is enclosed within a relative positioned DIV.
My problem is, on Block 2, the absolute DIV inherits the width property from its parent, thus rendering the child DIVs on top of each other. Compare that to Block 1 where the child DIVs are floated side by side properly (because maximum allowable width is assigned).
Is there any fix for this situation? The height and width given are arbitrary and can change at any time. The child DIVs shouldn't set any width because the content keeps changing (I put some here for illustration purposes). I can set a certain width, but people with different browsers and DPI settings keep getting different result, so it's best to keep the child DIVs' width unset.
Update for bounty:
The intended usage of the above HTML is similar to the following:
Block 2:

    Main Text

                Item 1: Left Column, Line 1

                Item 2: Left Column, Line 2

                Item 3: Left Column, Line 3

                Item 4: Right Column, Line 1

                Item 5: Right Column, Line 2

Notes:

leftcolumn and #rightcolumn width is not static, so there's no specific width that can be set. The width should follow the longest text (each item in a single line).

I can set #columncontainer width to a specific width (which I am doing right now), but if the text is too long, then the left-right column is messed up (#rightcolumn below #leftcolumn, which is correct because of not enough space).
main width is set to a specific width, which in all possible case will be much less than #columncontainer width.

I'm open for JS solution, as that may seem to be the only consistent solution I can think of.
Comment: Just so I get this right: You want two columns of unknown width next to each other, within a container which is most likely more narrow than the combined column width? With no line-break? Are overflow:hidden or overflow:auto; viable options?
Comment: #main will always be more narrow, #columncontainer will need to fit both #leftcolumn and #rightcolumn, overflow: hidden and auto is not viable (because we need the content to be visible and there's a background that needs to fit the content).
Answer: In Block 2, the absolutely positioned div doesn't strictly inherit its width from its parent. If that were the case, setting its width to auto would do the trick. Instead, its relatively positioned parent has become its "containing block", establishing a context inside which the absolute div lives, so to speak.
The only way to "break out" of that containing block is to set a width on it so it overflows, as you were doing. If you set that width to a value that will usually be good enough, you could further control how the floats inside it behave by setting (percentage) min-width and max-width values on them.
But do you really need the #columncontainer div to be inside #main, other than to position it relative to #main's coordinates?
What you could do instead is make them siblings in a common parent div (the rest of the CSS remains the same):

...

...

Comment: Hmm... splitting the #main content into a sibling DIV to #columncontainer does make it work. But it will create a different problem. But to be fair, this was not in the question.
Comment: Thanks! I'd be happy to help fix any remaining problems if you need. I'd rather give an answer that actually works than one that only works in theory.
Answer: The width of the two inner divs 50 and 100 is wider than the enclosing 60px div. Is it necessary to set the enclosing div to 60px? If you remove the width and height restriction then the inner divs will occur next to each other as desired. Otherwise set the width of the div to a number higher than 60, lets say 110px so that the inner divs have room to be side by side.
Comment: The enclosing DIV will most likely to have less width than the child DIVs combined. While this is easy to solve the problem, it will create problem elsewhere (and more prominent, too).
Comment: You are looking at height.  The width is 50px and 100px.
Answer: I think the best way to do it is instead of defining width in pixels, do it in percentages. What will happen is that if you set each to 50% (or 49%), they will both be next to each other. Given that the largest the content can get is 100%, giving each box 50% should work out nicely, unless one side should sometimes be larger than the other.
Edit: Just saw the fact that each needs to be on a single line, which means that one side might be bigger than the other, so my solution might not work.
Comment: You're right, it won't work. I can't set the width explicitly on the #leftcolumn or #rightcolumn since I don't know the width (it should accomodate the longest text).

Absolute Block Behaviour


Should I protect a struct object with mutex?

Question: I use 4 go routines to assign different member variables of a struct instance. Each member variable is only accessed by one go routine.
Do I need to add mutex when accessing the struct instance?
I am not sure if the 4 go routines access the same memory. I feel I should be cause all of them accesses the holder.
This code demonstrates what I'm doing.
<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    var res Response

    var mu sync.Mutex

    wg.Add(1)
    go func() {

        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.A = []string{"a"}
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.B = "b"
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.C = 100
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.D = map[string]string{
            "d": "dd",
        }
    }()

    wg.Wait()

    fmt.Println(res)

}

type Response struct {
    A []string
    B string
    C int
    D map[string]string
}
</code>
Comment: If the goroutines access independent fields, then no.
Answer: You do not need a mutex for this program. As far as the Go memory model is concerned, separate fields of a struct are separate variables. Since the four goroutines are accessing four separate (sub-)variables, there is no data race, even without the mutex.
You can verify this by removing the mutex and running your program with the race detector enabled: https://golang.org/doc/articles/race_detector.html


Sporting events held more than 4 years apart

Question: The Olympics are held every 4 years and all other major sporting events (soccer and rugby world cups etc.) are held on 4 year cycles to avoid clashing with the Olympics.
Are there any sporting events held regularly more than 4 years apart?
Comment: Also, this; http://history.stackexchange.com/questions/9564/why-have-major-sporting-events-been-held-every-4-years
Answer: At least two Swiss Wrestling (Schwingen) competitions are held every 6 years.
The Umspunnen-Schwinget in Interlaken is held every 6 years. The last events were in 1999, 2006 (the 2005 event was postponed due to rain) and 2011. The next event will be in 2017.
The Kilchberger Schwinget is also held every 6 years, with the last events in 2008 and 2014, and the next to be held in 2020.
It is interesting to note that the biggest event, the Eidgenössisches Schwing- und Älplerfest is held every 3 years. Schwingen is not an Olympic sport, so there is no need to synchronize with the Olympics, but it may be an advantage for local festivals to avoid clashing with the national festival.
Answer: Over the years the Rugby League World Cup has ranged from every 3 years up to every 8 years.  The most recent gaps being 8 years from 2000 to 2008 and then 5 years to 2013.  However, due to the switch in hemispheres, the next world cup will be a more traditional 4 year gap.


TypeScript Breaking the loop after entry is found

Question: This is more of a How to make this better type question then it is that this is completely broken.
I read now that Typescript doesnt allow for a Foreach to be broken so is there any other loops that allow data access of the current entry and then have it break once that is found and set:
 login(surName, passWord){
    const name = this.members.find( x => x.surname === surName)
    const pass = this.members.find( x => x.password === passWord)
    if(name && pass){
      this.members.forEach(element => {
        if(element.surname = surName){
            this.persist.setPersistence(surName, element.color);
            return;
        }
      });
    }else{
      alert("User Details are incorrect please make sure your username and password is correct");
    }
  }

Once the surname and members color are found I want the loop to end this is scuffed so im curious what your take on this would be
Answer: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
Early termination may be accomplished with:

A simple for loop
A for...of / for...in loops

example:
for (const element of this.members) {
    if(element.surname === surName){
        this.persist.setPersistence(surName, element.color);
        return;
    }
}

Comment: Ah Ya that makes a bit more sense thank you


Four questions about the propagation of errors

Question: This question overlaps with physics and statistics, but since I'm not getting answers at those SE forums, I will post it here since my difficulties are after all mathematical in nature.
All of the questions posed here are related to this Physics SE post that proves that the propagation of uncertainties is quadratic.

Can you provide further clarification on why $\sum_{i=1}^nb_{ii}E(x_i^2)$ appears in the second equation? Chris here says: To second order, you have to account for the expectations of the squares of the inputs not matching the squares of the expectations. Still, I'm having trouble understanding this. Also in the fourth equation two terms $2f_0\sum_{i=1}^nb_{ii}E(x_i^2)$ and $\sum_{i=1}^na_i^2E(x_i^2)$ appear and I have no idea from where they come from.
From where does the $2$ on the third term of the second equation come from, and why is the second sum in the same term starting from $j=i+1$ when in the first equation it starts simply from $j=1$. Also the same thing appears in equation 4, where the 2 on the third term becomes 4, and again $j=1$ becomes $j=j+1$, the same thing happens with the fourth term.
Shouldn't the squared expectation of $y$ (third equation) include more terms? If we set $f_0=a$; $\sum_{i=1}^na_i\hat{x_i}=b$; $2\sum_{i=1}^n\sum_{j=i+1}^nb_{ij}\hat{x_i}\hat{x_j}=c$; $\sum_{i=1}^nb_{ii}E(x_i^2)=d$ then $(a+b+c+d)^2=a² + b² + c² + d² + 2ab + 2cd + 2ac + 2bc + 2ad + 2bd $ however I don't see terms $4c^2$,$4bc$,$2bd$,$d^2$ and $4cd$ in the third equation.
How do we go from the fifth to the sixth equation?
Answer: 1/2: they are just taking expectations of every term, using linearity of expectation. They then separate out the terms where $i=j$ from the terms where $i \neq j$ (because this will be helpful to compute variances). They then, instead of writing $\sum_{i=1}^n \sum_{j=1,j \neq i}^n$, decide to write $2 \sum_{i=1}^n \sum_{j=i+1}^n$; it is the same because the $(i,j)$ term and $(j,i)$ term are identical in each case.
3: Though I don't want to work out all of the algebra, my guess would be that the terms that are not explicitly included wound up in the $O(x^3)$ term. As an example, if $a=O(x^2),b=O(x),c=O(1)$ then $(a+b+c+O(x^3))^2=a^2+b^2+c^2+2ab+2bc+2ac=b^2+c^2+2bc+2ac+O(x^3)$. Note that the $O(x^3)$ terms are not the same; some of the products involving just $a,b,c$, such as $a^2$, were rolled into the new $O(x^3)$.
4: As best I can tell it is just a change of notation, and an omission of the explicit error term. That is, the variance is exactly the difference in expectations in the sum, and the first derivative is exactly the $a_i$. Then they dropped the error term so $=$ had to become $\approx$.
Comment: Thanks. Just another quick question, if I were to take into account second partial derivatives at the end (like in case of zero uncertainty), would they be squared or just as they are? I'm guessing no because of dimensional equality.


Changing background of a Button to a different shape and Styles like shadow effect etc in kivy python

Question: I learnt that in Qt we do have some ways to make a QpushButton with :

Shadow effect
making it  Flat by making setFlat properties to True .
chaning the cursor of a different type if someone hovers over it like pushButton_18.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))

I am looking to make Buttons behavior similar in kivy as well . Is it possible ?
I learnt that we can change background Image changed to a Image with rounded shape
Changing the background color of a Button in Kivy
but this is not that satisfying as the button still looks very normal . There s no shadow affect . Even when we click on the corners outside the button it is treated s if button is clicked .
I have gone through documentation of Kivy Button as well as Label and tried to change the behavior and look of a button . Can someone advice on how to make a button look better We can try to have :

Shadowing affect
Animation affect in background
Rounded edges etc .
Can we put animated gif Images as background for animation (I did try that but it wasnt animated anymore )

Below is a code which i just created for exploring more into buttons in Kivy :
__author__ = 'pbatra'
#Good info about background
#https://stackoverflow.com/questions/20181250/changing-the-background-color-of-a-button-    in-kivy/20181407#20181407

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.image import Image
from kivy.graphics import Color

gui = '''
<MenuScreen>:
    canvas.before:
        BorderImage:
            # BorderImage behaves like the CSS BorderImage
            border: 10, 10, 10, 10
            texture: self.background_image.texture
            pos: self.pos
            size: self.size
    GridLayout:
        size_hint: .1, .1
        pos_hint: {'center_x': .5, 'center_y': .5}
        rows: 1
        Button:
            text: 'Play'
            font_size: 20
            font_name: 'DroidSans'
            bold: True
            italic: True
            height: 10
            background_color: (0.5, 0.7, 0.5, 0.9)
            #Read more about them from documentation
            background_normal: './images/orange.png'
            background_down: './images/green.png'
            border: 30,30,30,30
            color: (1, .3, .8, .5)

        on_press: self.text = 'Oh yeah'

'''

class MenuScreen(Screen):
    background_image = ObjectProperty(
                                Image(
                                    source='../Examples/examples/widgets/sequenced_images/data/images/button_white_animated.zip',
                                    anim_delay=.5))
    Builder.load_string(gui)
    pass

# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))

class MyJB(App):
    def build(self):
        return sm

if __name__ == '__main__':
    MyJB().run()

Answer: Button in kivy starts with a ButtonBehavior which is combined with a Label adding properties like background_normal/down...for handling textures on the canvas.
Knowing this you can simply combine ButtonBehavior with any other widget you choose. Eg.
from kivy.base import runTouchApp
from kivy.lang import Builder

kv = '''
<ButImage@ButtonBehavior+AsyncImage>

FloatLayout:
    # we don't specify anything here so float layout takes the entire size of the window.
    ButImage:
        id: but
        # take 50% size of the FloatLayout
        size_hint: .5, .5
        # Make Button change it's opacity when pressed for visual indication
        opacity: 1 if self.state == 'normal' else .5
        source: 'http://www.victoriamorrow.com/sitebuildercontent/sitebuilderpictures/enter_button.gif'
        # Introduce Label incase you want text on top of the image
        Label:
            center: but.center
            # change text acc to but state
            text: "Normal" if but.state == 'normal' else 'down'
'''

if __name__ == '__main__':
    runTouchApp(Builder.load_string(kv))

Here we just set the ButtonBehavior to be combined with a AsyncImage which downloads the image from web for your background.
you should see something like this

Animation affect in background

This would be as simple as changing the source to animated gif or list of images inside a .zip.
from kivy.base import runTouchApp
from kivy.lang import Builder

kv = '''
<ButImage@ButtonBehavior+AsyncImage>

FloatLayout:
    ButImage:
        id: but
        size_hint: .5, .5
        opacity: 1 if self.state == 'normal' else .5
        allow_stretch: True
        keep_ratio: False
        source: 'http://media1.policymic.com/site/article-items/2095/1_gif.gif'
        Label:
            center: but.center
            text: "Normal" if but.state == 'normal' else 'down'

'''

if __name__ == '__main__':
    runTouchApp(Builder.load_string(kv))

Look at the sequence images example This was done before ButtonBehaviors were introduced so it even has a example of a AnimatedButton class using the older method which is essentially not needed any more.

Shadow Effect:

There are many ways to do this too.
You could either add a shadow to a widget/layout and have the button on top of this widget/layout take up less space than the shadow so as to account for touch on the shadows.
Or Create your own CustomButtonBehavior class derived from ButtonBehavior that overrides collidepoint method to only return True for custom collision. There is a example of using custom collision for widgets. You could even set the Image's keep_data property to True and later check pixel data for alpha to determine if you want to return true for collision.

Rounded edges etc.

Simply use a image with rounded edges kivy supports use of BorderImage Instruction which is equivalent to css borderimage in terms of functionality. Kivy's own button by default uses this.
Try and experiment with border attribute of BorderImage.
Comment: Your answer is really useful and helped . I am still trying to figure out that when I tried to use a .gif image for background_normal and background_down it didnt show the animation , but your way its showing animation . I am still trying to learn Shadow effect fro your post .. Do you know why .gif didnt work for background_normal or background_down .
Comment: Button by default uses just a vertex instruction.. BorderImage for drawing it's canvas which loads and displays static(doesn't have support for animation, you have to handle it manualy). Image Widget however does have support for just being given a gif or a .zip with images which it animates.
Answer: from kivy.app import App from
kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button

class lay(FloatLayout):
    def __init__(self, **kwargs):
       super(lay,self).__init__(**kwargs)
       self.btn = Button(background_normal='image_state_on.png',
       background_down='image_state_off', size_hint_x = .50, size_hint_y = .50)
       self.add_widget(self.btn)

class ImageButton_APP(App):
    def build(self):
           return lay()

ImageButton_APP().run()

I think this is more effective. I am using two kind of image.


How can the author choose when to publish an article, whether the article gets a teaser or not?

Question: Is there a possibility for the author/editor to decide - when publishing - whether the article (the content type) gets a teaser or not?
This is important for the look of the article on the front page.
I thought so far that would have to be defined before in the content Type.
Answer: If I understand your question, then this can be done by checking the Promoted to Frontpage box on the article.
You can then change your view to filter out nodes that have Promoted to Frontpage checked.
Comment: No, the author himself should decide whether this information article should be published independently of the publication on front page in full length or with a teaser. This is my mine only with different content types, right?
Answer: Have a look at Community Documentation about View modes, here is an intro about it (from that same page):

How a node is displayed depends on the context in which it is viewed, such as the difference between full nodes and teasers. On the page for field display management there are extra settings under the label custom display settings. The settings consist of a check box list of all view modes available for nodes, marking which view modes should have customized display settings. In a standard Drupal installation only teaser is checked, resulting in two sub tabs on the manage display page – default and teaser. The sub tabs lead to separate settings for each view mode.

Some more details (from the same linked page):

In Drupal 7, additional View modes can be added to entities using hook_entity_info_alter().
In Drupal 8, adding a custom view mode can be accomplished without code. To add one, expand Custom Display Settings on the Manage Display tab of a content type, then click Manage View Modes.

So if you'd only add 1 optional (text?) field to store such teaser, the author/editor could use that to optionally use such teaser, and by using "View nodes" you (as an admin) can decide how to dislay them.
Comment: Hi Pierre, I've tried it. There is no possibility for the Author to change Teaser/or not. Which Drupal Version do You mean?
Answer: There is not a built-in way to do this, you'll need to add a field or other setting to the content to indicate how the article is displayed. The Custom Publishing Options module would be one way to add the option to the edit form. Alternately you could just use a field.
As Pierre suggested, a custom view mode will help with the next step. You might create a new view mode called 'full_or_teaser':
/**
 * Implements hook_entity_info_alter().
*/
function mymodule_entity_info_alter(&$entity_info) {
   $entity_info['node']['view modes']['full_or_teaser'] = array(
  'label' => t('Full or teaser'),
  'custom settings' => FALSE,
 );
}

That view mode can then be selected in your front page view.
Now you need to select full or teaser output depending on the setting for the node. There's a number of ways you could do that but hook_entity_view_mode_alter looks like the best for this case:
function my module_entity_view_mode_alter(&$view_mode, $context) {
   if ($view_mode === 'full_or_teaser') {
       $node = $context['entity'];
       $view_mode = empty($node->myoption_full)? 'teaser': 'full';
   }
}


Como fazer um preg_replace com varias condições e varias alterações?

Question: Como fazer um PREG_REPLACE tendo varias buscar e varias substituições ao mesmo tempo
Por exemplo quero
('/(BR|BL)/', 'B') se tiver BR e BL substituir por B e também ('/PH/', 'F') se tiver PH substituir por F
São varias condições e varias substituições.
Answer: Você pode fazer da seguinte forma abaico, passando dois arrays como argumentos para a função preg_replace, o primeiro com os padrões de substituições e o segundo com os valores de substituições:
<?php
$string = 'Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. ';

//Array com os padrões de substituição:
$patterns = array(
    '/(Lorem Ipsum|século XVI)/',//Ou '/(Lorem Ipsum|século XVI)/i' caso você queira que seja case insensitive, não diferencia maiusculo de minusculo.
    '/tipográfica/',//Ou '/tipográfica/i'
    '/livro/'//Ou '/livro/i'
);
//A partir da versão PHP 5.4 você também pode usar a sintaxe contraída de array:
//$patterns = ['/(Lorem Ipsum|século XVI)/', '/tipográfica/', '/livro/'];

//Array com os valores de substituição:
$replacements = array(
    '$1',
    'tipográfica',
    'livro'
);
//Sintaxe contraída de array:
//$replacements = ['$1', 'tipográfica', 'livro'];

echo preg_replace($patterns, $replacements, $string);

Exemplo: exemplo de utilização.
No seu caso deve ficar da seguinte forma, por exemplo:
<?php

$string = 'Lorem Ipsum é BR simplesmente uma simulação de BL texto da indústria BL tipográfica e de impressos, e vem sendo utilizado PH desde o PH século XVI. ';

//Array com os padrões de substituição:
$patterns = array(
    '/(BR|BL)/',//Ou '/(BR|BL)/i'
    '/PH/',//Ou '/PH/i'
);
//Sintaxe contraída de array:
//$patterns = ['/(BR|BL)/','/PH/'];

//Array com os valores de substituição:
$replacements = array(
    'B',
    'L',
);
//Sintaxe contraída de array:
//$replacements = ['B', 'L'];

echo preg_replace($patterns, $replacements, $string);

Exemplo: exemplo de utilização.
Answer: $texto = 'BLZ vou mudar o que tiver BR para B e o que tiver BL também. Além disso, quero mudar o que tiver PH para L, mas, será que pega com letras minúsculas? -> Teste: ph br bl';

echo
    preg_replace(
        ['/(BR|BL)/i','/PH/i',],
        ['B', 'L',],
        $texto
    );

Saida:
BZ vou mudar o que tiver B para B e o que tiver B tambm. Alm disso, quero mudar o que tiver L para L, mas ser que pega com letras minsculas? -> Teste: L B B

i É um modificador para CASE INSENSITIVE.