Azure App Gateway warning about Public IP

Question: I am using the Azure App Gateway v2 and the App Gateway Ingress Controller as a public frontend to an AKS cluster. Following the guidance in this doc, I created and associated the IP address to my gateway without issue. However, when I inspect the IP address itself in the Azure Portal, I receive the following warning indicating a misconfiguration and that I must use a dynamically associated IP:

So far I have not run into any issues actually routing traffic through the gateway, though this message gives me pause as we've not yet configured DNS for this gateway. Is this warning simply a leftover from older versions of App Gateway that remains in the portal that I can safely ignore, or is this something I'll actually need to modify going forward and potentially something that can invalidate the configuration as it goes beyond the scope of the tutorial implementation?
Answer: To convert an existing public IP from dynamic to static using the Azure portal:

Browse to the Public IP address to be updated
Switch to the Configuration blade
Change the Assignment from Dynamic to Static
Click on Save to save the changes


Listing Active Members of Current Group in View pane (OG 7.x-2.3)

Question: I am relatively new to Drupal and somewhat boggled by the new version of Organic Groups. We recently migrated our site from OG 7.x-1.4 to OG 7.x-2.3. Everything went fine except certain view panes no longer work. We had one view content pane that listed the members of the group in a page based on the context. We created a panel page for the group home page layout when the content pane was embedded in that page it would show the members for that group. However, the contextual filter for that view was broken after the import.
I tried to copy the view settings from a clean install of the latest OG code but that didn't work. The view is one of users but I cannot figure out how I should set the contextual filters or the relationships of that view to show only the members of the group. I just can't seem to wrap my head around how the OG_Membership object works.
Any help would be greatly appreciated.
Answer: In retrospect the answer was rather obvious. When you migrate from OG 1.x to OG 2.x, the views associated with OG do not get updated. So they have "missing/broken relationships." For most of the view panes it was easy to fix by going to the view page and under the "edit view name/description" drop down, there is an option to "Revert View". Choosing this fixes the views that come with OG because it "reverts" the view to the updated OG 2.x code. Custom views have to be rebuilt.


Django SQLite on Heroku doesn't recognize any of the changed models and throws a "relation doesn't exist" error

Question: I changed the name of several models on Django. Successfully ran makemigrations and migrate. I can interact with the SQLite directly as admin or through requests on localhost.
before changing the tables I had deployed to Heroku and it was working. when I changed the model names and pushed to Heroku (after successfully running on localhost) I get issues. When I login as admin to the site (on Heroku) I can interact with tables like User and Token, but not with the newly updated models. as soon as I click on them I get bellow error. when I click on add to these models, the columns appear but as soon as I hit save I get below error as well.
ProgrammingError at /admin/app_name/model_name/
relation "app_name_model_name" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "app_name_model_name"
I kept the Debug=True to see what's going on otherwise I get "500 Internal Server Error". I have added heroku's site as "ALLOWED_HOSTS".
When I was trying to make the migrations work, I had delete the files on the migration folder. not sure if there is a similar process on Heroku or if I'm missing something else?
By the way I have ran the migration commands using "heroku run bash" too. also, some of the models only had name changes, some had field updates too, but all of them throw the same error on Heroku.
Comment: "Django SQLite on Heroku"—this is a nonstarter. SQLite is not compatible with Heroku due to its [ephemeral filiesystem](https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem). There is extensive documentation about this on Heroku's site, and there are several questions about it here.
Comment: there are limitations on SQLite but the point here is that it was working with Heroku but I'm getting this error after changing and migrating the models.
Comment: SQLite on Heroku causes _all kinds_ of problems, trivially including the exact error that you are seeing (e.g. if you don't migrate and commit changes to your database file, which is itself a _huge_ antipattern). You need to switch to a client-server database. SQLite is _not_ an option on Heroku.
Comment: "it was working with Heroku"—it was _not_. Your database would have been regularly reset to whatever state it had in the commit you had deployed. That includes data and structure.
Answer: I removed the app entirely from Heroku and recreated. it's working now.


Transformar array multidimensional em unidimensional em VUE

Question: Pessoal estou precisando transformar um array multidimensional em VUE em um array unidimensional, pois preciso recupera um array apenas com os campos "cod" dessa array, tendei da forma abaixo sem sucesso.
new Vue({
    el:"#app",
    data : {
        array_teste : [{cod : '1', nome : 'S'},{cod : '2', nome : 'V'}],
    },

    computed: {
        cat_vender_rec: function() {
            return JSON.stringify(this.cat_vender);
        }
    }
})

Comment: Só lembrando que você não tem um array multi-dimensional aí... Você tem um array de objetos com dimensão 1.
Answer: Você pode usar o método .map() para mapear os dados do array que você quer.
const array = [{cod : '1', nome : 'S'},{cod : '2', nome : 'V'}];

const arrayCods = array.map(obj => {
  return obj.cod;
});

console.log(arrayCods); // ['1', '2']

Documentação do método .map()


How to open .msu extension file?

Question: I have downloaded a file WINDOWS POWERSHELL that has an .msu extension how do i install this package in my winxp professional sp3 OS.
Comment: For Windows XP the answer to this question seems to be in an answer to this question at superuser.SE: http://superuser.com/questions/628392/how-do-you-open-a-msu-file
Answer: There is this link on microsoft support site that explains how to install the .msu file:

Description of the Windows Update Standalone Installer in Windows
Comment: Did an older version of that article include information about XP? It's not there now. (I think XP is almost entirely scrubbed from Microsoft's site.)

How to open .msu extension file?


C# SqlCommand and non named parameters

Question: I have a huge program which has already tons of queries with parameters.
In the whole project I accessed to the database only through IDbConnection, IDbCommand, etc interfaces instead of using directly OleDbConnection, OleDbCommand, etc.
This allowed me to use different database engines and connection types with my application. Until now, for example, I used OleDbConnection to connect to MS SQL Server databases, OdbcConnection for MySql and SQLiteConnection from an external library for, obviously, SQLite.
Now I would like to try replacing the OleDbConnection with SqlConnection to connect to SQL Server but I found some problems with the parametrized queries.
I was used to do something like that with parametrized queries:
IDbCommand cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE foo SET field1=? WHERE ID=?";
DbUtils.AddParameter(cmd, DbType.StringFixedLength, "hello");
DbUtils.AddParameter(cmd, DbType.Int32, 1);
cmd.ExecuteNonQuery();

The AddParameter static method checks the type of the IDbCommand and adds the parameter value to it.
This works with the three connection types I specified above, but doesn't work with SqlConnection, it throws the error: Incorrect syntax near '?'.
SqlCommand seems to require named parameters to work:
IDbCommand cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE foo SET field1=@pfield1 WHERE ID=@pID";
DbUtils.AddParameter(cmd, DbType.StringFixedLength, "@pfield1", "hello");
DbUtils.AddParameter(cmd, DbType.Int32, "@pID", 1);
cmd.ExecuteNonQuery();

Do you know if it is possibile to avoid using named parameters to maintain compatibility with the other connection types?
Thanks!
Francesco
Comment: Did you try with just `@` instead of `?`?
Comment: @krillgar: I just tried, but it gives me the error: **Must declare the scalable variable '@'**
Comment: That is what I figured it would do, but worth a shot.
Comment: @Formentz If you use it _only_ as `@` in your command , it is too normal to say that error because it is **not** a named parameter with just itself.
Comment: @xanatos sorry, you're right. The post you linked is also an answer for my question. Should I remove my question?
Comment: @Formentz I don't know... It will be probably merged by the cleaners :-)
Answer: I don't think so.
From SqlCommand.Parameters property

The Microsoft .NET Framework Data Provider for SQL Server does not
  support the question mark (?) placeholder for passing parameters to a
  SQL Statement or a stored procedure called by a command of
  CommandType.Text. In this case, named parameters must be used.
Comment: thank you, I didn't find that comment in the docs... Seems I have to keep using OleDbProvider
Comment: @Formentz Glad to help. You should always use the right provider that you needs of course ;)

C# SqlCommand and non named parameters


Autoencoder with tied weights: bias?

Question: For some unsupervised learning problem, I need to train an autoencoder, so that I only have to store the encoder afterwards. However, I am not sure on how and if the bias weights can be tied.
To make myself more clear:
I have input $x\in R^d$, being encoded to a code $h\in R^{d'}$ using the encoding: $h=\sigma(Wx+b)$. The code is then used for the recostructruction with $y=\sigma(W'h+b')$, where $W'=W^T$ (tied weights) and $||y-x||^2$ is used as the minimization criterion.
And now my question: Is there a similar way to tie the bias $b'$ according to some function of $W$ and $b$, so that after the training of the autoencoder, I can store the encoder parameters only? Or do I have to store the bias weights of the decoder as well? Also, if there are more layers on the encoder/decoder, does the same apply to their bias weights as well?
Answer: There is no connection between the bias to hidden nodes and those to the reconstructed layer. To understand that this is not possible you can look at the dimensions of $b$ and $b'$. $b$ needs to be $d'$-dimensional and $b'$ is $d$-dimensional, one term for each node in the respective layer.
If you need to save $b'$ depends on what you want to do with your autoencoder. If you only want to perform dimensionality reduction there is really no need for the decoder part, the same goes if you want to use your autoencoder to initialize a deep neural network. However, if you want to build a deep autoencoder you would need the $b'$:s. And I guess it would not be that much of a trouble of saving them anyway.

Autoencoder with tied weights: bias?


Diferença na execução de threads em Java

Question: Veja a execução de dois programas semelhantes em Java. Um herda de Thread e outro implementa a interface Runnable:
Programa1:
public class PingPong extends Thread{
private String msg;
private int delay;

PingPong(String s,int tempo){
    msg = s;
    delay = tempo;
}

public void run(){
    try{
        for (int i=1;i<=10;i++){
            System.out.println(msg+ " " + i);
            Thread.sleep(delay);
        }
    }
    catch (Exception e){
        System.err.println("Deu pau!");
        return;
    }
}

public static void main(String[] args) {
    PingPong ping = new PingPong("ping",500);
    ping.start();

    PingPong pong = new PingPong("pong",1000);
    pong.start();

    System.out.println("*** FIM DO PROGRAMA PRINCIPAL ***");
}}

Ele gera a seguinte saída:

E temos o programa 2:
    public class PingPong2 implements Runnable{
    private String msg;
    private int delay;

    PingPong2(String s,int tempo){
        msg = s;
        delay = tempo;
    }

    public void run(){
        try{
            for (int i=1;i<=10;i++){
                System.out.println(msg+ " " + i);
                Thread.sleep(delay);
            }
        }
        catch (Exception e){
            System.err.println("Deu pau!");
            return;
        }
    }

    public static void main(String[] args) {
        Runnable ping = new PingPong2("ping",500);
        Runnable pong = new PingPong2("pong",1000);

        new Thread(ping).start();
        new Thread(pong).start();
        System.out.println("*** FIM DO PROGRAMA PRINCIPAL ***");
    }
}

Gerando a seguinte saída:

Por que a saída no programa1 não é impresso o "ping1" uma vez que na implementação do método run(), a impressão na tela é feita antes de colocar a thread para dormir (em espera)?
Comment: A resposta resolveu o seu problema? Acha que pode aceitá-la? Se não souber como faz, veja o [tour]. Isso ajudaria muito indicar que a solução foi útil para você e dar uma indicação que houve uma solução satisfatória. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Primeiro: a classe do primeiro exemplo está conceitualmente errada. PingPong não é uma Thread, por isso não deveria herdar dela. Funciona, mas está errado. O problema de fato não é esse. Entendo que esse é só um teste, mas é comum as pessoas transporem coisas assim para código normal. Então vale o alerta.
Threads são complicadas, são imprevisíveis, o programador tem pouco controle sobre elas. Elas são duas linhas de execução distintas e independentes, por isso não há garantia de ordem de execução. Threads tendem a criar condições de corrida.
Depende do agendamento do sistema operacional. Especialmente a primeira execução pode dar uma diferença maior porque a criação de uma nova thread é algo custoso.
O que provavelmente ocorreu é que a execução do pong pegou um agendamento mais favorável e conseguiu concluir a criação da thread e seu início antes. Muito provavelmente a criação da thread do ping iniciou antes, mas o que importa é a conclusão.
O segundo exemplo poderia ter ocorrido o mesmo, só deu "sorte" de não ocorrer. Cada execução será diferente. Note que ele também não executa como o esperado e intercala o ping com o pong nas primeiras execuções como se o delay fosse igual.
Não use threads se precisar de previsibilidade. Elas são menos úteis do que as pessoas imaginam.

Existe diferença entre Programa, Thread e Processo?
É sempre garantido que uma aplicação com múltiplas threads rode mais rápido que usando uma única thread?
Problemas com thread (praticamente duplicata, só vi depois de concluir esta resposta)


Finding Coordinate along Ellipse Perimeter

Question:
Given an ellipse at (0, 0), with height "h" and width "w", what's the "x" coordinate along the perimeter for a given "y" coordinate?
Answer: An ellipse is in the standard form if its major and minor axes are co-ordinate axes and intersect at origin. This point of intersection is usually called the center of the ellipse.
This is a standard ellipse whose equation is $$ \dfrac{4x^2}{w^2}+\dfrac{4y^2}{h^2}=1$$
Also, notice that, since the curve is symmetric about origin, there are always $2$ $x$- coordinates that satisfy a given $y$-coordinate and vice versa.
$$x=\pm \dfrac{w}{2}\sqrt{1-\dfrac{4y^2}{h^2}}$$ $$y=\pm \dfrac{h}{2}\sqrt{1-\dfrac{4x^2}{w^2}}$$
Now, that you have pointed out to a positive $x$, we can resolve this sign ambiguity and we'll have that, $$\boxed{x=+\dfrac{w}{2}\sqrt{1-\dfrac{4y^2}{h^2}}}$$
Comment: This raises a question about the factor of $2$ you have included:  In his diagram, does $h$ refer to the distance from the top of the ellipse to the bottom, or from the origin to the top?  (I really can't tell from the picture)
Comment: @Eric, OP says his/her ellipse is of height "h", and not "2h". So, I thought this was a reasonable interpretation.
Comment: Just tested it. That's exactly what I needed. Thanks!
Answer: The equation for the ellipse will be  $$\frac{x^2}{w^2}+\frac{y^2}{h^2}=1.$$


Norm inequality proof

Question: How to show that for any normed space and for any two elements x and y, the following inequality holds: $||x|| \leq max \{||x+y||, ||x-y||\}$ ?
I believe that i need to show the following: 1) $||x|| > ||x+y|| => ||x|| \leq ||x-y||$ and 2) $||x|| > ||x-y|| => ||x|| \leq ||x+y||$, but I don't know how it can be done.
Thank you very much.
Answer: Write $x=\frac12\bigl((x+y)+(x-y)\bigr)$. By the triangle inequality,
$$\lVert x\rVert\le \frac12\bigl(\lVert x+y\rVert+\lVert x-y\rVert\bigr) \le \frac12\cdot 2\max\bigl(\lVert x+y\rVert,\lVert x-y\rVert\bigr).$$

Norm inequality proof


JS visibility of a variable in function

Question: I work with JSON and I want to count the number of elements in the response.
    $.getJSON("/api/getEvents", function(data) {
        $.each(data, function(key, event) {
            var count = 10;
            $.getJSON("/api/getUsers", function(data) {
                $.each(data, function(key, event) {
                    alert("Value: " + count);
                    count++;
                });
            });
            alert("Count: " + count);
        });
    });

As a result, I get:
Value: 10
Value: 11
Value: 12
...
Count: 10

Why count = 10?
Comment: I'm not quite sure, that's why I'm not posting this as an answer, but I believe that in $.getJSON you create a closure, which only captures the reference to the variable count.
Comment: It looks to me like `data` from the `getUsers` call is an empty array. You set count to 10, you increment it zero times, then it alerts Count: 10.
Comment: @BenLee No, array is not empty. I can get the value of elements from data.
Comment: When you say "As a result, I get..." what do you mean by "you get"? Is this console output? Alerts? Where are the "Value: ..." lines coming from -- I don't see that in the code anywhere?
Comment: @BenLee Sorry, the parser ate line. Alerts.
Comment: It seems to work here http://jsfiddle.net/TfG2C/
Answer: It's because ajax requests are asynchronous. $.getJSON just initiates a request, but javascript execution immediately continues. You can see the count if you move the alert inside the ajax callback:
$.getJSON("/api/getEvents", function(data) {
    $.each(data, function(key, event) {
        var count = 10;
        $.getJSON("/api/getUsers", function(data) {
            $.each(data, function(key, event) {
                alert("Value: " + count);
                count++;
            });

            // I moved this here:
            alert("Count: " + count);
        });
        // It used to be here.
    });
});

So after you set var count = 10, the javascript parser then runs $.getJSON, but then immediately goes on to the next line, which in your code example alerted the "Count: 10". Then, whenever the request finishes, it runs the callback code that increments the count and alerts the Value lines.
Comment: Thats what I thought at first, too but in the question the alert is not where you say it is. It actually is already inside the getJSON callback.
Comment: @Joi, that was a mistake in the question. The OP fixed it after I asked him where the "Value" lines were coming from.

JS visibility of a variable in function


Definition of Infinite Dimensional Vector Space :

Question: In the text i am referring for Linear Algebra , following definition for Infinite dimensional vector space is given .
<code>The Vector Space V(F) is said to be infinite dimensional vector space or

infinitely generated if there exists an infinite subset S of V such that L(S) = V.
</code>
I am having following questions which the definition fails to answer :-

Let us say i have an infinite dimensional vector space I(F) .If S is
the infinite subset that spans  I(F) , can i say that S is Linearly
Independent . If so , why ?
Does that mean any subset that
spans every infinite dimensional vector space is Linearly
Independent.
On similar lines , can i say that Basis will exist for each Infinite
Dimensional Vector Space and it is nothing but the subset that spans
over vector space ?
Comment: "*If $S$ is* **the** *infinite subset that spans...*"  The article `the` carries some connotation in English that you think it is the only possible object that fits that description.  Vector spaces in general can have *many* different spanning sets.  You should have used the article `a` or `an` here instead implying you are aware that there could be others.  Now... a spanning set does not need to be linearly independent.  A *basis* does.  Don't confuse these.  As for your supposed definition you quoted, it is missing the condition that $S$ be linearly independent.
Comment: What's $L(S){}$?
Comment: L(S) is Linear Combination of S over the field F. Here , S is a subset of V. Sorry for not mentioning.
Comment: Consider... $\Bbb R^2$ is equal to the span of the vectors $\{(0,1),(1,0),(2,0),(3,0),(4,0),(5,0),\dots\}$ yet $\Bbb R^2$ is 2-dimensional despite there being infinitely many vectors in the set used for the spanning set.  It just so happened that this choice of spanning set was *incredibly redundant* and not formed using linearly independent vectors.
Comment: Can we say any infinite dimensional vector space set will have a basis (whether finite or infinite ) for sure ?
Comment: [Yes](https://en.wikipedia.org/wiki/Basis_(linear_algebra)#Proof_that_every_vector_space_has_a_basis).
Comment: An infinite dimensional vector space will *never* have a finite basis.  An infinite dimensional vector space always having an infinite basis might or might not be true depending on whether you accept or reject the axiom of choice respectively.  Moving from the finite case to the infinite case, there are different competing notions for bases.  [See here](https://en.wikipedia.org/wiki/Basis_(linear_algebra)#Analysis).  In particular you have Hamel bases, Schauder bases, Markushevic bases, etc... with their different nuances.
Answer: Assuming that $L(S)$ denotes the linear hull (or span) of $S$, which is the set of all linear combinations that can be formed from finitely many elements in $S$, the statement you gave is wrong:
Note that $V=\mathbb R^n$ is a finite dimensional vector space over $\mathbb R$, yet for the infinite set $S=\mathbb R^n$, we have $L(S)=V$.
The correct definition is that $V$ is infinite dimensional if there exists no finite $S$ such that $L(S)=V$. Or equivalently (by the axiom of choice) if there exists an infinite set $S$ that is linearly independent and satisfies $L(S)=V$. That is, $V$ is infinite dimensional if it admits no finite basis, which is equivalent to admitting an infinite basis.
Comment: How does V having no finite basis is equivalent to an infinite basis unless the linear independence of that infinite set is proved ?
Comment: A basis is a linearly independent spanning set by definition. [Every vector space admits a basis by the axiom of choice](https://en.wikipedia.org/wiki/Basis_(linear_algebra)#Proof_that_every_vector_space_has_a_basis), so if there is no finite basis, there has to be an infinite one.
Comment: Let W = {0} be subset of vector space V(F) ,where 0 is the identity element. Clearly W is a subspace of V(F). What is the basis of W?
Comment: $W=\{0\}$ is a $0$-dimensional subspace and accordingly there's only one basis of $W$: the empty set $\varnothing$.


Convert PIL.Image to/from Gtk.Picture/Gtk.Image in gtk4

Question: I do RGBA image manipulation in PIL(low) and would like to display the resulting image in a gtk4 application. For that, I'd need a seamless PIL.Image <--> Gtk.Picture/Gtk.Image converter. I'd like to avoid using temporary files at all cost. I found helpful hints here and here but was wondering if there was anything more convenient in gtk4?
Answer: As of GTK 4.4, this seems to work best:
buffer = GLib.Bytes.new(pil_image.tobytes())
gdata = GdkPixbuf.Pixbuf.new_from_bytes(buffer, GdkPixbuf.Colorspace.RGB, True, 8, pil_image.width, pil_image.height, len(pil_image.getbands())*pil_image.width)
gtk_image = Gtk.Image.new_from_pixbuf(gdata)

Once GTK 4.6+ becomes ubiquitous, GdkPixbuf should be replaced with GdkTexture, via Gdk.Texture.new_from_bytes().


RabbitMQ pika: cannot stop consuming a stream queue because it doesn't allow nack or reject

Question: My application has a Stream queue and I want it to stop consuming when a certain condition is met. Since start_consuming blocks forever with a BlockingConnection, it looks like the only way to get out is to call stop_consuming somewhere in a callback.
Unfortunately, that doesn't work because stop_consuming will reject all pending messages (from pika docs)

NOTE: pending non-ackable messages will be lost; pending ackable messages will be rejected.

...and you can't do a reject on a stream queue as this error message confirms:
operation basic.reject caused a connection exception not_implemented: "basic.nack and basic.reject not supported by stream queues queue 'stream-queue' in vhost '/'"
Here's a minimal example. Server code:
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost')
)
channel_stream = connection.channel()

channel_stream.queue_declare(
    "stream-queue",
    auto_delete=False, exclusive=False, durable=True,
    arguments={
        'x-queue-type': 'stream',
    }
)
channel_stream.basic_qos(
    prefetch_count=1,
)

class Server(object):
    def __init__(self):
        channel_stream.basic_consume(
            queue="stream-queue",
            on_message_callback=self.stream_callback,
        )

    def stream_callback(self, channel, method, props, body):
        print(f"received '{body.decode()}' via {method.routing_key}")
        channel_stream.stop_consuming()

server = Server()

try:
    channel_stream.start_consuming()
except KeyboardInterrupt:
    connection.close()

And the client code:
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost')
)
channel_stream = connection.channel()

channel_stream.queue_declare(
    "stream-queue",
    durable=True,
    arguments={
        'x-queue-type': 'stream',
    }
)

# This publishes twice: once to trigger the server's callback
# and again to get a message in the queue that the server is forced
# to nack, causing a crash.
for i in range(2):
    channel_stream.basic_publish(
        exchange='',
        routing_key='stream-queue',
        body=f"stream data".encode()
    )
connection.close()

And the full output:
~/anaconda3/envs/py310/bin/python ~/workspace/rabbitmq_train/stream_bug/server_stream_only.py
received 'stream data' via stream-queue
Traceback (most recent call last):
  File "~/workspace/rabbitmq_train/stream_bug/server_stream_only.py", line 36, in <module>
    channel_stream.start_consuming()
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 1880, in start_consuming
    self._process_data_events(time_limit=None)
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 2041, in _process_data_events
    self.connection.process_data_events(time_limit=time_limit)
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 848, in process_data_events
    self._dispatch_channel_events()
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 567, in _dispatch_channel_events
    impl_channel._get_cookie()._dispatch_events()
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 1507, in _dispatch_events
    consumer_info.on_message_callback(self, evt.method,
  File "~/workspace/rabbitmq_train/stream_bug/server_stream_only.py", line 30, in stream_callback
    channel_stream.stop_consuming()
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 1893, in stop_consuming
    self._cancel_all_consumers()
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 1494, in _cancel_all_consumers
    self.basic_cancel(consumer_tag)
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 1802, in basic_cancel
    self._flush_output(
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 1350, in _flush_output
    self._connection._flush_output(lambda: self.is_closed, *waiters)
  File "~/anaconda3/envs/py310/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 523, in _flush_output
    raise self._closed_result.value.error
pika.exceptions.ConnectionClosedByBroker: (540, "NOT_IMPLEMENTED - basic.nack and basic.reject not supported by stream queues queue 'stream-queue' in vhost '/'")

Process finished with exit code 1

And this is how I started the server:
docker run -it --rm -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management

Comment: Hey, you're on a roll. Gabriele is a co-worker of mine, and his suggestion is a good one, though I'm not 100% sure it'll solve your problem. Pika likes to do some magic behind the scenes as you've found. If you don't mind, open an issue in the Pika repository and we can figure out the best solution there (https://github.com/pika/pika/issues). The way you have been reporting issues is *excellent*, please keep up the good work.
Comment: Sounds good, looks like he reported it already: https://github.com/pika/pika/issues/1389
Answer: You can't use the same channel for different kinds of queues.
In general, it is not a best practise. You should have a channel per consumer.
To solve your problem:
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost')
)
channel = connection.channel()
channelStream = connection.channel()

channelStream.queue_declare(
    "stream-queue",
    auto_delete=False, exclusive=False, durable=True,
    arguments={
        'x-queue-type': 'stream',
    }
)
channel.queue_declare(
    "normal-queue"
)
channelStream.basic_qos(
    prefetch_count=1,
)

class Server(object):
    def __init__(self):
        channelStream.basic_consume(
            queue="stream-queue",
            on_message_callback=self.stream_callback,
        )
        channel.basic_consume(
            queue="normal-queue",
            on_message_callback=self.normal_callback,
        )

    def stream_callback(self, channel, method, props, body):
        print(f"received '{body}' via {method.routing_key}")
        channelStream.basic_ack(delivery_tag=method.delivery_tag)
        channelStream.stop_consuming()

    def normal_callback(self, channel, method, props, body):
        print(f"received '{body}' via {method.routing_key}")
        channel.basic_ack(delivery_tag=method.delivery_tag)
        channel.stop_consuming()

server = Server()

try:
    channel.start_consuming()
    channelStream.start_consuming()
except KeyboardInterrupt:
    connection.close()

Multi-Thread would be:
#!/usr/bin/env python
import threading

import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost')
)

connectionStream = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost')
)
channel = connection.channel()
channelStream = connectionStream.channel()

channelStream.queue_declare(
    "stream-queue",
    auto_delete=False, exclusive=False, durable=True,
    arguments={
        'x-queue-type': 'stream',
    }
)
channel.queue_declare(
    "normal-queue"
)
channelStream.basic_qos(
    prefetch_count=1,
)

class Server(object):
    def __init__(self):
        pass

    def stream_callback(self, channel, method, props, body):
        print(f"stream_callback '{body}' via {method.routing_key}")
        channelStream.basic_ack(delivery_tag=method.delivery_tag)
        channelStream.stop_consuming()

    def normal_callback(self, channel, method, props, body):
        print(f"normal_callback '{body}' via {method.routing_key}")
        channel.basic_ack(delivery_tag=method.delivery_tag)
        channel.stop_consuming()

    def start_consume_normal(self):
        print(f"start_consume_normal ")
        channel.basic_consume(
            queue="normal-queue",
            on_message_callback=self.normal_callback,
        )
        channel.start_consuming()

    def start_consume_stream(self):
        channelStream.basic_consume(
            queue="stream-queue",
            on_message_callback=self.stream_callback,
        )
        print(f"start_consume_stream ")
        channelStream.start_consuming()

server = Server()

try:
    x = threading.Thread(target=server.start_consume_normal, args=())
    x.start()
    print(f"start_consume_normal")
    x2 = threading.Thread(target=server.start_consume_stream, args=())
    x2.start()
    print(f"start_consume_stream")
    input()
except KeyboardInterrupt:
    connection.close()

Note about multi-thread
Comment: I think this works based on an initial test. One question: doesn't `start_consuming` block? How is`channelStream.start_consuming()` able to run when it's blocked by the previous line?
Comment: That was a pseudo solution. btw added a multi-thread solution. Please read about Pika and multi-threads
Comment: Weirdly the previous solution worked, despite blocking the 2nd line the callbacks for both still run.
Comment: I was hoping to avoid threads as much as possible: I like `BlockingConnection` because I can handle all business logic through callbacks. It looks like `SelectConnection` can meet my needs: there's one ioloop for an arbitrary number of channels.
Comment: The only drawback to `SelectConnection` is the catch-all behavior, hence my other SO question: https://stackoverflow.com/q/73736444/17404810
Comment: I am not a python expert, but in general, the main point is that you have to use two different channels.
You can't use the same channel to consume two queues. It is not a best practice.
Comment: It doesn't seem to work anyway. I added an even simpler example using only 1 channel and 1 stream queue.
Comment: you are right, I can reproduce the issue


I am stuck between either a memory leak or excessive static in Audio while capturing audio from microphone

Question: I am writing an iPhone app where I need to capture audio from the mic and stream the it to a streaming server in AAC format. So I first capture the audio and then use the
<code>AudioConverterFillComplexBuffer
</code>
method for converting the audio to AAC.
Below is the code
<code>- (void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{

   NSArray *audioChannels = connection.audioChannels;
   if (audioChannels == nil || [audioChannels count]==0) {
        // NSLog(@"We have Video Frame");
        [_encoder encodeFrame:sampleBuffer];
   }else{
        // NSLog(@"We have Audio Frame");
        if (hasAudio) {
            CMTime prestime =          CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
        double dPTS = (double)(prestime.value) / prestime.timescale;

        [self getAudioBufferDataFromCMSampleBufferRef:sampleBuffer];

        // describe output data buffers into which we can receive data.
        AudioBufferList outputBufferList;
        outputBufferList.mNumberBuffers = 1;
        outputBufferList.mBuffers[0].mNumberChannels = _aacASBD.mChannelsPerFrame;
        outputBufferList.mBuffers[0].mDataByteSize = _aacBufferSize;
        outputBufferList.mBuffers[0].mData = _aacBuffer;

        OSStatus st = AudioConverterFillComplexBuffer(_converter,   &putPcmSamplesInBufferList, (__bridge void *) self, &_numOutputPackets, &outputBufferList, NULL);

        if (0 == st) {
            [_rtsp onAudioData:_aacBuffer :outputBufferList.mBuffers[0].mDataByteSize :dPTS];
        }else{
            NSLog(@"Error converting Buffer");
            NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:st userInfo:nil];
            NSLog([self OSStatusToStr :st] );
            char * str = new char[3];
            FormatError(str, st);

        }

        if (_blockBuffer) // Double check that what you are releasing actually exists!
        {
            CFRelease(_blockBuffer);
        }
  }

}
</code>
The code for the
     getAudioBufferDataFromCMSampleBufferRef
is as below
<code>- (AudioBuffer) getAudioBufferDataFromCMSampleBufferRef: (CMSampleBufferRef)audioSampleBuffer{

     AudioBufferList audioBufferList;

     OSStatus err =      CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(audioSampleBuffer, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &_blockBuffer);
     AudioBuffer audioBuffer ;

     if (!err && _blockBuffer && audioBufferList.mBuffers[0].mData && (audioBufferList.mBuffers[0].mDataByteSize > 0))
     {
         for( int y=0; y<audioBufferList.mNumberBuffers; y++ )
         {
             audioBuffer = audioBufferList.mBuffers[y];
             break;
         }
     }

    inputBuffer.mData=audioBuffer.mData;
    inputBuffer.mDataByteSize=audioBuffer.mDataByteSize;
    inputBuffer.mNumberChannels=1;

    return audioBuffer;
}
</code>
In the above version of the code I get a BAD_ACCESS error. If instead, I remove the code that releases the blockBuffer, there is a memory leak and the app eventually terminates because of memory pressure.
If I don't retain the blockBuffer and write the code of
<code> getAudioBufferDataFromCMSampleBufferRef
</code>
differently as given below
<code>- (AudioBuffer) getAudioBufferDataFromCMSampleBufferRef: (CMSampleBufferRef)audioSampleBuffer
{
    _blockBuffer = CMSampleBufferGetDataBuffer(audioSampleBuffer);
    int audioBufferByteSize =    CMSampleBufferGetTotalSampleSize(audioSampleBuffer);

CMBlockBufferCopyDataBytes(_blockBuffer,0,audioBufferByteSize,inputBuffer.mData);
    inputBuffer.mDataByteSize=audioBuffer.mDataByteSize;
    inputBuffer.mNumberChannels=1;
}
</code>
In this version the blockbuffer is not retained so no need to release it. However now I get a terrible static in the audio.
Anybody have an idea on how to solve this issue?
Thanks,
Ozgur
Answer: One way this is commonly done it to copy all the audio sample data from the unretained buffer into your own (pre-allocated and retained, lock-free) circular fifo buffer.  Then ignore the unretained buffer, as it will be released at some point.  Use the audio data in your own circular buffer.
Comment: In the second (alternative) implementation of  getAudioBufferDataFromCMSampleBufferRef, I have used CMBlockBufferCopyDataBytes(_blockBuffer,0,audioBufferByteSize,inputBuffer.mData); to copy the blockBuffer into my own buffer inputBuffer.mData. However in this case there is a strong static in the audio. inputBuffer is of type AudioBuffer. Do you have any idea how I can get rid of the static?
Comment: Is your own buffer a lock-free circular buffer multiple times larger than a single AudioBuffer?  If not, you might be overwriting data before you finish using it.
Comment: This is the way to go, especially if data gets encoded.  The codec will want a certain number of frames for each packet.  If there aren't enough samples left to complete a packet AudioConverterFillComplexBuffer should fail, and then roll the remaining samples into the next packet when there are more samples In your buffer.


How to determine if two rows are identical (similar) if row 2 contains part of the info from row 1?

Question: Hope you are having a good day. I am currently working with an extremely dirty dataframe containing First Name, Last Name, and Middle Name. One the issues that I am trying to resolve looks like below:

First Name
Last Name

James Agnew
Bond

James
Bond

Another similar issue that I am trying to resolve looks like follows:

First Name
Last Name

Jam
Bond

James
Bond

Looking forward to your ideas.
Thanks!
Edit: FYI, to make life simpler, I already have data grouped by address which is unique. So, two rows will have one address, another two or three rows will have another address, and so on.
Comment: Use `df.drop_duplicates('Address')` to keep only one instance of (First Name, Last Name)?
Comment: Not that easy. I have other rows with a similar issue (please see my other post). I could drop rows which are pure duplicates and then drop rows which are criss cross duplicates.
Comment: I tried to find a solution but it takes too many time because you need to check NxN combinations. Sorry :(
Answer: This is a not so simple problem. To check if 2 strings are 'similar' you must enter in non-Euclidean distance algorithm.
I mean, you must define a similarity function and 'understand' the distance between string.
jellyfish is a library born to solve these problems
Another approach is to collect all names and bind them to a thesaurus of names like this
With a some search,  I've found this
hope can help
Answer: If we just want to check that both elements in row2 are contained in the respective elements of row1, we just need one if statement
<code>row1 = ["James", "Bond"]
row2 = ["Jam", "Bo"]

if row2[0] in row1[0] and row2[1] in row1[1]:
    print("Similar!")
else:
    print("Not Similar!")
</code>
If you want to check the opposite case (that ro1 is in row2), just create a second if statement with 'row1' and 'row2' terms swapped.
Comment: What if we want to check for similar cases throughout the whole dataframe?
Comment: @IsaacA You'd have to compare each row against every other row. A nested for loop going over every possible 2-row combination would work.


Probability of $k$ fixed points for a random function from and to $\{1,..,n\}$

Question: I would like to derive the probability mass distribution $p_k$ of the number $k$ of fixed points of a random function from $A:=\{1,..,n\}$ to the same set.

I proceed computing the number of derangements $D_n$, as per a random permutation, obtaining:
$$ D_n = n^n - \binom n1 n^{n-1} + \binom n2 n^{n-2} - .. (-1)^k\binom nk n^{n-k}=\sum_{i=0}^n (-1)^i\binom ni n^{n-i}.$$

Then I compute the number of random functions with $k$ fixed points $n_k$ as the product of $\binom nk$ and $D_{n-k}$, as if to say that each function is composed by a $k$-subset of $A$ times a deranged $n-k$-disposition of the remaining $n-k$ elements of $A$:
$$n_k=\binom nk \sum_{i=0}^{n-k} (-1)^i\binom {n-k}i (n-k)^{n-k-i},$$

so that
$$p_k = \frac{n_k}{n^n}=\binom nk \sum_{i=0}^{n-k} (-1)^i\binom {n-k}i \frac{(n-k)^{n-k-i}}{n^n}.$$

To me it makes sense, but a quick check on Python shows me that $\sum_{k=0}^n p_k\neq 1$.
Any thoughts?
Comment: But $\binom{n}{k}D_{n-k}$ implies that your function is onto, no?
Comment: Do you require your random function to be a bijection (i.e., a permutation)?
Comment: Note... while there are $D_n$ **permutations** (*which are necessarily bijective*) over $n$ elements with no fixed points, there are $(n-1)^n$ **functions** (*not necessarily bijective*) with no fixed points.
Answer: As JMoravitz pointed out in a comment, to find the number of functions with $\ k\ $ fixed points you need to multiply $\ {n\choose k}\ $ by the number of functions with no fixed points on $\ n-k\ $ elements—namely $\ (n-1)^{n-k}\ $—, not the number of derangements. Thus,
\begin{align}
p_k&=\frac{{n\choose k}(n-1)^{n-k}}{n^n}\\
&= {n\choose k} \left(\frac{1}{n}\right) ^k\left(1-\frac{1}{n}\right)^{n-k}\ .
\end{align}
That is, the distribution of the number of fixed points is $\ Binomial\big(n, \frac{1}{n}\big)\ $.  Another way of seeing this is that each of the numbers $\ 1,2,\dots,n\ $ is independently and equally likely to be a fixed point with probability $\ \frac{1}{n}\ $.
Comment: right, thank you and to @JMoravitz


A (not for me) simple inequality

Question: I have some problems to understand the following situation:
Let $A=\{z\in\mathbb C : |z|\ge 1$ and $|\Re(z)|\le\frac{1}{2}\}$, then the inequality $|cz+d|\le 1$ with $c,d\in\mathbb Z$ doesn't have solutions in $A$ if $|c|\ge 2$.
I have tried to write
 $z=x+iy$ so
$|cz+d|^2=c^2(x^2+y^2)+d^2+2cdx\ge 5+2cdx...$
but probably this is the wrong way because there is the obnoxious term $2cdx$.
Answer: Draw a sketch of $A$ in the complex plane and note that the imaginary part of $z\in A$ must be (absolutely) at least $\frac{\sqrt 3}2$. Therefore, if $|c|>2$ the imaginary part of $cz+d$ is at least $\sqrt3$, which is more than $1$.

A (not for me) simple inequality


Como conseguir um IResource de um ICompilationUnit

Question: Estou fazendo um plugin no eclipse e quando seleciono uma classe java no Package Explorer acabo recebendo um objeto do tipo ICompilationUnit, mas preciso de um IResource, o que pode ser feito ?
Answer: tente o método getUnderlyingResource():
  public IResource obterIResourceDe(ICompilationUnit unit) {
    return unit.getUnderlyingResource();
  }

da documentação Javadoc.
Comment: Muito obrigado, funcionou perfeitamente.


Why would this not work in Spree

Question: I am having problems with modifying a function in spree. The function is called copy_price
The original version is something like this:
def copy_price
  if variant
    self.price = variant.price if price.nil?
    self.currency = variant.currency if currency.nil?
  end
end

which if I understand right will update the line_item's unit price only if the price is null, which I believe it shouldn't be inside the orders page (after the order is completed).
I noticed that order changes if the master price is changed inside the admin section even after the order is complete.
So i thought that the copy_price function was to blame, but each time i try to modify it there is no change.
E.g.
def copy_price
  @price_run = true
   self.price = 30.00
end

def get_price_run
  if @price_run == true
    return "true"
  else
    return "false"
  end
end

and call get_price_run inside my view to print out if the price run was actually run. and It keeps outputting false. Does anyone know why that would be.
Answer: I have figured out the problem. The function copy_price is only called when the line item is first created (e.g. when you put it into the cart). So when I was trying to find out if it was called while looking at the admin orders page it was never getting called.

Why would this not work in Spree


wds: deploying applications too?

Question: I have started using WDS to setup win7 client machines. The next step is deploying specific applications (both MSFT and non-). Can WDS be used for this or is there a recommended solution that I can tie in with it?
Comment: As Bart has metioned, WDS is just for system images - but don't forget the system image could contain commonly-used software. You might run into activation/license issues with things like Office though. The way our build process works is that the system gets re-imaged and then Office pushed out through GPO. We have CS5 on some of our laptops as well - they are part of the image as we had issues trying to deploy several GB of stuff over a MSI.
Comment: So if I wanted Chrome or OpenVPN installed.. is this the sort of thing that SCCM is used for? The distinctions between all these products is still quite hazy in my head.
Comment: I don't know, as we don't use SCCM - but I believe you are corrct.
Answer: Allow me to add to Tim's suggestion of MDT...
MDT allows you to install applications (even 3rd party applications like Adobe reader), updates, and drivers. In the How-to Videos section of this page, the second video is all about using MDT to deploy Windows and Office.
More information on using MDT to deploy can be found on the Windows 7 Springboard pages.
And remember, MDT is free and will integrate with your WDS server or SCCM.
Answer: There are a couple ways you could go about this.
You can capture an image with your desired software installed. This isn't a favorite of mine since it tends to age badly and be more work than it is worth.
I suggest you look at the Microsoft Deployment Toolkit to deploy out images as part of your process. This allows for scripted installations. This includes driver injection and the ability do silient installs as part of the deploy process.
It works pretty well, plus it is a free product. I used this method for a while before settling with the method outlined below.
My favorite method is using EminentWare (now Solar Winds Patch Manager) to push out both full packages and updates. When I image in this fashion I  use WDS to do a network boot and pull down a lite touch MDT image. I have a small script that pulls down all of the available Windows Updates in this process. Whatever updates and packages I have approved for my build will automatically be pushed out and installed.
This results in a perfectly built reproducible and fully up to date system every time.
EDIT -
Although I have a strong leaning to EminentWare SCCM (and likely a couple other products) can be used in the same fashion.
Answer: WDS is for deploying Windows system images. To deploy applications, you can deploy MSI installers via GPO, or you can look for third-party installer software to handle it. Or use products that deploy them from a central server like appdeploy from VMWare.

wds: deploying applications too?


Compile a debian package for amd64 on a i386 machine?

Question: I have a i386 ubuntu hardy machine, and an amd64 ubuntu hardy machine. I want to compile a debian package (a.k.a. deb) for the amd64 machine on the i386 (because I don't have enough memory to compile is quickly on the amd64 machine). If I do a dpkg-buildpackage on the i386 machine, it produces a deb for i386, which can't be installed on the amd64 machine. Is there anyway to compile the deb for amd64 on the i386 machine?
Comment: This may include some of what you need.http://wiki.debian.org/DebianAMD64Faq
Comment: For the flaggers: compiling software is well within administrative responsibilities and does not automatically belong on Stackoverflow, especially in the case of package creating.
Comment: I am a bit confused about why you would be using amd64 on a system with low amounts of memory.  Does your i386 have a 64bit capable processor?  I would guess you could boot amd64 temporarily from a livecd or something to do your compilation.
Comment: @Zoredache, that FAQ is good, and explains how to compile a i386 deb on an amd64 machine, but not the reverse
Comment: it does include how to compile a 64bit kernel on i386.  But I agree that it doesn't tell give details for your specific situation, which is why I added it as a comment.
Comment: Quick and dirty - fire up a machine at amazon to do the compiles.  This requires getting up to speed with amazon, but it's not too difficult.
Answer: So, there are some solutions to that:

Setup a cross-compiling toolchain and use regular dpkg-buildpackage to build your package. The problem is that creating a toolchain is not very straightforward.
Use a 32 bit chroot on your 64 bit machine to compile stuff. Apparently it's the most recommended method. This blog post has an example of kernel compilation but it's the same process for any other software.
Comment: 32 bit chroot on a 64 bit machine, is not very helpful. I want to compile a 64 bit deb on a 32 bit machine. I can't do any compiling on my 64 bit machine. And I'm pretty sure you can't run a 64 bit chroot on a 32 bit machine.
Comment: Ahh sorry I misread your question then. Maybe cross compiling works?
Answer: It's probably more trouble than it's worth to try and get cross compiling going.  There are various ways to emulate 64 bit systems on 32 bits, but you'll pay a perfomance price.
If you're only doing a bit of this, then I'd say fire up a 64 bit machine on Amazon for a few hours.  If you're doing it a lot, then maybe get some 64 bit hardware, or maybe AWS remains interesting, because you only pay for how much you use it, and you can fire up a build farm when you want it.
This might give you some useful ideas:  http://blog.fwbuilder.org/2009/05/building-ubuntu-deb-packages-on-amazon.html
This list of images of debian systems for various architectures and releases might be useful too:  https://wiki.debian.org/Cloud/AmazonEC2Image
Answer: One thing I do on Debian all the time is use a 64-bit kernel with a 32-bit userland for my normal system, and then create a chroot with 64-bit userland to build amd64 packages.  The structure of the kernel packages in Ubuntu is a bit different, so I don't know if this is possible or recommendable there.
Other than that, the clean solution is to use a virtual machine.  QEMU is the obvious choice, because it can emulate just about anything on anything (and it's free).  You can use qemubuilder (packaged in Ubuntu) to integrate the build with pbuilder.  This can be a bit tricky to set up in my experience, but it might be worth it if you need to do this repeatedly.  For a few packages, just fire up QEMU and log in by hand.
If you are very adventurous you can also try cross-compiling, but this is probably much more difficult and doesn't work with all packages.  Look for dpkg-cross to get started.
Or how about you create a Personal Package Archive (PPA) on Launchpad and have your package be autobuilt there.
Comment: The OP asks for 64bit target with a 32bit machine, not the contrary
Comment: it may be relevant - sometimes folks run a 32-bit OS on 64-bit hardware.


Get Mako template from within Pyramid app view

Question: I'm currently using the Pyramid web framework and I have it configured with Mako templates. I know that I can render a template as a string from within a view method (Pyramid - Is it possible to render my mako template as a string within my view callable?), however, I was wondering if it is possible to get the actual template object from within a view and not just a function to render the template.
Looking through the Pyramid source code, in mako_templating.py I see that the default TemplateLookup class is overridden with a lookup method for Pyramid. Is there anyway to access this lookup object primarily so I can use the get_template function that is part of it?
Thanks for any direction on this issue.
Answer: This level of introspection is not officially supported by Pyramid's rendering API. That being said, here's a way to do it. This is completely undocumented, unsupported, private, etc, etc. Meaning, don't come complaining when this stops working.
from pyramid.mako_templating import IMakoLookup
lookup = request.registry.queryUtility(IMakoLookup, name='mako.')
tmpl = lookup.get_template('myapp:templates/foo.mako')

opts = {} # rendering context
result = tmpl.render_unicode(**opts)

Comment: Thanks for you answer, Michael! In the end, I decided to implement a separate Mako Templatelookup instance using the projects configuration settings.
Answer: This works for me:
from pyramid.renderers import render
sRenderedStuff = render('path/to/template.mak',dContext)

An example use case would be something like this:
sEmailHtml = render("email/welcome_message_html.mak",dContext)

With the following line in your pyramid settings file:
mako.directories = your_app:templates

The template is fetched from your_app/templates/email/welcome_message.html. All inheritance and include tags work just as they would for templates rendered to a view response.
Comment: Although this works, my question was geared toward using the TemplateLookup instance that's already configured for the application. Calling the `render` function like this does not take into account the existing template configuration.


Improve querying table using dates

Question: I have a table that contains a huge amount of data and I want to query it using a date range.
Here's the query
<code>SELECT TOP (10000)
    [PositionId] AS [PositionId],
    [DeviceId] AS [DeviceId],
    [Course] AS [Course],
    [Latitude] AS [Latitude],
    [Longitude] AS [Longitude],
    [Speed] AS [Speed],
    [MomentTiming] AS [MomentTiming],
    [Fuel] AS [Fuel],
    [Ignition] AS [Ignition]
 FROM
    [PositionInsights]
 WHERE
    deviceId = 352
    AND [MomentTiming] >= '8/12/2015 7:38:00 AM'
    AND [MomentTiming] <= '8/12/2015 3:38:00 PM'
</code>
The problem is that this simple query takes too much time, about 35 sec
Comment: What indices are on the table? If there is no index on the field `deviceId`, adding an index on this field will improve the performance.  What is the clustered Index ? If this is the most common (frequent) query run against this table, I I would suggest a cliustered Index on the columns `deviceId`, `MomentTiming`, and whatever the Prtimary Key Column is.
Comment: how many records you have in the table?
Comment: visit this link may help, http://stackoverflow.com/questions/1716798/sql-server-2008-ordering-by-datetime-is-too-slow
Comment: @NickBullatovci millions of records
Comment: @CharlesBretana the only index that exists is on the primary key positionId
Comment: see my answer, you need to start with indexing the fields in your where clause
Comment: Change the clustered index (currently only on `positionId`) to be a clustered Index on (`deviceId`, `MomentTiming`, and `positionId`) in that order.
Answer: As a general rule, any fields in your where clause should be indexed. And you should make sure the indexes are not fragmented over time if you are doing a lot of CRUD on the table(s).
So I would create two separate indexes, one on the deviceid field and another on the MomentTiming field.
If your table is in the millions or billions of rows, you will probably want to set up table partitions on one of those fields. If the deviceid field is an autonumber field, then that might be a good enough range partitioning value, otherwise partition on your MomentTiming date field. If you partition, keep the indexes the same as I described.
UPDATE: since you only have millions, not billions, of rows, just start with the indexing and see what happens. However, if your data is growing fast, you may want to look at partitioning anyway. Also, if you go the partitioning route, you should try to put the different files on different mountpoints to get the best performance.
HTH
Comment: datetimes are already a numeric value presented as a datetime. I doubt this would boost performance at all
Comment: another thought is that you could store your dates as bigints, since there is a lot of opinion out there that number-based indexes often provide faster lookups

Improve querying table using dates


Differential Geometry on the Sphere: Integration by Parts, Volume Form,Stokes Theorem

Question: I was trying to work out a integration by parts formula $S^2$ of the form
$$\int_{S^2}f(x)\frac{\partial g}{\partial x_1}dx \tag{1}$$
where $f,g:\mathbb{R}^3\rightarrow\mathbb{R}$. Given $g$ and $\tilde{g}$ that agree on $S^2$, I am not sure if (1) independent from which of the two we choose.
Having realized this I tried two work purely on the manifolds. Does anyone know a good reference that explains how to use Stokes Theorem and an the volume form associated with the Riemanian metric to derive a integration by parts formula.
Thank you,
warsaga
Comment: What is $\widetilde{g}$?
Comment: $\tilde{g}$ is another function $\tilde{g}:\mathbb{R}\rightarrow\mathbb{R}$. $g=\tilde{g}$ on $S^2$. Is (1) dependent on the particular choice of $g$?
Answer: Here's a general integration-by-parts using Stokes' theorem.  I saw this in class, so I don't recall reading this in a text, but I'm sure it's covered in any text that covers differential forms --- try Principles of Mathematical Analysis (Rudin), or Differential Topology (Guillemin-Pollack).
Remember that if $\alpha,\beta$ are respectively $k-1$ and $n-k$-forms on $M$, then $$d(\alpha\wedge\beta) = (d\alpha)\wedge\beta + (-1)^k\alpha\wedge (d\beta).$$  We have required that $\alpha$ and $\beta$ be $k-1$ and $n-k$ forms so that $d(\alpha\wedge\beta)$ is a multiple of the volume form and so can be integrated against $M$ instead of a submanifold of $M$.
Now we can use this formula and Stokes' theorem:
\begin{align*}\int_M d\alpha\wedge\beta &= \int_M \bigg(d(\alpha\wedge\beta) - (1)^k\alpha\wedge (d\beta)\bigg) \\
&= \int_{\partial M}\alpha\wedge\beta + (-1)^{k+1} \int_M \alpha\wedge (d\beta)
\end{align*}
Note that if $M$ is closed, the term integrating over the boundary vanishes.
This formula recovers integration by parts on the real line.  Let $M = [a,b]\subset \mathbb{R}$, so that $\partial M = \{a\}\cup\{b\}$.  If $f$ is a function, then $df = \frac{df}{dx}dx$.  Integrating by parts is expressed by:
$$\int_a^b \frac{df}{dx}gdx = \int_a^b df\wedge g = \int_{\partial M} fg - \int_a^b f\wedge dg = (fg)\bigg|_a^b - \int_a^bf\frac{dg}{dx}dx.$$
Integration of the zero-form $fg$ over $\partial M$ is signed evaluation.

In response to the question in comments below, integrating a top-dimensional form is exactly the same as integrating a function against the measure induced by the volume form.  On an orientable manifold $M$, the top exterior bundle $\Lambda^nM$ is a trivializable rank $1$ bundle.  Choice of a volume form  $Vol$ trivializes the bundle, hence induces an isomorphism ($C^\infty(M)$-modules) $\Omega^n(M)\cong C^\infty(M)$, where $1\leftrightarrow Vol$.  So integrating a function against the volume measure is the same as integrating its corresponding $n$-form.
Comment: Thanks for the good answer. How does this relate to integrating functions (not forms) against the measure associated with the riemanian metric.
Comment: I'll try to find time tomorrow morning to edit additional information in to my answer.
Comment: I appreciate your help.
Comment: @warsaga I'm sorry to not get to the edit - I'm having an extremely busy week.  Just letting you know I haven't forgotten.
Comment: It would be great if you find time to explain it.
Comment: @warsaga I think that should answer your question.
Answer: Just to give an alternative way of looking at things, here's a look at integration by parts through Clifford (geometric) algebra.
$$\oint_{\partial V} A(x) \; dS \; B(x) = \int_V \dot A(x) \dot \nabla \cdot dV \;  B(x) + \int_V A(x) \dot \nabla \cdot dV \; \dot B(x)$$
The overdots denote which function the vector derivative $\nabla$ acts on, even though its vector character has a certain position within the expression.  Note that $dS, dV$ are not scalars but rather multivectors appropriate to the type of object being integrated over.  All products are the "geometric" product, combining the inner and outer products, except where others are explicitly denoted by $\cdot$ or $\wedge$.
An integration by parts formula follows from isolating one of the "volume" integrals on the right.  Nevertheless, if you have this integral over a sphere and you want to use integration by parts, I don't think you're going to find much help if you want to consider the sphere $V$ in this problem, as a sphere has no boundary.  If you consider the sphere $\partial V$, the boundary of the volume, then you will get terms involving further derivatives of $\partial g/\partial x_1$. Furthermore, you said that $g,\tilde g$ agree on the sphere, but nothing about their derivatives.  It seems to me that there's no need for your (1) to be the same between the two because you've explicitly written it with a derivative.


Should the UI layer be able to pass lambda expressions into the service layer instead of calling a specific method?

Question: The ASP.NET project I am working on has 3 layers; UI, BLL, and DAL.  I wanted to know if it was acceptable for the UI to pass a lambda expression to the BLL, or if the UI should pass parameters and the Service method should use those parameters to construct the lambda expression?  Here is an example class showing both senarios.
public class JobService
{
    IRepository<Job> _repository;

    public JobService(IRepository<Job> repository)
    {
        _repository = repository;
    }

    public Job GetJob(int jobID)
    {
        return _repository.Get(x => x.JobID == jobID).FirstOrDefault();
    }

    public IEnumerable<Job> Get(Expression<Func<Job, bool>> predicate)
    {
        return _repository.Get(predicate);
    }
}

For the above class is it acceptable for the UI to call the following:
JobService jobService = new JobService(new Repository<Job>());
Job job = jobService.Get(x => x.JobID == 1).FirstOrDefault();

or should it only be allowed to call GetJob(int jobID)?
This is a simple example, and my question is in general, should the UI layer be able to pass lambda expressions into the service layer instead of calling a specific method?
Answer: This is a judgement call based on the situation.  It's not necessarily wrong to pass in a predicate like this.  I think it should be considered a minor bad smell though.
If the passing in of a lambda expression allows you to reduce 6 methods down to 1, then it might be a good move.  On the other hand, if you can just as easily pass in a simple type, then lambda syntax is a needless complication.
In the above example, not knowing the context, my preference would be to use a simple integer parameter.  There should usually be a basic method that just gets a record by it's ID.  And maybe one or two other such methods that are repeatedly used through your application.  And then maybe a general purpose method that takes a lambda.
You should also consider what some would suggest should be a rule:  that you not have any methods with lambda-specified predicates between your UI and your business layer.  (And some believe, with reason, that your repositories shouldn't even have such methods!)  I don't believe this should be an iron-clad rule, but there's good reasons for it.  Your business and data layers, between them, should keep dangerous queries from happening.  If you allow the passing in of lambdas, it's very easy for a junior developer in the UI layer to specify queries that could really hose your database.  (For example, they'll do huge queries against non-indexed fields, and/or filter against the resultset using LINQ-to-objects, and not realize how inefficient that is.)
Like many other good practices, this will depend somewhat on scope.  In my recent large application, I have no passing of lambda syntax from the UI layer to the business layer.  My plan was to invest heavily in the business layer, to make it very smart.  It has all the needed methods with simple types.  In fact, it typically gives you what you need through simple domain object properties, with no parameters at all.  My interface assures that the UI can only cause efficient queries to happen, with perhaps just minor LINQ-to-Objects predicates in the UI layer.  (This goes even for "search" pages.  My business layer accepts a criteria object with constrained possibilities, and ensures an efficient query.)
Now, you said "layers", rather than "tiers".  So these are all in the same assembly?  Another disadvantage of lambda is they're (currently) difficult to serialize.  So you'd regret them if you had to separate your tiers.
Answer: This is always a moot point as to which 'layer' that exposing Expression trees (and IQueryables) should be limited to.
So first the obvious - the main benefit of allowing an IQueryable lambda into a layer obviously allows for enormous flexibility in the query, without the need for writing lots of GetXXXByYYY type methods. Client layers can also directly control the joins by using .Include to specify the depth of graph retrieval, and can control ordering (.OrderBy), grouping (.GroupBy), row limits (.Take) in the database, which generally will have performance gains over doing the same thing in memory.
The downsides include:

Testability - because the interface is so open, there are an arbitrarily large number of permutations to check.
Trust - clients of your layer have free reign to execute arbitrary queries against your database, which could have performance issues (i.e. clients could execute queries which miss all the Indexes) and security issues (retrieving data to which they should not have access).
Serialization - Expression Trees can't be directly serialized, so you couldn't expose your BLL across e.g. WCF (although they can be proxied)

If you do allow the Expression tree as a parameter, then I would suggest you go 'all the way' and return IQueryable instead of IEnumerable. This will allow the queries to be chained / aggregated (e.g. you can amend the query later on, before materialising it)
Personally we don't permit expression trees past our BLL, so we wouldn't extend this to our UI - IMO Expression<> predicates are seen as mechanism of implementing Evan's specification pattern.
Answer: Assuming that the reason why you're thinking it may not be appropriate is that it might violate the encapsulation of the BLL, I'm going to go with it depends.
Delegates and lambda expressions are basic language constructs so the simple act of using them doesn't break any encapsulation per se.
The exception is of course if the signature of the delegate passed as argument to a method exposes a type that should not be accessed directly from within the caller's scope. Let me give you an example:
// Bad
public IEnumerable<Job> Get(Action<SqlCommand> queryCommand);

// Good
public IEnumerable<Job> Get(Func<Job, bool> predicate);

In the first example the method signature breaks encapsulation by exposing an implementation detail to the caller in the form of the SqlCommand type. It also grants the caller too much freedom by allowing it to specify any query as argument, which is plain dangerous.
In the second example, on the other hand, the method signature simple exposes a model class, which is already part of the layer's public interface. It doesn't increase the surface area of the API nor does it expose any details about how the operation is implemented.
Answer: I personally do not like this. I guess it isn't wrong, but it creates a grey area of where you should be writing your queries.  I think that when someone else comes into my application, and all of the expressions are in one nice layer, it makes it easier to navigate.
Answer: I would not do that. It's bad practice. It's legal, but bad.
You are adding DAL logic to the UI rendering your DAL as a wrapper. Your UI should only pass parameters to the BLL or DAL, not perform the logic for getting the data.
Answer: This is just my opinion but what you are trying to write looks similar to how a LINQ expression is written, so if it is good enough for LINQ then why not you?
If you think it makes your job easier then I don't see why you shouldn't do it. The only thing I would be wary of is making sure it is easy to maintain i.e. being able to keep track of all these lambdas you are passing about.


Google App Engine Python: How to display textarea value in mail

Question: I have a html form with <textarea name="message"></textarea> and I get the value by message  = self.request.get('message').
Then I do mail api
message = mail.EmailMessage(sender="email@example.com", subject="Testing")
message.to = 'email@example.com'
message.html = """The Message: %s """ % (message)
message.send()

The problem is I can only see the "The Message:" in my email without the 'message' value, how do I solve the problem?
Answer: You're using the variable name 'message' for both the original text in the textarea, and the email you're sending. Try this:
text = self.request.get('message')
message = mail.EmailMessage(sender="firstname.lastname@example.com", subject="Testing")
message.to = 'email@example.com'
message.html = """The Message: %s """ % (text)
message.send()

Answer: I'm not familiar with the GAE mail api but you seem to reassign the message variable name to a new item, in this case an object, then you try to make the object the message body. :s
Try something like:
message = self.request.get('message')
mailer = mail.EmailMessage(sender="firstname.lastname@example.com", subject="Testing")
mailer.to = 'firstname.lastname@example.com'
mailer.html = """The Message: %s """ % (message)
mailer.send()

In production you would probably also want to do a null check for the message variable's value.


Where does drush look for the path of the mysql socket (on MAMP)?

Question: After upgrading from drush 6.5.0 to 8.0.1-dev through brew, the drush terminal command returns the popular

'PDOException: SQLSTATE[HY000] [2002]' error.

The only way to make it work is to add the unix_socket line to my Drupal settings.php files for all my projects:
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'site',
      'username' => 'user',
      'password' => 'pass',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
    ),
  ),
);

Even if I use /var/mysql/mysql.sock, it will work, because I have a symlink up:
lrwxr-xr-x  1 root  wheel    39B Mar 11  2015 /var/mysql/mysql.sock -> /Applications/MAMP/tmp/mysql/mysql.sock

But that is exactly the thing I don't understand. And I would like to configure it at one point so I don't have to edit all the current and upcoming project's settings.php files.
So my question is: Where does drush look for the path of the mysql socket (on MAMP)?
If it's through the php.ini, it should be correct too (/Applications/MAMP/bin/php/php5.6.10/conf/php.ini):
mysql.default_socket = /Applications/MAMP/tmp/mysql/mysql.sock

Currently, my .bash_profile contains no alias or export related to this issue because it worked fine with my previous drush installation.
Comment: use 'host' => '127.0.0.1' instead of localhost.
Answer: First of all, check which php and php.ini file is used by drush:
$ drush status --full
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database username               :  root
 Database name                   :  drupal7
 Drupal bootstrap                :  Successful
 Drupal user                     :
 PHP executable                  :  /usr/local/opt/php56/bin/php
 PHP configuration               :  /usr/local/etc/php/5.6/php.ini

Then edit its default MySQL socket name for local db connects:
pdo_mysql.default_socket=/path/to/mysql.sock

as by default it points to /tmp/mysql.sock unless PHP was configured with different (--with-mysql-sock).
Check by:
$ php -i | grep ^pdo_mysql.default_socket
pdo_mysql.default_socket => /tmp/mysql.sock => /tmp/mysql.sock

So probably that's why /var/mysql/mysql.sock didn't work, as it was looking for /tmp/mysql.sock instead.
Then the symbolic link should work as expected.
If drush is using wrong instance of PHP, then add it into PATH (as you did) or specify with --php=</path/to/file>, so the right php.ini would be loaded.
Alternatively specify unix_socket in your settings file (as you already did).
Comment: probably /usr/local/etc/php/5.6/php.ini was used and indeed, pdo_mysql.default_socket was not even set there
Comment: As well as `drush status --full`, check `php -i` and look for "Additional .ini files parsed" - these are a common place to override settings in your main `php.ini`.
Answer: Found the solution ...
drush status

shows the PHP executable path was the OSX native one, which was then symlinked to a PHP installed by brew
adding the following line to ~/.bash_profile
export PATH="/Applications/MAMP/bin/php/php5.6.10/bin:/Applications/MAMP/Library/bin:$PATH"

made drush look up into the correct php.ini file
but to me, it is still a mystery why the symlink
lrwxr-xr-x  1 root  wheel    39B Mar 11  2015 /var/mysql/mysql.sock -> /Applications/MAMP/tmp/mysql/mysql.sock

did not do the trick


swift 3 iOS tableview datasource memory

Question: I have a tableview which acts as a newsfeed. The cells are filled from an array of newsfeed items. I get the JSON from the Server, create newsfeed items from that input and attach them to my newsfeed array. a newsfeed item contains a title, a description and an imageurl string.
At:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "ImageFeedItemTableViewCell1", for: indexPath) as! ImageFeedItemTableViewCell
    var item = self.feed!.items[indexPath.row]
    if (item.messageType == 1){
    cell = tableView.dequeueReusableCell(withIdentifier: "ImageFeedItemTableViewCell1", for: indexPath) as! ImageFeedItemTableViewCell
    cell.title.text = item.title
    cell.description.text = item.contentText

    if (item.imageURL as URL == URL(string: "noPicture")!)
    {
      cell.picture.image = UIImage(named:"empty")
    }
    else{

    if (item.cachedImage == UIImage(named:"default-placeholder")){
    let request = URLRequest(url: item.imageURL as URL)
    cell.picture.image = item.cachedImage
    cell.dataTask = self.urlSession.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
        OperationQueue.main.addOperation({ () -> Void in
            if error == nil && data != nil {
                let image = UIImage(data: data!)
                if (image != nil){
              self.feed!.items[indexPath.row].cachedImage = image!
                }
                cell.picture.image = image

             }

        })

    })
        cell.dataTask?.resume()
    }else
    {
        cell.picture.image = item.cachedImage
    }
    }

}

the cells from the rows get filled with my newsfeeditem data.
But since i keep all my newsfeeditems inside an array, the memory usage is high and gehts higher for each additional newsfeeditem. I want it to work with endless scrolling like twitter, so i wonder how experienced developers tackle this memory issue.
Comment: please add the cellForRowAt method as a code snippet
Comment: pagination is a good way to implemented if there are lots of feeds
Comment: i thought about that as well. what kind of pagination? page index numbers look outdated, so i thought about twitter, they load new tweets when you reach the bottom, but you can scroll up again without loading, which means that they save the data somewhere and i wonder where since keeping all tweets in memory would crash the app i guess.
Comment: i have added the missing code!
Comment: normal data can be saved in array. but information like images can be fetched and set. Kingfishers and alamofireImage can help cache it too.\
Answer: Your problem is in this lines or wherever you try to hold UIImage inside your array, this is really not advised and will cause crash due to memory since image is very large data and not advised to persist it in your RAM with UIImage inside array:
self.feed!.items[indexPath.row].cachedImage = image!
What you need to do is basically after fetch your image from URL, you save it to your app's documents folder and save the name or it's path that can distinct your image in cachedImage (just change the type to string or sth) and refetch it from your app's document folder when you need to show it in cellForRow
Flow: Fetch image -> save to disk and persist path in array -> refetch from disk with the path in cellForRow
Comment: Ok i heard that i can reach that behaviour using SDWebImage, is that right? But what if i never had an image inside the cell, the memory would rise even with text only newsfeed items doesn't it?
Comment: Yes, `SDWebImage` will help you do all the step above with little code
Comment: how can i make the items from the array only load into the memory when needed?
Comment: i edited my answer just seconds before you answered, sorry
Comment: Because the memory is not from the cell, but from the array, its your array that make this behavior and raise your memory, the cell is just showing whatever is holding in your array
Comment: You cant, array is persist in RAM until your viewcontroller is deallocated, you have to persist as little resource as possible, thats why im telling you to store the image to disk and save it's path into your array
Comment: @JochenÖsterreicher, If you are worried about the memory footprint caused by saving a large amount of text you can also use some third-party caching lib such as [this](https://github.com/hyperoslo/Cache). But, as always, before complicating things you should carefully measure current memory usage with the help of Xcode profile tools.

swift 3 iOS tableview datasource memory


Global object constructor isn't getting called

Question: Somehow my global objects are created without having their respective constructors called:
static int num = 0;
class TestClass
{
public:
    int a;
    float b;
    TestClass(float f)
    {
        a = 55;
        b = f;
        ++num;
    }
};
TestClass test(32);

int main(int argc,char *argv[])
{
    std::cout<<"Int: "<<test.a<<std::endl;
    std::cout<<"Float: "<<test.b<<std::endl;
    std::cout<<"Constructor has been called "<<num<<" times"<<std::endl;
    while(true);
    return 0;
}

The output is:
Int: 0
Float: 0
Constructor has been called 0 times

I've used constructors like this in different projects before and never ran into any problems like this.
I've tried a parameterless constructor and making the test-variable static, neither had any different effect.
Can anyone enlighten me about what's going on here?
I'm using visual studio 2010, in case that makes any difference.
Comment: Is this your exact code? Specifically are the global `TestClass test` and `int num` counter in the same file?
Comment: @Silverlan well it can't be this *exact* code since this is missing `#include `.
Comment: @Silverlan does this **exact** code demonstrate the issue on your machine?
Comment: In case anyone's interested, [on ideone](http://ideone.com/3pnvDc) it works just fine.
Comment: Your code gives me the correct output.
Comment: Yes, it's all in the same file and I've tried it with this exact code. And no, I haven't changed the entry point, just checked it to be sure.
Comment: Just ran the code on VS 2010 as well, also no problems, prints expected values.
Comment: VS 2012 produces the expected output as well. Is this code in a library? If yes, you might want to check my answer below.
Comment: voting to close as the posted code does not reproduce the problem
Comment: `while(true);` is UB BTW...
Answer: I'm not completely sure but this might answer your question: http://www.nsnam.org/docs/linker-problems.doc
Edited to add more information:
The document points out problems that can occur when using global constructors in different compilation units. For example if you define an object globally in some dynamically linked library, its object constructor might not be called when accessing a method from this library.
To use the example from the original question: The class TestClass and the global object test might be in TestLibrary.dll while the main() function is in some executable file. Depending on how the TestLibrary.dll is loaded and the test object is accessed from the executable, its constructor might never get called because the library is never "informed" that it was just loaded (or to put it differently: the global initialization function was never called).
Comment: Could you summarize the contents of this link for those who don't have Word and in case the link stops working?
Comment: ... and specifically which part of the 17 page document fixes the problem. Useful links are encouraged, but they should generally be comments instead of answers, **unless** you **fully** answer the question and just include the link in a "this is where I found it" kind of way.
Comment: You're right. Sorry. I just added some more information to make this answer more helpful.
Answer: If you compile your project, which you link into your Executable, to an Executable-File, Visual Studio will link everything fine, but your Global-Constructor will not get invoked.


Update existing foreign key values using eloquent

Question: I am trying to update multiple rows of data with existing foreign key values where basket should only link to the foreign ID of 100.
Example:

id
title
basket_id (foreign key to another table)

1
apple
100

2
banana
200

2
kiwi
300

What I have tried:
$fruits = Fruit::whereIn('basket', [200, 300])->get();

foreach ($fruits as $fruit) {
  $fruit->update([
    "basket_id" => 100
  ])
}

This works fine, however, when I print $fruit, I am still getting the old basket_id in the relations attribute in eloquent.
Am I missing a step?
Thanks
Answer: To fetch it, you can use the fresh() or refresh() on $fruit object, like this:
$fruits = Fruit::whereIn('basket', [200, 300])->get();

foreach ($fruits as $fruit) {
  $fruit->update([
    "basket_id" => 100
  ]);
  $fruit->refresh(); // Fetch updated object
}

https://laravel.com/docs/10.x/eloquent#refreshing-models

The fresh method will re-retrieve the model from the database. The existing model instance will not be affected:
$flight = Flight::where('number', 'FR 900')->first();
$freshFlight = $flight->fresh();

The refresh method will re-hydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well:
$flight = Flight::where('number', 'FR 900')->first();
$flight->number = 'FR 456';
$flight->refresh();
$flight->number; // "FR 900"

Comment: Thank you, do I need to a save() after?
Comment: No. `update()` method already performs a save operation
Comment: I see, what does `refresh()` do? does it do any updates to the DB?
Comment: `refresh()` method is used to reload the entire model instance and its relationships from the database, discarding any changes made to the model instance.
Comment: When you call `$fruit->refresh()`, eloquent will reload the entire `$fruit` object from the database, along with its related object. @cafe123


Como carregar classes com autoload em servidor web e local

Question: Estou precisando fazer com que o meu arquivo que faz a instância das classes do meu projeto funcione tanto no servidor web como no servidor local.
Esse é o arquivo que faz o autoload, o autoload.php
<?php
spl_autoload_register ( function ($classe){
    $classesDiretorio = __DIR__.'/classes/';

    $classesArquivo = $classesDiretorio . ' / ' . $classe . '.php';

    if(file_exists($classesArquivo)){
        require_once ($classesArquivo)
    }
});

No xampp, ele funciona direitinho, porém quando subo para o site, ele dá erro no endereço do caminho.
Segue o erro:

Fatal error: Class 'Cliente' not found in
  /home/diego325/public_html/temporario/rental/cadastro.php
  on line 13

Como posso fazer com que o autoload pegue os caminhos tanto no servidor local como no servidor web?
Acredito que o meu problema é semelhante a esse:
Problemas com autoload no PHP
Porém no problema mencionado acima não houve uma solução.
Comment: Aparentemente não há nada errado. O código que apresentou funciona bem em ambientes diversos, exceto pelo uso da constante `__DIR__` pois essa é disponível a partir do PHP5.3 http://php.net/manual/en/language.constants.predefined.php. Se não for esse o problema, verifique se os nomes dos arquivos estão de acordo, com letras maiúsculas e minúsculas. O sistema de arquivos do linux é case sensitive. Se o arquivo for **cliente.php**, vai dar esse erro. Deve ser **Cliente.php** (presumo).
Comment: podes sempre experimentar substituir o `__DIR__` por `dirname(__FILE__)` e ver se resolve o problema. Deves também levar em consideração o `/`, que pode variar a critério do servidor, DIRECTORY_SEPARATOR ?
Comment: Existe um diretório chamado `classes` em `/temporario/rental/`, contendo o arquivo `Cliente.php`?
Comment: Opa Wanderson, tem sim. É esse que uso para instanciar a classe Cliente.
Comment: Então Daniel, é esse __DIR__ mesmo que está dando o problema. No meu caso é servidor linux mesmo. A versão do php no servidor é 5.6.30. Tentei fazer uso dos valores de $_SERVER, mas não tive sucesso.
Answer: DEFINE('DS', DIRECTORY_SEPARATOR);
DEFINE('ROOT', dirname(__FILE__));
DEFINE('PUBLIC_PATH', ROOT . DS . 'public');
DEFINE('PRIVATE_PATH', ROOT . DS . 'private');
DEFINE('LIB_PATH', PRIVATE_PATH . DS . 'lib');
DEFINE('CLASS_PATH', LIB_PATH . DS . 'classes');

spl_autoload_register(function($class){
    foreach(get_defined_constants(true)['user'] as $path)
    {
        if($path === DS){ continue; }
        if(file_exists($path . DS . $class . '.php')){
            require_once $path . DS . $class . '.php';
        }
    }
});

Fora isso, que pessoalmente não sei quão eficiente ou problemático poderá ser, ainda assim é funcional. Podes também optar pela definição através de arrays, especificando os directórios a serem verificados para o carregamento automático que acho bem mais fácil de se usar.
Answer: Como o post é antigo, talvez vc. já tenha resolvido...
Eu uso Xampp (MacOs) e coloco sempre meus includes fora da raiz, por segurança.
Mas não uso o DIR e sim o $_SERVER['DOCUMENT_ROOT'] para definir o path, seja no servidor local ou remoto:
    define('INC_PATH',str_replace('/www','',$_SERVER['DOCUMENT_ROOT']).'meudiretoriodeincludes/');

ou, dependendo do servidor remoto, adicione uma barra antes do diretório de includes:
    define('INC_PATH',str_replace('/www','',$_SERVER['DOCUMENT_ROOT']).'/meudiretoriodeincludes/');

Resolvido o path...


ASP.NET Route config for Backbone Routes with PushState

Question: I have run into an issue recently where we have been told to remove the hash symbols from our Backbone applications. This presents two problems: (a) the ASP.NET routes need to handle any remotely linked URL (currently this is no problem with the hash symbols) so that we're not hitting a 404 error and (b) the proper route needs to be preserved and passed on to the client side (Backbone) application. We're currently using ASP.NET MVC5 and Web API 2 for our backend.
The setup
For an example (and test project), I've created a test project with Backbone - a simple C# ASP.NET MVC5 Web Application. It is pretty simple (here is a copy of the index.cshtml file, please ignore what is commented out as they'll be explained next):

Backbone PushState Test

Now, without pushState enabled I have no issue remote linking to this route, ie http://localhost/Home/Index#test/sometext
The result of which is that the div with a class of .row is now "Hello, sometext".
The problem
Enabling pushState will allow us to replace that pesky # in the URL with a /, ie: http://localhost/Home/Index/test/sometext. We can use the Backbone method of router.navigate("url", true); (as well as other methods) to use adjust the URL manually. However, this does not solve the problem of remote linking. So, when trying to access http://localhost/Home/Index/test/sample you just end up with the typical 404.0 error served by IIS. so, I assume that it is handled in in the RouteConfig.cs file - inside, I add a "CatchAll" route:
routes.MapRoute(
    name: "CatchAll",
    url: "{*clientRoute}",
   defaults: new { controller = "Home", action = "Index" }
);

I also uncomment out the pushState and root attributes in the Backbone.history.start(); method:
        Backbone.history.start({
            pushState: true,
            root: "/Home/Index/"
        });
        var Route = Backbone.Router.extend({
            routes: {
                "test/:id": function (event) {
                    $(".row").html("Hello, " + event);
                },
                "help": function () {
                    alert("help!");
                }
            }
        });
        var appRouter = new Route();
        //appRouter.navigate("/test/sometext", { trigger: true });
        //appRouter.navigate("/help", { trigger: true });

This allows me to at least let get past the 404.0 page when linking to these routes - which is good. However, none of the routes actually "trigger" when I head to them. After attempting to debug them in Chrome, Firefox, and IE11 I notice that none of the events fire. However, if I manually navigate to them using appRouter.navigate("/help", { trigger: true }); the routes are caught and events fired.
I'm at a loss at this point as to where I should start troubleshooting next. I've placed my Javascript inside of the $(document).ready() event as well as the window.onload event also (as well as not inside of an event); none of these correct the issue. Can anyone offer advice on where to look next?
Answer: You simply have to move Backbone.history.start after the "new Route" line.
var Route = Backbone.Router.extend({
    routes: {
        "test/:id": function (event) {
            $(".row").html("Hello, " + event);
        },
        "help": function () {
            alert("help!");
        }
    }
});
var appRouter = new Route();
Backbone.history.start({
    pushState: true,
    root: "/Home/Index/"
});

Make sure you go to ".../Home/Index/help". If it doesn't work, try temporarily removing the root and go to ".../help" to see if the root is the problem.
If you still have troubles, set a js breakpoint in Backbone.History.loadUrl on the "return" line. It is called from the final line of History.start to execute the current browser url on page load. "this.matchRoot()" must pass then, "fragment" is matched against each "route" or regexp string in "this.handlers". You can see why or why not the browser url matches the route regexps.
To set to the js breakpoint, press F12 in the browser to open the dev console, press Ctrl-O or Ctrl-P to open a js file, then type the name of the backbone js file. Then search for "loadUrl:". You can also search for "Router =" to find the start of the router class definition (same as for "View =" and "Model =" to find the backbone view/model implementation code). I find it quite useful to look at the backbone code when I have a question like this. It is surprisingly readable and what better place to get answers?
If your js files happen to be minified/compressed, preferably turn this off. Alternately you can try the browser unminify option. In Chrome this is the "{}" button or "pretty print". Then the js code is not all on 1 line and you can set breakpoints. But the function and variable names may still be mangled.
Answer: I have solved my own problem using what feels to be "hackish", via the following. If anyone can submit a better response it would be appreciated!
My Solution:
I globally override the default Backbone.Router.intilaize method (it is empty) with the following:
$(document).ready(function (event) {
    var _root = "/Home/Index/";
    _.extend(Backbone.Router.prototype, {

        initialize: function () {
            /* check for route & navigate to it */
            var pathName = window.location.pathname;
            var route = pathName.split(_root)[1];
            if (route != undefined && route != "") {
                route = "/" + route;
                this.navigate("", { trigger: false });
                this.navigate(route, { trigger: true });
            }
        }

    });
});


strange results differing between left and right positioning

Question: This is a strange bug i'm facing, i don't really understand the problem so forgive me for the obscure title.
The problem is I'm developing a SPA style site and i want the content to slide in from the right (when the buttons at the bottom are clicked)
I thought this would be easy, but for some reason it is easy to achieve from the left, using the example below
.page {
  right: 100%;}
  .page.active {
    right: 0; }

https://jsfiddle.net/pphfstos/3/
and less ideally to slide the full width across like this
.page {
  left: -100%;}
  .page.active {
    left: 0; }

https://jsfiddle.net/pphfstos/4/
But when i try to create the same effect as the first example but from the right it not only doesn't work but totally seems to destroy the page
.page {
  right: -100%;}
  .page.active {
    right: 0; }

https://jsfiddle.net/pphfstos/5/
There is other code involved as you can see in the fiddle, but these are the only things that are different between the 3 examples
Can anyone explain what is happening and how to fix it?
Answer: Content you position outside of the viewport to the left is actually hidden, and can't be reached via scrolling.
Content you position outside of the viewport to the right however "extends" the page in that direction, and can be scrolled to.
Remove the overflow-x: hidden from html/body in your first and third fiddle, and you see what I mean – in the first one, the content positioned to the left is hidden, and no scrollbar appears; in your third fiddle however you do get a scrollbar, and the content positioned to the right can be reached via scrolling, moving the part of your page that is initially visible to the left while you're doing so.
Now, setting overflow-x: hidden removes the ability to scroll using the mouse; but the viewport can still be "shifted" to display that content, for example by navigating to an anchor – and that is what your links are doing. (But because this is an "instant jump" and not smooth scrolling, you don't see your initially visible content move away, it is just gone instantly.)
So you simply need to suppress the default action of your anchor links in your click event handler:
mainNavButton.click(function (e) {
    e.preventDefault(); // prevent event default action
    // … rest of your code

– and the effect of the page "jumping" to the anchor position is gone.
https://jsfiddle.net/pphfstos/6/
Comment: thanks, that's brilliant! i also put a 'max-width:100%; overflow-x:hidden;' around the container div to prevent scrolling sideways with mousewheel