text:
Q: Condicial anidadas a un ciclo for dentro de varios switch c++ Debo realizar un programa que me imprima los numeros comprendidos entre 1 y 200, ir mostrando los primeros numeros en grupos de 20 (1 hasta el 20) y cuando toque mostrar los nuevos nuevamente el grupo de 20 (que en este caso sería del 20 hasta el 40) le pregunte al usuario si desea continuar para seguir mostrando los que siguen, así hasta llegar al 200.
#include <iostream>

using namespace std;

int main (){

    int op;

    for(int i=1; i<201; i++){
        cout<<i<<endl;
        if(i>19){
            cout<<"Desea continuar? "<<endl;
            cout<<" 1 = Si "<<endl;
            cout<<" 2 = No "<<endl;
            cin>>op;
            switch(op){
                case 1: cout<<i<<endl;
                        if(i==40){
                            cout<<"Desea continuar: "<<endl;
                            cout<<" 1 = Si "<<endl;
                            cout<<" 2 = No "<<endl;
                            cin>>op;
                            switch(op){
                                case 1: cout<<i<<endl;
                                        if(i>59){
                                            cout<<"Desea continuar: "<<endl;
                                            cout<<" 1 = Si "<<endl;
                                            cout<<" 2 = No "<<endl;
                                            cin>>op;
                                            switch(op){
                                                case 1: cout<<i<<endl;
                                                        if(i>79){
                                                            cout<<"Desea continuar: "<<endl;
                                                            cout<<"1 = Si "<<endl;
                                                            cout<<"2 = No "<<endl;
                                                            cin>>op;
                                                            switch(op){
                                                                case 1: cout<<i<<endl;
                                                                if(i>99){
                                                                cout<<"Desea continuar: "<<endl;
                                                                cout<<"1 = Si "<<endl;
                                                                cout<<"2 = No "<<endl;
                                                                cin>>op;
                                                                switch(op){
                                                                    case 1: cout<<i<<endl;
                                                                    if(i>119){
                                                                        cout<<"Desea continuar: "<<endl;
                                                                        cout<<"1 = Si "<<endl;
                                                                        cout<<"2 = No "<<endl;
                                                                        cin>>op;
                                                                        switch(op){
                                                                            case 1: cout<<i<<endl;
                                                                            if(i>139){
                                                                                cout<<"Desea continuar: "<<endl;
                                                                                cout<<"1 = Si "<<endl;
                                                                                cout<<"2 = No "<<endl;
                                                                                cin>>op;
                                                                                switch(op){
                                                                                case 1: cout<<i<<endl;
                                                                                if(i>159){
                                                                                cout<<"Desea continuar: "<<endl;
                                                                                cout<<"1 = Si "<<endl;
                                                                                cout<<"2 = No "<<endl;
                                                                                cin>>op;
                                                                                switch(op){
                                                                                case 1: cout<<i<<endl;
                                                                                if(i>179){
                                                                                cout<<"Desea continuar: "<<endl;
                                                                                cout<<"1 = Si "<<endl;
                                                                                cout<<"2 = No "<<endl;
                                                                                cin>>op;
                                                                                switch(op){
                                                                                case 1: cout<<i<<endl;
                                                                                }
                                                                                }
                                                                                case 2: return 0;
                                                                                }
                                                                                }
                                                                                case 2: return 0;
                                                                                }
                                                                            }
                                                                            case 2: return 0;
                                                                        }
                                                                    }
                                                                    case 2: return 0;
                                                                }
                                                                }
                                                                case 2: return 0;
                                                            }
                                                        }
                                                case 2: return 0;}
                                        }
                                case 2: return 0;break;}
                        }break;
                case 2: return 0;break;
            }
        }
    }

    return 0;
}

El problema que tengo es que a la hora de ejecutar el codigo, este me imprime los 20 primeros numeros pero cuando salta la primera pregunta (si deseo continuar o no) y le doy que si, solamente me imprime un numero adicional (21) en lugar de los otros 20 numeros que le siguen (hasta el 40), soy consciente de que mi codigo es poco ortodoxo y bastante largo, pero me gustaría en lo posible dejarlo como esta pero entendiendo el funcionamiento de los switch aninados.

A: No entiendo la complicación de tu código, que puede escribirse así:
int op;

for (int numero = 1; numero != 200; ++numero)
{
    if (!(numero % 20))
    {
        std::cout <<
            "Desea continuar?\n"
            "1 = Si\n"
            "2 = No\n";

        std::cin >> op;

        if (op == 2)
            return 0;
    }

    std::cout << numero << '\n';
}

Respecto a tu problema: Cada vez que repites el bucle, se cumple la primera condición:
if(i>19){

Ya que cualquier número a partir del 19 será mayor que 19; por lo tanto a cada número te hace la misma pregunta.

A: Tu codigo puede reescribirse de esta forma:
#include <iostream>

#define RANGE_JUMP  20 //definimos de cuanto en cuanto queremos que se impriman los numeros.
#define RANGE_LIMIT RANGE_JUMP * 10 //definimos hasta que numero queremos llegar.

typedef unsigned short int iter_size; //creamos un tipo para iterar sobre nuestro bucle for.

//system("cls") limpia la consola. Usar "cls" si te encuentras en Windows. Si estas en linux el
//comando correcto seria: system("clear")

int main()
{
    using std::cout; using std::cin;

    iter_size acc = 20; //variable que nos permitira manejar paulatinamente los lotes de numeros.

    for (iter_size i = 0; i < RANGE_LIMIT; i = i + 1) {
        if (i <= acc) {
            cout << i << '\n';
        }
        else {
        menu:
            unsigned short int user_option;
            cout << "Menu de opciones:\n";
            cout << "1. Imprimir el siguiente lote de numeros.\n";
            cout << "2. Terminar.\n";
            cout << "Ingrese su opcion aqui: ";
            cin >> user_option;

            if (user_option == 1) {
                acc = acc + RANGE_JUMP; //incrementamos el lote segun lo indicado.
                i = i - 1; //decrementamos una vez a i para que la secuencia numerica no se vea afectada.
                system("cls");
            }
            else if (user_option == 2) {
                std::cout << "\nPrograma terminado...\n";
                system("pause");
                break;
            }
            else {
                system("cls");
                cout << "\nOpcion incorrecta, vuelva a intentarlo...\n";
                goto menu; //se repetira la impresion del menu en caso que se ingrese una opcion invalida.
            }
        }
    }
}


text:
Q: await message.channel.send(response.text) NameError: name 'response' is not defined I have tried to run this code, and the discord bot does turn on, but when I try and type '$joke' in discord it returns this error:    await message.channel.send(response.text) NameError: name 'response' is not defined I'm quite new to this so i'm not really sure what exactly the problem here is. here is my code:
import os
import requests
import json
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

def get_quote():
  response = requests.get("https://zenquotes.io/api/random")
  json_data = json.loads(response.text)
  quote = json_data[0]['q'] + " -" + json_data[0]['a']
  return(quote)

def get_meme():
    url = "https://ronreiter-meme-generator.p.rapidapi.com/meme"
    querystring = {"top":"haha MEME","bottom":"from Photon#2400","meme":"Condescending-Wonka","font_size":"50","font":"Impact"}
    headers = {
        'x-rapidapi-host': "ronreiter-meme-generator.p.rapidapi.com",
        'x-rapidapi-key': "443da94d87mshc53009d5fb1dca7p189387jsn7ca32834f0b6"
        }
    response = requests.request("GET", url, headers=headers, params=querystring)
    return(response)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

    if message.content.startswith('$quote'):
        quote=get_quote()
        await message.channel.send(quote)

    if message.content.startswith('$whoami'):
        await message.channel.send('You are {}'.format(message.author.name))

    if message.content.startswith("$joke"):
        await message.channel.send(response.text)

client.run(os.getenv('DISCORD_TOKEN'))

A: try install Django rest framework -drf
from rest_framework.response import Response

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kivy save widget without being drawn results in blank Fbo I am trying to render some labels over the top of a canvas texture i have previously saved. When i render the widget to an Fbo without drawing it to the screen first i get a blank output. I believe this is replicated in the snippet below, save_file called from on_start writes the file incorrectly, but if the same logic is called from the button press it saves a file of the widget rendered correctly.
Is there a way to render the widget to the Fbo without rendering to the canvas?
Is there an update or draw command i need to call on the widget?
(notshown.texture seems to be None, and adding notshown.canvas.draw() seems to crash with no stacktrace or reason?)
from kivy.app import App
from kivy.factory import Factory

class TestApp(App):
    def build(self, *kwargs):
        layout = Factory.BoxLayout()
        test1 = Factory.Button(text='test1', size_hint=(None,None), size=(200,200))
        test1.bind(on_press=self.save_file1)
        layout.add_widget(test1)
        test2 = Factory.Button(text='test2', size_hint=(None,None), size=(200,200))
        test2.bind(on_press=self.save_file2)
        layout.add_widget(test2)
        return layout
    def save_file1(self, widget, value=False):
        fbo = Factory.Fbo(size=widget.size, with_stencilbuffer=True)
        fbo.add(widget.canvas)
        fbo.draw()
        fbo.texture.save('C:/Temp/test1.png', flipped=True)
    def save_file2(self, widget, value=False):
        notshown = Factory.Button(text='notshown', size_hint=(None,None), size=(200,200))
        fbo = Factory.Fbo(size=notshown.size, with_stencilbuffer=True)
        fbo.add(notshown.canvas)
        fbo.draw()
        fbo.texture.save('C:/Temp/test2.png', flipped=True)

TestApp().run()

A: Per John Anderson's input, the issue was not giving the application enough time to render a frame before attempting to save the texture.
Using Clock.schedule_once to await the next frame means that export_to_png or all other uses of the texture of the widget succeed with little to no fuss.
img = Factory.FinalImage(imagedata, size_hint=(None,None), size=imagedata.size)
Clock.schedule_once( lambda x: img.export_to_png(filename=imagename) )


text:
Q: Boolean Java program to check if k-clique in my graph "W" I am using the backtracking algorithm to write a program that checks if I have a k-clique in my graph W (W is a 2D array).
k-clique means that there exist k-vertices, in my graph W, such that every vertex is connected (form an edge) to all other (k-1) vertices. For instance, we say that v1, v2, and v3 form 3-clique if there is an edge between:

*

*v1 and v2.

*v1 and v3.

*v1 and v4.

*v2 and v3.

*v2 and v4.

*v3 and v4.

I.e., there exist an edge between v1 and v2 if W[v1][v2] == 1.
boolean haskclique(int n, int k, int [][] W){
            int[] kVertices = new int [k + 1];
            return haskcliqueRec(n, k, 0, kVertices, W);
        }

public static boolean
haskcliqueRec(int n, int k, int i, int [] kVertices, int W[][]){
              boolean hasKclique = true;

              if (i == k) {
                    //check if kCLique
                    for ( int x = 1; x <= k; x++){
                        int y = x + 1;
                        while (hasKclique && y <= k){
                            if( W[ kVertices[x] ][ kVertices[y] ] != 1 )
                                hasKclique = false;

                            if ( y == k && hasKclique)
                                return true;
                            y++;
                        }
                    }
              }
              else{
                  for (kVertices[1] = W[1][1]; kVertices[1] <= k; kVertices[1]++)
                   {
                      kVertices[i+1] = W[1][1];

                      //Check if there is a repeat
                      if( kVertices[i+1] != kVertices[i] )
                          haskcliqueRec(n, k, i+1, kVertices, W);
                   }
              }
              return false;
          }

I am getting true when my method should return false. Why?


text:
Q: Is it really necessary to create foreign key in this query? I have a table called investors having a primary key as ID. I also have additional tables named Users Login_Logs and Accounts. All of these tables contain the foreign key investor_id. Between investors and Users we have a one to one relation. between investors and Login_Logs a one to many relation and between investors and Acccounts a one to many relation as well. My question is in order to create a query that loads info contained in the table Users, Login_Logs and Accounts - do I need to store the Users id, Accounts id and Login_Logs id in the investors table? I mean, do I need to create foreign keys in the investors table for all columns?

A: No, foreign key constraints don't affect joins and read queries.  They ensure that the values in the child column(s) exist in the referenced column(s).  They're used for integrity, not for linking rows or tables.
AFAICT recording the user id in your investors table is redundant, and recording the account and login_log ids in investors isn't practical.
To be able to join the tables efficiently, what you need is to index the investor_id in each of the tables.  Then, it's up to your query to connect the tables as required.
The problem with retrieving all the information about investors at the same time is that you have (multiple) one-to-many relations.  If we join all the tables:
SELECT *
FROM investors i
JOIN users u ON i.ID = u.investor_id
JOIN accounts a ON i.ID = a.investor_id
JOIN login_logs l ON i.ID = l.investor_id

Then, if an investor has 2 accounts and 2 login_logs, then we'll get 4 rows.  SQL databases can't nest related data.  Instead, you may have to use 3 queries to retrieve everything about investors:
SELECT *
FROM investors i
JOIN users u ON i.ID = u.investor_id

SELECT *
FROM accounts

SELECT *
FROM login_logs

Then process the results in code.  You could process the combined query above programmatically, but it's a bit more complicated.


text:
Q: How to easily prove Euler's theorem, $OI^2=R(R-2r)$? If $R$ is the circumradius and $r$ is the inradius of some triangle $ABC$, with its circumcenter being $O$ and incenter being $I$, then how to prove:
$$OI^2=R(R-2r)$$
I have seen many mentions of this theorem, and Euler's inequality is a corollary. Wikipedia
has a proof, but its quite tough to follow and long, so does anyone have a nicer proof? :)


text:
Q: Distributed database for worldwide LIDAR point cloud I have an idea for a project that would build a free worldwide 3D scan of the real world. You may think of it as a high-definition version of OpenStreetMap (OSM) project. The point cloud data would originate in LIDAR or stereo camera 3D scans. I am thinking of possible database solution for the project.
The main problem would be storing trillions of data primitives (point cloud points). Each point would have few properties (coords - lon, lat, elevation; intensity, RGB values, some semantic tags). I think the scenario is mostly similar to OSM but with way more data (easily 1000 times the OSM data but most likely much more).
Real spatial features are not neededn it the database and only a queries by location (with the help of geohash or b-tree indexes?) are required.
OSM uses plain Postgres (not PostGIS) because they do not need any geometry operations on top of their nodes. Today (October 2016) the OSM project contains 3.5 billion of nodes in a plain Postgres db table that runs on a single server. The whole database (including ways, relations, editing history etc.) has a size of about 6 TB (see server hardware).
Since I need 1000x the scale of OSM it is clear that many servers will be needed. Can someone help to at least roughly outline how the system may look like? I think data fragmentation may be done geographically by dividing Earth's surface into squares and have one table_points (=one database?) per such patch - lets call these "slave servers". There would be a central "master server" (not a db) that would manage queries for slaves (in case data from multiple slaves would be needed) and handle data returns to clients. Would such model be viable?
I can think of some very sophisticated fully distributed database system but I think at the beginning something very simple like simple Postgres slaves (maybe with few read-only replicas for faster reads) could be sufficient for the basic functionality.
Note: I found the pointcloud extension for Postgres (explanatory video here). It seems to group points into "patches" to minimize table row count. Would this make DB faster?
EDIT: I am also exploring distributed NoSQL databases like Cassandra or CouchDB. Also thinking about a DIY solution with people having nodes at home rather than using a datacentre (mostly due to financial reasons - datacentre needs to be paid). But with a "flat worldwide NoSQL" (read: data not fragmented by geo coords) I am not sure how queries would work (speed etc.).

A: I have dealt with something very similar to this. This is quite a broad problem but I'll try to offer the pointers I can after a year (and then the rest) of dealing with massive geographic data sets.
I'm not saying "do these", I'm saying these ideas will be resourceful depending on your hardware situation and software needs. You clearly already have good ideas about distributing out the data, that's good.
Firstly, I'd make sure not to have monolithic tables with too many sets of datatypes. Normalise out - I've found that splitting your geospatial columns into an entirely separate table.
Secondly, write down the sort of queries you'd expect a typical client to need. There's a 'chicken and egg' situation here, but I always like to write the SQL then design the table and indexes around that. Rick James' blog (former DBA at Yahoo!) always has nuggets of wisdom on this.
Thirdly, shard by location, which you have already touched upon. You can try doing this by 5-10 degree boxes around the world by latitude and longitude, depending on how dense your data is. Or if your data density is not uniform around the world, try a more sophisticated approach based on densities.
Our approach to sharding involved creating multiple Amazon RDSs, and then having a meta data table that mapped a range to the correct database and table. This is a simpler approach if you have the cash - personally I was against this due to the spiralling costs, but the uptime of AWS is top-notch. Something for you to think about.
Good luck, sounds like a cool project!


text:
Q: How to order divs in bootstrap 4? I have to divs next to each other in a row div. On mobile, i want the right_side div(col-md-9) to be the first div.
I tryed ordering it with flex, but it messed up all my site.

Left side

Right side, but first on mobile or tablet

If i am viewing the site on mobile or tablet, i want the col-md-9 div as first div.

A:

@media screen and (max-width: 767px) {
  .col-md-3 {
    order: 2;
  }
  .col-md-9 {
    order: 1;
  }
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

Left side

Right side, but first on mobile or tablet

A: you can do with flex and order as below example.
If it is messing-up with all sites, then give your custom class and then give CSS.

@media screen and (max-width: 531px) {
    .row { display: flex; flex-direction: column; }
    .two { order: 1; }
    .one { order: 2 }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">

Left side

Right side, but first on mobile or tablet

A: Just use order property.
@media only screen and (max-width: 760px) {
  .col-md-3 {
 order:2;
  }
}

@media only screen and (max-width: 760px) {
  .col-md-3 {
 order:2;
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Left side

Right side, but first on mobile or tablet

A: there is an option to reverse the row using class. here is the code please try it once.

Right side, but first on mobile or tablet

Left side

A: Use Column Ordering to accomplish this.
col-md-push-6 will "push" the column to the right 6 and col-md-pull-6 will "pull" the column to the left on "md" or greater view-ports. On any smaller view-ports the columns will be in normal order again.
I think what throws people off, is that you have to put B above A in your HTML. There may be a different way to do this where A can go above B in the HTML, but I'm not sure how to do it...
See Code

B

A

view-port >= md
|A|B|

view-port < md
|B|
|A|


text:
Q: Explanation and proof of the 4th order Runge-Kutta method The 4th order Runge-Kutta (RK4) method is a numerical technique used to solve ordinary differential equations (ODEs) of the following form
$$\frac{dy}{dx} = f(x,y), \qquad y(0)=y_0$$
It gives $y_{i+1}$ in the form
$$y_{i+1} = y_i+(a_1k_1+a_2k_2+a_3k_3+a_4k_4)h$$
where the constants are found to be:
$$y_{i+1} = y_i+\frac{1}{6}(k_1+2k_2+2k_3+k_4)h$$
and:
$$\begin{aligned} k_1 &= f(x_i, y_i)\\ k_2 &= f \left(x_i+\frac{1}{2}, y_i+\frac{1}{2}k_1h \right)\\ k_3 &= f \left(x_i+\frac{1}{2}, y_i+\frac{1}{2}k_2h \right)\\ k_4 &= f(x_i+h, y_i+k_3h) \end{aligned}$$
I also learnt that these are derived from the first four terms Taylor series:
$$y_{i+1}=y_i+f(x_i,y_i)h+\frac{1}{2!}f'(x_i,y_i)h^2+\frac{1}{3!}f''(x_i,y_i)h^3+\frac{1}{4!}f'''(x_i,y_i)h^4$$
These are the things that I understood. However, here are what I cannot:

*

*I cannot see why this method "works"?

*How are the $a_ik_i$ terms derived and computed from the Taylor series?

*What justifies or proves this result?

Please note that I have seen many articles on these things things, but none of them contained a full proof whatsoever... I would also much like to get some examples where the f function is actually a function of both x, y not only x. Could you please send me some links with further advanced and concise links of this question?

A: There are many Runge–Kutta methods. The one you have described is (probably) the most popular and widely used one. I am not going to show you how to derive this particular method – instead I will derive the general formula for the explicit second-order Runge–Kutta methods and you can generalise the ideas.
In what follows we will need the following Taylor series expansions.
\begin{align}
\tag1\label{eq1} & x(t+\Delta t)  = x(t) + (\Delta t)x'(t) + \frac{(\Delta t)^{2}}{2!}x''(t) + \text{higher order terms}. \\
\tag2\label{eq2} & f(t + \Delta t, x + \Delta x) = f(t,x) + (\Delta t)f_{t}(t,x) + (\Delta x)f_{x}(t,x) + \text{higher order terms}.
\end{align}
We are interested in the following ODE:
$$x'(t) = f(t,x(t)).$$
The value $x(t)$ is known and $x(t+h)$ is desired. We can solve this ODE by integrating:
$$x(t+h) = x(t) + \int_{t}^{t+h}f(\tau,x(\tau))\text{d}\tau.$$
Unfortunately, actually doing that integration exactly is often quite hard (or impossible), so we approximate it using quadrature:
$$x(t+h) \approx x(t) + h\sum_{i=1}^{N}\omega_{i}f(t + \nu_{i}h,x(t + \nu_{i}h)).$$
The accuracy of the quadrature depends on the number of terms in the summation (the order of the Runge–Kutta method), the weights, $\omega_{i}$, and the position of the nodes, $\nu_{i}$.
Even this quadrature can be quite difficult to calculate, since on the right-hand side we need $x(t + \nu_{i}h)$, which we don't know. We get around this problem in the following manner:
Let $\nu_1=0$, which makes the first term in the quadrature $K_{1} := hf(t,x(t)).$ This we do know and we can also use it to approximate $x(t + \nu_{2}h)$ by writing the second term in the quadrature as $K_{2} := hf(t+\alpha h,x(t) + \beta K_{1})$.
With this, the quadrature formula is:
$$\tag3\label{eq3} x(t+h) = x(t) + \omega_{1}K_{1} + \omega_{2}K_{2}.$$
Some notes:

*

*If we wanted to find a third-order method, we would introduce $K_{3} = hf(t+\tilde{\alpha}h,x+\tilde{\beta}K_{1} + \tilde{\gamma}K_{2})$. If we wanted a fourth-order method, we would introduce $K_{4}$ in a similar way.

*This is an explicit method, i.e. we have chosen $K_{2}$ to depend on $K_{1}$ but $K_{1}$ does not depend on $K_{2}$. Similarly, $K_{3}$ (if we introduce it) depends on $K_{1}$ and $K_{2}$ but they do not depend on $K_{3}$. We could allow the dependence to run both ways but then the method is implicit and becomes much harder to solve.

*We still need to choose $\alpha$, $\beta$ and the $\omega_{i}$. We will do that now using the Taylor series expansions I introduced at the very beginning.

In equation \eqref{eq3}, we substitute in the Taylor series expansion \eqref{eq1} on the left-hand side:
$$x(t) + h x'(t) + \frac{h^{2}}{2!}x''(t) + \mathcal{O}\left(h^{3}\right) = x(t) + \omega_{1}K_{1} + \omega_{2}K_{2}.$$
Since $x' = f$ and thus $x'' = f_{t} + ff_{x}$ (suppressing arguments for ease of notation), we have:
$$hf + \frac{h^{2}}{2}(f_{t} + ff_{x}) + \mathcal{O}\left(h^{3}\right)  = \omega_{1}K_{1} + \omega_{2}K_{2}.$$
Now substitute for $K_{1}$ and $K_{2}$:
$$hf + \frac{h^{2}}{2}(f_{t} + ff_{x}) + \mathcal{O}\left(h^{3}\right)  = \omega_{1}hf + \omega_{2}hf(t + \alpha h, x + \beta K_{1}).$$
Taylor-expand on the right-hand side using \eqref{eq2}:
$$hf + \frac{h^{2}}{2}(f_{t} + ff_{x}) + \mathcal{O}\left(h^{3}\right)  = \omega_{1}hf + \omega_{2}(hf +\alpha h^{2}f_{t} + \beta h^{2} ff_{x}) + \mathcal{O}\left(h^{3}\right).$$
Thus the Runge–Kutta method will agree with the Taylor series approximation to $\mathcal{O}\left(h^{3}\right)$ if we choose:
$$\omega_{1} + \omega_{2} = 1,$$
$$\alpha \omega_{2} = \frac{1}{2},$$
$$\beta \omega_{2} = \frac{1}{2}.$$
The canonical choice for the second-order Runge–Kutta methods is $\alpha = \beta = 1$ and $\omega_{1} = \omega_{2} = 1/2.$
The same procedure can be used to find constraints on the parameters of the fourth-order Runge–Kutta methods. The canonical choice in that case is the method you described in your question.


text:
Q: Why i can't see desired data in jsp file I am new in Java EE and I am building a web application with maven, spring mvc
and hibernate.
I have a problem with the jsp. I can not show the data of object with the expression / jstl
language. In console doesn't show any error. Any suggestions?
Pom.xml:

Controller:

Inicio.jsp:

A: I guess in the controller you are setting the object with key
model.addObject("usuario", usuarioo);

The first character is small 'u'.
And in your jsp you are trying to access using Usuario. Thus the value is not getting printed.
Kindly use something like
${usuario.nombre}


text:
Q: iOS app "Processing" in iTunes Connect I uploaded my first iOS app today to iTunes Connect.
I uploaded it over xCode 7.2.1 and I see the app as "Processing" inside the "activity"-tab.
But under "AppStore"-tab for version 1.0 there is no app build visible. I only see the message that I should upload a build with xCode or Application Loader.
Is this normal or should I wait some time that the app is also showing up?
See the screenshots below:

A: Yes, this is perfectly normal. You just have to wait for it to finish processing (Can take a few minutes or a few hours depending on Apples traffic). Once it is done processing, it will appear in that builds section and you can select it as the version you want to submit. This is the same for testflight.
Additional from my personal experience (happened to me once and only once), if you submit the archive late at night on the last weekday or just before a public holiday, "sometimes" it might be processed on the next working day on the morning.
I'm at Indonesia (GMT +7), it is not uncommon for me to upload an archive around 7PM, and if it doesn't get processed in 15 minute, I usually just go home, and check it in the morning the next day. Because it happens a few time that if I upload too late, it get processed around 8AM the next morning.

A: It happened to me a couple of times. I just uploaded a new version (same code, just increased the version) and it was processed quite fast.
Just in case, the second time I kept the archiving dialog in the foreground.

A: Yes, this is perfectly normal. You just have to wait for it to finish processing (can take a few minutes or a few hours depending on Apple's traffic). Once it is done processing, it will appear in that builds section and you can select it as the version you want to submit. This is the same for TestFlight.
I recommend getting watchbuild and running it on your terminal so you can just get a notification on your computer when your build is done processing instead of having to keep checking App Store Connect.

A: This is normal. After uploading a build, iTunes Connect performs some processing to prepare it for TestFlight Distribution and App Store distribution.
The status of the build should go to ready after some time. Sometimes, this happens as fast as 15 minutes after uploading but can sometimes take 1 hour or longer. After the processing finishes, the build will become available to select for TestFlight betas and app submission.

A: I had this issue today, i tried all of the fixes suggested and found that you need to wait till the invitations are sent out. I think the servers were just very busy when i was trying to test my app.

A: It happened to me when I export Unity iOS build and upload it to AppStore there are more than 3 days waiting but still showing processing.
Finally, Many search things I found that Bitcode = NO here is the issue on my build I have Bitcode = YES once you change and set to NO and upload again your build it's not showing processing and it's working properly.


text:
Q: Grafana Total Number of panel in Dashboard I have a task to create a panel in grafana dashboard to dynamically calculate and show a number of objects in the dashboard.
I have a server that I monitor with ping in Zabbix. I build a dashboard where I see if the server is online or offline and now I need to count servers and show how many are online and how many are offline.
I am new in Grafana I googled but did not find anything


text:
Q: Get value "8" from a wordpress url: mywebsite.com/profile/8/ How can I get that value "8" from a wordpress url: mywebsite.com/profile/8/
    $current_uri = $_SERVER['REQUEST_URI'];
    $url_params = explode( '/', $current_uri );
    $the_value = $url_params[2];

But seems a little dirty to me. Any thoughts? Thank you
NOTE: that "8" changes. Not always "8".

A: In word press you can get query variable by below function:
get_query_var( $var, $default );

$var is The variable key to retrieve. (e.g. profile, paged, id,  etc. )
$default Value to return if the query variable is not set.
check below link: Query var

A: You can use Regular Expression like this.
<?php
//$current_uri = $_SERVER['REQUEST_URI'];
// For Demo I have declared it as string below.
$current_uri="mywebsite.com/profile/8/";
preg_match('/(\d+)\/$/', $current_uri, $m );
print $m[1];
?>

Regex: (\d+)\/$
Above regex will extract a number(\d+) appearing before last( $ quantifier ) /(slash)
Capturing it into a group by using () around \d+ extracted number is retrieved in array $m[1].
Ideone Demo


text:
Q: Unique identifier of mp3 regardless of id3 tag? Ideally I want a way to uniquely identify files (audio files) where things like the ID3 tag or the file name can change and the hash remains the same.
Is there a better way I don't know of to uniquely identify files? Or would I have to change my record of the file every time an edit was made? Can I hash on other pieces of data or something?

A: If you only count files wich have EXACTLY the same audio information as "the same" (same bit depth, bitrate, compression, etc.) its pretty easy: you would just hash the "audio" part of the file. im not too familiar with the MPEG audio codec myself though.
reading material:
http://en.wikipedia.org/wiki/MP3
http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm


text:
Q: double quote not showing in Image alt and title I am facing issue: On home page double quote not showing in Image alt and title on view source, But on inspect element it is showing. Anyone have suggestion so please share.

A: Try this
src="{{media url='wysiwyg/images/block/services.png'}}"

in your img  tag instead of
src="{{media url="wysiwyg/images/block/services.png"}}"

A: Inside double quote you cannot use double directly. You have to use like

OR


text:
Q: How to detect when my Django object's DataTimeField reach current time I'm using Django 1.5.5.
Say I have an object as such:
class Encounter(model.Models):
    date = models.DateTimeField(blank=True, null=True)

How can I detect when a given Encounter has reached current time ? I don't see how signals can help me.

A: You can't detect it using just Django.
You need some scheduler, that will check every Encounters date (for example, by using corresponding filter query), and do needed actions.
It can be a simple cron script. You can write it as django custom management command. And cron must call it every 5 minute, for example.
Or, you can use Celery. With it, you can see worker status from admin and do some other things.

A: What you could do is use Celery. When you save an object of Encounter this would then get into the task queue and execute only once it has reached current time.
There is one caveat though, it might execute a bit later depending on how busy the celery workers are.


text:
Q: How do I make an interactive tkinter text box, then entry box, then text box as a response to the entry I cannot get it to first show the question a text box, and a entry box to put the answer to the question. Push the send button. Then after the answer is  sent pop up the next text box as a response to the entry box.  Then give them another entry box to type an answer, send the answer with a button, and them again a text box as the response.  Do I need to use something other than a text box, entry box, and button.  I'm so new to using tkinter it is confusing me as to how to get it to do as I want it. Here is my code so far.
from tkinter import *

root = Tk()
frame = Frame(root, bg='lightgray')
frame.pack(fill='both', expand='yes')
root.title("Uganda Project")

#This is the first Question
T1= Text(frame, height=3, width=37)
T1.pack()
T1.insert(END, "Did you take your medicine?\n 1= Yes\n 2= No\n")
T1.configure(fg='white', bg='blue')

#Make an entry box to answer the question in
e1 = Entry(master=frame, fg='black', bg='lightgray', width=37)
e1.pack()

def answer1():
    """ What to do with the answer in the entry box"""
    answer1 = e1.get()
    return answer1

#Make a Send button to send the answer from the entry box to the definition
of answer1
send = Button(frame, text="Send", command=answer1)
send.pack()

#This is the second question
if answer1==1:
    T2 = Text(frame, height=1, width=37)
    T2.pack()
    T2.insert(END, "Good Job! Text 0 to end conversation")
    T2.configure(fg='white', bg='blue')

elif answer1==2:
    T2 = Text(frame, height=3, width=37)
    T2.pack()
    T2.insert(END, "1= Did you forget?\n2= Did you run out of medicine?\n3=
    Did it have bad side effects?\n")
    T2.configure(fg='white', bg='blue')

else:
    T2 = Text(frame, height=3, width=37)
    T2.pack()
    T2.insert(END, "I did not understand your response.")
    T2.configure(fg='white', bg='blue')

#Make an entry box to answer the question in
e2 = Entry(master=frame, fg='black', bg='lightgray', width=37)
e2.pack()

def answer2():
    """ What to do with the answer in the entry box"""
    answer2 = e2.get()
    return answer2

#Make a Send button to send the answer from the entry box to the definition
of answer2
send = Button(frame, text="Send", command=answer2)
send.pack()

#This is the response to the second entry box
if answer2==0:
    T3 = Text(frame, height=1, width=37)
    T3.pack()
    T3.insert(END, "Have a good day.")
    T3.configure(fg='white', bg='blue')

elif answer2==1:
    T3 = Text(frame, height=2, width=37)
    T3.pack()
    T3.insert(END, "Take it as your earliest convience.\nDo Not Take two
    doses at once!\n")
    T3.configure(fg='white', bg='blue')

elif answer2==2:
    T3 = Text(frame, height=2, width=37)
    T3.pack()
    T3.insert(END, "Please contact your doctor or\npharmacy for refills.\n")
    T3.configure(fg='white', bg='blue')

elif answer2==3:
    T3 = Text(frame, height=3, width=37)
    T3.pack()
    T3.insert(END, "Please contact your doctor about\nchanging your
    medications or\ndealing with your symptoms.\n")
    T3.configure(fg='white', bg='blue')
else:
    T3 = Text(frame, height=3, width=37)
    T3.pack()
    T3.insert(END, "I did not understand your response.")
    T3.configure(fg='white', bg='blue')

root.mainloop()

A: one more code, with previous interface:
import tkinter as tk
root = tk.Tk()
root.title("Uganda Project")
frame = tk.Frame(root, bg='lightgray')
frame.pack(fill='both', expand='yes')

def answer1():
    """ What to do with the answer in the entry box"""
    # This is the second question
    if e1.get () == str (1):
        T2.replace (1.0, tk.END, "Good Job! Text 0 to end conversation")
    elif e1.get () == str (2):
        T2.replace (1.0, tk.END, "1= Did you forget?\n"
                                 "2= Did you run out of medicine?\n"
                                 "3= Did it have bad side effects?\n")

def answer2():
    """ What to do with the answer in the entry box"""
    #This is the response to the second entry box
    if e2.get()==str(0):
        T3.replace (1.0, tk.END, "Have a good day.")
    elif e2.get()==str(1):
        T3.replace (1.0, tk.END, "Take it as your earliest convience.\n"
                                 "Do Not Take two doses at once!\n")
    elif e2.get()==str(2):
        T3.replace (1.0, tk.END, "Please contact your doctor or\n"
                                 "pharmacy for refills.\n")
    elif e2.get()==str(3):
        T3.replace (1.0, tk.END, "Please contact your doctor about\n"
                                 "changing your medications or\n"
                                 "dealing with your symptoms.\n")

#This is the first Question
T1= tk.Text(frame, height=3, width=37)
T1.pack()
T1.insert(tk.END, "Did you take your medicine?\n 1= Yes\n 2= No\n")
T1.configure(fg='white', bg='blue')

#Make an entry box to answer the question in
e1 = tk.Entry(master=frame, fg='black', bg='lightgray', width=37)
e1.pack()

#Make a Send button to send the answer from the entry box to the definition of answer1
send = tk.Button(frame, text="Send", command=answer1)
send.pack()

T2 = tk.Text(frame, height=3, width=37)
T2.pack()
T2.insert(tk.END, "I did not understand your response.")
T2.configure(fg='white', bg='blue')

#Make an entry box to answer the question in
e2 = tk.Entry(master=frame, fg='black', bg='lightgray', width=37)
e2.pack()

T3 = tk.Text(frame, height=3, width=37)
T3.pack()
T3.insert(tk.END, "I did not understand your response.")
T3.configure(fg='white', bg='blue')

#Make a Send button to send the answer from the entry box to the definition of answer2
send2 = tk.Button(frame, text="Send", command=answer2)
send2.pack()

root.mainloop()

A: Please try this code (I have changed a few things as well as adding others to hopefully do the job). Its not the most efficient or the best structured code but it does the job (for me at least):
from tkinter import *
import datetime

root = Tk ()
root.bind ("<Return>", lambda event: answer1 ())
f = Frame(root, bg='lightgray')
f.grid (sticky = "nsew")
Grid.columnconfigure (root, 0, weight = 1)
Grid.rowconfigure (root, 0, weight = 1)
root.title("Uganda Project")

#This is the first Question
Bar = Scrollbar (f)
T = Listbox (f, fg='white', bg='blue', yscrollcommand = Bar.set, width = 50, height = 20)
Bar.config (command = T.yview)
T.grid (row = 0, column = 0, columnspan = 2, sticky = "nsew")
Bar.grid (row = 0, column = 2, sticky = "ns")
Grid.columnconfigure (f, 0, weight = 1)
Grid.rowconfigure (f, 0, weight = 1)
T.insert (END, "Support:")
T.insert (END, "    Did you take your medicine?")
T.insert (END, "    1= Yes")
T.insert (END, "    2= No")

#Make an entry box to answer the question in
e = Entry(f, fg='black', bg='lightgray')
e.focus_force ()
e.grid (row = 1, column = 0, sticky = "ew")

def answer1():
    """ What to do with the answer in the entry box"""
    answer1 = e.get()
    T.insert (END, "You: " + answer1)
    e.delete (0, END)
    if answer1=="1":
        T.insert (END, "Support:")
        T.insert (END, "    Good Job! Text 0 to end conversation")
        send.config (command = answer2)
        root.bind ("<Return>", lambda event: answer2 ())

    elif answer1=="2":
        T.insert (END, "Support:")
        T.insert (END, "    1= Did you forget?")
        T.insert (END, "    2= Did you run out of medicine?")
        T.insert (END, "    3= Did it have bad side effects?")
        send.config (command = answer2)
        root.bind ("<Return>", lambda event: answer2 ())

    else:
        T.insert (END, "Support:")
        T.insert (END, "    I did not understand your response.")

    return answer1

#Make a Send button to send the answer from the entry box to the definition of answer1
send = Button(f, text="Send", command=answer1)
send.grid(row = 1, column = 1, columnspan = 2)

#This is the second question

#Make an entry box to answer the question in

def save ():
    with open ("Log - %s.txt" % str (datetime.datetime.now ()).replace (":", "."), "w") as f: f.write ("\n".join (T.get (0, END)))

def answer2():
    """ What to do with the answer in the entry box"""
    answer2 = e.get()
    T.insert (END, "You: " + answer2)
    e.delete (0, END)
    #This is the response to the second entry box
    if answer2=="0":
        T.insert (END, "Support:")
        T.insert (END, "    Have a good day.")
        send.config (text = "OK", command = root.destroy)
        root.bind ("<Return>", lambda event: root.destroy ())
        save ()
        e.pack_forget ()

    elif answer2=="1":
        T.insert (END, "Support:")
        T.insert (END, "    Take it as your earliest convience.")
        T.insert (END, "    Do Not Take two doses at once!")
        root.bind ("<Return>", lambda event: root.destroy ())
        send.config (text = "OK", command = root.destroy)
        save ()
        e.pack_forget ()

    elif answer2=="2":
        T.insert (END, "Support:")
        T.insert (END, "    Please contact your doctor or")
        T.insert (END, "    pharmacy for refills.\n")
        root.bind ("<Return>", lambda event: root.destroy ())
        send.config (text = "OK", command = root.destroy)
        save ()
        e.pack_forget ()

    elif answer2=="3":
        T.insert (END, "Support:")
        T.insert (END, "    Please contact your doctor about")
        T.insert (END, "    changing your medications or")
        T.insert (END, "    dealing with your symptoms.")
        root.bind ("<Return>", lambda event: root.destroy ())
        send.config (text = "OK", command = root.destroy)
        save ()
        e.pack_forget ()

    else:
        T.insert (END, "Support:")
        T.insert (END, "    I did not understand your response.")

    return answer2

root.mainloop ()

#Make a Send button to send the answer from the entry box to the definition of answer1
send = Button(f, text="Send", command=answer1)
send.grid(row = 1, column = 1, columnspan = 2)

#This is the second question

#Make an entry box to answer the question in

def answer2():
    """ What to do with the answer in the entry box"""
    answer2 = e.get()
    T.insert (END, "You: " + answer2)
    e.delete (0, END)
    #This is the response to the second entry box
    if answer2=="0":
        T.insert (END, "Support:")
        T.insert (END, "    Have a good day.")
        send.config (text = "OK", command = root.destroy)
        root.bind ("<Return>", lambda event: root.destroy ())
        e.pack_forget ()

    elif answer2=="1":
        T.insert (END, "Support:")
        T.insert (END, "    Take it as your earliest convience.")
        T.insert (END, "    Do Not Take two doses at once!")
        root.bind ("<Return>", lambda event: root.destroy ())
        send.config (text = "OK", command = root.destroy)
        e.pack_forget ()

    elif answer2=="2":
        T.insert (END, "Support:")
        T.insert (END, "    Please contact your doctor or")
        T.insert (END, "    pharmacy for refills.\n")
        root.bind ("<Return>", lambda event: root.destroy ())
        send.config (text = "OK", command = root.destroy)
        e.pack_forget ()

    elif answer2=="3":
        T.insert (END, "Support:")
        T.insert (END, "    Please contact your doctor about")
        T.insert (END, "    changing your medications or")
        T.insert (END, "    dealing with your symptoms.")
        root.bind ("<Return>", lambda event: root.destroy ())
        send.config (text = "OK", command = root.destroy)
        e.pack_forget ()

    else:
        T.insert (END, "Support:")
        T.insert (END, "    I did not understand your response.")

    return answer2

root.mainloop()

Below is an example of how different projects can be called assuming:
1) The project is in the same directory as the calling code
2) The project is named after its function (so Uganda Project respectively)
I have also created a Rwanda Project as well to show how you can add extra pojects other than just the Uganda Project.
from tkinter import *
import importlib, threading, time, logging

PROJECTS = ("Uganda Project", "Rwanda Project")

def constructWindow ():
    global root, close
    close, wait = False, False
    logging.basicConfig (format = "%(message)s")
    while True:
        root = Tk ()
        root.title ("Main Menu")
        Label (root, text = "Which project would you like to run?").grid ()
        for project in PROJECTS: Button (root, text = project, command = lambda project = project: callProject (project)).grid ()
        root.protocol ("WM_DELETE_WINDOW", closeWindow)
        root.mainloop ()
        while wait: time.sleep (0.1)
        if close: break
def callProject (project):
    global wait
    wait = True
    root.destroy ()
    try: importlib.import_module (project)
    except ImportError: logging.warn ("Cannot find project.")
    wait = False
def closeWindow ():
    global close
    close = True
    root.destroy ()
if __name__ == "__main__": constructWindow ()


text:
Q: regarding like query operator For the below data (well..there are many more nodes in the team foundation server table which i need to refer to..below is just a sample)
Nodes
------------------------
\node1\node2\node3\
\node1\node2\node5\
\node1\node2\node3\node4\
\node1\node2\node3\node4\node5\

I was wondering if i can apply something like (below query does not give the required results)
select * from table_a where nodes like '\node1\node2\%\'

to get the below data
\node1\node2\node3\
\node1\node2\node5\

and something like (below does not give the required results)
select * from table_a where nodes like '\node1\node2\%\%\'

to get
\node1\node2\node3\
\node1\node2\node5\
\node1\node2\node3\node4\

Can the above be done with like operator? Pls. suggest.
Thanks

A: You'll need to combine two terms, LIKE and NOT LIKE:
select * from table_a where
   nodes like '\node1\node2\%\' AND
   nodes NOT like '\node1\node2\%\%\'

for the first query, and a similar solution for the second.  That's with "plain SQL".  There are probably SQL Server specific functions which will count the number of "\" characters in the column, for instance.

A: It seems like this would work (basically just eliminating the last backslash):
select * from table_a where nodes like '\node1\node2\%\%'

EDIT
You could also try this:
select * from table_a where
      nodes like '\node1\node2\%\' or
      nodes like '\node1\node2\%\%\'

A: maybe use the delimiter to get the resutls.
it is unclear what you are actually trying to get, but you could use the
substr

function to either count or find the position of the delimiter '/' character.

A: A little late to the party, but it appears that the problem is still open.  Could it be that the backslashes are escaping the wildcard meaning of the percent signs?  And the backslash n could be getting interpreted as well.

A: Doesn't sql-server know a wildcard for a single character?
 select * from table_a
   where nodes LIKE '#node1#node2#node_#';
        nodes
---------------------
 #node1#node2#node5#
 #node1#node2#node3#

I testet this on postgresql, where it is hard to insert a backslash, which is the reason why I replaced them with #.
Here is another possibility - negate more than one backslash (# used for my convenience):
SELECT * FROM table_a
WHERE (nodes LIKE '#node1#node2#%#'
  AND NOT nodes LIKE '#node1#node2#%#%#');

On postgresql there is too the possibility to match against patterns, with SIMILAR TO, or ~:
SELECT * FROM table_a
WHERE nodes SIMILAR TO '#node1#node2#[^#]*#';
        nodes
---------------------
 #node1#node2#node5#
 #node1#node2#node3#

[] encapsulates a group of alternatively allowed characters, for example [aeiou] would be a lowercase vocal. But when the caret is the first sign in the brackets, the sign(s) are negated so [^aeiou] would mean anything but a lowercase vocal, and [^#] means anything but a #.
The asterix behind that expression means that the preceding sign can occur as often as you like, 0 to million times. (+ would mean at least one times, ? would mean 0 or 1 times).
So '#node1#node2#[^#]*#' means '#node1#node2#', followed by anything but a hash, 0 or single or multiple times, and then, finally a hash.


text:
Q: Restart SSH on a machine where SSH is the only mode of access I've made some changes to sshd_config file and therefore need to restart. I'm looking tips on safely restarting ssh when getting physical access to the server would be a huga PITA.

A: If you have access to the hardware you may consider putting a terminal on the serial port /dev/ttyS0 . Then you can have a back door into your server.
simply add
SO:2345:respawn:/sbin/mingetty ttySO

to your /etc/inittab and a terminal will spawn over your serial port.  You can use a serial port concentrator or use a null modem from the server next to it.

A: Restarting sshd while logged in via ssh will not disconnect your ssh connection.
If you're worried about your configuration, log in a few times via ssh, and restart. If you can no longer ssh in, with new connections, you now have access to fix the problems.
Mentioned below in a comment by @Milan Babuškov: sshd -t will test your configuration for syntax correctness, if you really want to be certain.
Another suggestion, by @Ronald Pottol was to set up a cron task to restart the server with a known working configuration. Perhaps overkill, but if you're updating a mission critical server, etc... sometimes you can never be too careful.

A: Don't worry, your current session won't be disconnected, even if there's a problem with the new configuration.
After applying the new configuration and restarting sshd, just try to login a couple of times and take a look at the logs to see if everything is ok.

A: Or, use a cron or at job to start it back up, if you are feeling unlucky?

A: Could you not Just run a kill -HUP in the PID of the SSH service? Its not clean but it works

A: I have found that nowadays sshd does not disconnect your sessions when restarting, especially when it is a Redhat based distro. You could always write a small script that will automatically restore your sshd config from backup and restart sshd after 5 min as a cron or at job. This will ensure that even if you get disconnected, you can get back into your server at least.

A: I wouldn't recommend restarting/reloading SSHD on a sshd connection. I've seen many occasions where sshd just wouldn't start back up because of a syntax error in sshd_config.
Even though everything is ok with the config file, it's risky.


text:
Q: Nothing writing to a file in c Printing in two different files using the same code for both the files.
Nothing is being written in the second file(my_rank1.out) whereas in the other file, everything is properly written
  FILE *my_pointer;
  FILE *my_rank_ptr;
  for(int name = 1;name<=5;name++)
  {
      //read(name)
      char filename[21];
      sprintf(filename, "port%d.out", name);

      char temp_file[21];
      sprintf(temp_file, "my_rank%d.out", name);

      my_rank_ptr = fopen(temp_file,"w");
      my_pointer = fopen(filename,"w");

      fprintf(my_rank_ptr, "lambda\tcrossprob\tmutprob\tbasic_seed\trun\tseed\t");
      for(int i=1;i<=nstock;i++)
      {
        fprintf(my_rank_ptr, "var%d\t",i);
      }
      fprintf(my_rank_ptr, "fitness value\n");

      fprintf(my_pointer, "lambda\tcrossprob\tmutprob\tbasic_seed\trun\tseed\t");
      for(int i=1;i<=nstock;i++)
      {
        fprintf(my_pointer, "var%d\t",i);
      }
      fprintf(my_pointer, "fitness value\n");

//Some code follows this
      fclose(my_pointer);
      fclose(my_rank_ptr);

}

A: Add after every
fprintf(my_rank_ptr ....

a
fprintf(my_pointer

as you want to write to two files the same stuff

A: As noted in comments, are you checking the output of your fopen statement?
...
my_rank_ptr = fopen(temp_file,"w");
if(!my_rank_ptr) return -1;
my_pointer = fopen(filename,"w");
if(!my_pointer) return -1;
...

If your FILE pointers are not NULL, then for simplicity you could
arrange all your printf statements to use the same loop:
      fprintf(my_rank_ptr, "lambda\tcrossprob\tmutprob\tbasic_seed\trun\tseed\t");
      fprintf(my_pointer, "lambda\tcrossprob\tmutprob\tbasic_seed\trun\tseed\t");
      for(int i=1;i<=nstock;i++)
      {
        fprintf(my_rank_ptr, "var%d\t",i);
        fprintf(my_pointer, "var%d\t",i);
      }
      fprintf(my_rank_ptr, "fitness value\n");
      fprintf(my_pointer, "fitness value\n");

A: You may be getting a permission error when trying to open the file for writing. You should always check if the fopen() call succeeded or not before trying to write to a file.
     my_rank_ptr = fopen(temp_file,"w");

if ( !my_rank_ptr ) // failed to open...


text:
Q: How to define a freemarker function? I define a freemarker function, such as:
<#function ehtml str>
    <#if (str??) >
        <#return str?html>
    <#else>
        <#return "">
    </#if>
</#function>

I try to check the 'str' is not exist using <#if (str??) >, But it does not work. I still get a error "required parameter: str is not specified." when the paramter is null.

A: Because the str parameter is required according that function definition, it doesn't even reach the <#if str??> line (BTW that () is redundant there). Right now the only way to make it non-required is providing a default for it, like <#function ehtml str=''>. So actually this function could be written as <#function ehtml str=''><#return str?html></#function>. Indeed, the best would be if you just to write ${foo!?html} where you expect a null, instead of the longer ${ehtml(foo)}. That's why FTL has the maybeNull!/ maybeNull!default operator after all. So then you don't need this function.


text:
Q: Función para agregarBarcos C++ Buenas gente la consigna es la siguiente:
void agregarBarcos( int tablero[N][N], int nuevos)

La función recibe como argumentos una matriz NxN de enteros (tablero) y un valor entero (nuevos). La matriz representa un tablero cuadricular de NxN casilleros. En cada casillero pueden agregarse uno o más barcos. Por lo tanto, el elemento correspondiente a la fila x y columna y de la matriz indica la cantidad de barcos posicionados en la coordenada horizontal x y la coordenada vertical y. El argumento entero (nuevos) indica la cantidad de nuevos barcos que se deben agregar al tablero.  La función debe solicitar que el usuario ingrese tantos pares de coordenadas como indicado por el argumento 'nuevos', y para cada coordenada valida agregar un barco en dicha posicion. De existir ya uno o mas barcos en la misma, se debe agregar un nuevo barco incrementando la cantidad preexistente. Si la coordenada ingresada fuera invalida, no debe agregarse barco alguno.
Pense la solución de la siguiente forma:
void agregarBarcos(int tablero[N][N],int nuevos)
{
    for(int i=0;i<N;i++){
        for(int j=0;j<N;j++){
            do{
            cin >> tablero[i][j];
            }
            while(i==nuevos);
            if(tablero[i][j]!=0){
                tablero[i][j]+=1;
            }
        }
    }

 }

No estoy entendiendo bien la consigna por lo tanto no estoy logrando que compile, tengo los siguientes errores:
_tester__.cpp: In function 'int main()':
__tester__.cpp:33:1: error: this 'for' clause does not guard... [-Werror=misleading-indentation]
 for(int i=0; i<N; i++)
 ^~~
__tester__.cpp:36:5: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'for'
     return 0;
     ^~~~~~

Agradezco cualquier ayuda sea link de libro, video, cualquier cosa sirve.

A: Los errores son claros y concisos, tal vez no los entiendas por estar en inglés, te los traduzco:
__tester__.cpp:33:1: error: this 'for' clause does not guard... [-Werror=misleading-indentation]
 for(int i=0; i<N; i++)
 ^~~
__tester__.cpp:36:5: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'for'
     return 0;
     ^~~~~~

__tester__.cpp:33:1: error: esta cláusula 'for' no corresponde con…  [-Werror=misleading-indentation]
 for(int i=0; i<N; i++)
 ^~~
__tester__.cpp:36:5: nota: … esta sentencia, la cuál está incorrectamente sangrada como si correspondiera con dicho 'for'
     return 0;
     ^~~~~~

*

*-Werror es una opción del compilador que hace que las alarmas se comporten como errores.

*Misleading significa: hacer creer algo que no es cierto.

*Indentation se conoce en Español como sangrado y es un tipo de notación secundaria utilizado para mejorar la legibilidad del código fuente.

En resumen, el error que tienes no es un error, es una alarma que te está indicando que el sangrado de tu código es confuso y sinceramente, tiene mucha razón.

La función debe solicitar que el usuario ingrese tantos pares de coordenadas como indicado por el argumento 'nuevos', y para cada coordenada valida agregar un barco en dicha posición.

Tu código ni siquiera se acerca a hacer algo remotamente parecido, no tiene ningún sentido ni en el contexto del ejercicio ni en el contexto de algo coherente.
Mi propuesta es la siguiente:
for (int datos_leidos = 0; datos_leidos != nuevos; )
{
    unsigned x, y;
    std::cout << "Coordenada X: ";
    std:::cin >> x;
    std::cout << "Coordenada Y: ";
    std:::cin >> y;

    if (x >= N || y >= N)
    {
        std::cout << "Coordenadas incorrectas";
        continue;
    }
    else
        ++datos_leidos;

    ++tablero[x][y];
}

Las coordenadas son unsigned para que no acepten valores negativos; de esta manera basta con comprobar que las coordenadas no sean mayores que N, de serlo repetimos el bucle sin avanzar a la siguiente coordenada; en caso contrario sumamos un barco a la posición de las coordenadas. Puedes ver el código funcionando en Try it online!.

A: Según lo que entendí tienes que agregar tantos barcos según indica la variable int nuevos, siempre y cunado las coordenadas ingresadas sean validas. Seria algo como lo siguiente
void agregarBarcos(int tablero[N][N], int nuevos) {

  // iniciar tablero si es que aun no se ha hecho
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      tablero[i][j] = 0;
    }
  }

  // preguntar coordenadas para ingresar barcos
  for (int i = 0; i < nuevos; nuevos++) {
    int x, y;
    while (true) {
      std::cout << "ingrese coordenada x para el barco " << i << std::endl;
      std::cin >> x;
      std::cout << "Ingrese coordenada y para le barco " << i << std::endl;
      std::cin >> y;

      // valida coordenadas
      if (x < N && y < N) {
        tablero[x][y]++;

        // Si el valor es valido y se puede agregar en la matriz se sale del bloque while.
        break;
      } else {
        std::cout << "valores ingresados no son validos, intentar nuevamente." << std::endl;
        std::cout << std::endl;
      }
    }
  }
}


text:
Q: Move UIScrollView so UIButton is fully shown I have 6 UIButton controls placed inside a UIScrollView.
The buttons are horizontally aligned, but there is only room for 3.5 of them to be visible at a time.
What I want to happen is when I touch the half visible button - for the UIScrollView to move its content so that the touched button will be fully visible (like how the filters bar works in Instagram).

A: - (IBAction)buttonPressed:(id)sender{
      [scrollView scrollRectToVisible:sender.frame animated:YES];
      //your code
}

Add action to button.


text:
Q: How to capture JavaScript event callbacks during run-time? We are looking for a way to capture all the callback-functions that were executed during runtime
for example, if there function a() runs during page load and function b() run upon click on button 'b' I would like to capture a() run at timestamp1 and then b() at timestamp2
I need the file/line/column per function (represents where this function starts)
it's good enough if we could solve it using a browser extension/add-on

A: You sure can do this.
Use the nsIEventListenerInfo component.
https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIEventListenerInfo
Just tell it which element you want to get the listeners for and you get them all. If you want to intercept them and sometimes prevent them then add your own listeners on whatever is being listend to by the target and do event.stopPropagation and e.preventDefault


text:
Q: How to make a reference between two integers in java? int x=1;
int y=x;
System.out.println(y);
x=20;
System.out.println(y);

Obviously the program will print 1 and 1.
However, I need to create a reference between x and y so every time i change x, y will be changed as well.


text:
Q: Boot from CD triggers Bitlocker using Paragon, I have deleted the recovery partition.
Afterwards, Windows 8.1 would not boot anymore.
Then I tried booting from a Partition Manager CD, but when I try to boot from the CD, the Bitlocker Manager kicks it and asks my for a recovery key (which I don't have because I entered some garbage mail during the setup process).
I would like to ask why the Bitlocker kicks it. When I try to boot from the CD, the file system shouldn't be accessed, right?

A: Bitlocker can be associated with the BIOS and is often associated with the onboard TPM chip. These do not require a filesystem to get things going.
If you don't have your recovery key, it's unlikely you'll be able to recover this system. Its likely that the partition you deleted included the necessary bits to initialize Bitlocker, including authentication, for booting from the Bitlocker encrypted drive. It's also likely that the bios recognizes that you have a Bitlocker encrypted drive.
It may be necessary to disconnect the drive before you'll be able to boot the computer. If your computer and HDD support hot swapping, you may be able to just plug in the drive and mount it after booting the system. If not, you'll need something that supports hot swapping such as a USB-to-SATA adapter.


text:
Q: Convert JSON file to xls correctly I have a JSON file I change in a Python file via lists. I'd like to convert it to xls. It's working but not the way I want it.
My JSON file:
[
{
    "populaires": {
        "perfo_indice_annual_value": 100,
        "perfo_percentage_annual_value": "0.96%",
        "perfo_percentage_monthly_value": "0.96%"
    },
    "classics": {
        "perfo_indice_annual_value": 100,
        "perfo_percentage_annual_value": "0.0%",
        "perfo_percentage_monthly_value": "0.0%"
    },
    "500k": {
        "perfo_indice_annual_value": 103,
        "perfo_percentage_annual_value": "3.62%",
        "perfo_percentage_monthly_value": "3.62%"
    },
    "youngtimers": {
        "perfo_indice_annual_value": 105,
        "perfo_percentage_annual_value": "4.97%",
        "perfo_percentage_monthly_value": "4.97%"
    }
}
]

The output I have:

The output I'd like:

My code:
# Just indices
for indices in data_indices:
    indice_pop_modele = indices["populaires"]
    indice_pop = indices["populaires"]["perfo_indice_annual_value"]
    indices["populaires"]["perfo_indice_annual_value"] = int(indices["populaires"]["perfo_indice_annual_value"])
    indices["populaires"]["perfo_percentage_annual_value"] = str(indices["populaires"]["perfo_percentage_annual_value"]) + "%"
    indices["populaires"]["perfo_percentage_monthly_value"] = str(indices["populaires"]["perfo_percentage_monthly_value"]) + "%"
    indice_pop_modele.pop('modeles', None)
    #print(indice_pop_modele)

    indice_classics_modele = indices["classics"]
    indices["classics"]["perfo_indice_annual_value"] = int(indices["classics"]["perfo_indice_annual_value"])
    indices["classics"]["perfo_percentage_annual_value"] = str(indices["classics"]["perfo_percentage_annual_value"]) + "%"
    indices["classics"]["perfo_percentage_monthly_value"] = str(indices["classics"]["perfo_percentage_monthly_value"]) + "%"
    indice_classics_modele.pop('modeles', None)
    #print(indice_classics_modele)

    ...

df_just_indices = pd.DataFrame(data_indices)
df_just_indices.to_excel('indices' + date_file + '.xls')

A: You are creating the dataframe from a list of dict(s). So each dict is an entry, with the keys being the columns and the values the.... values. Since you have just one dict (which represents your whole data), you get one single entry.
First of all you need to extract the dict from the list:
pd.DataFrame(data_indices[0])

This means that now each key is a column, and each inner dict represents the rows.
So this will give:
                               populaires classics   500k youngtimers
perfo_indice_annual_value             100      100    103         105
perfo_percentage_annual_value       0.96%     0.0%  3.62%       4.97%
perfo_percentage_monthly_value      0.96%     0.0%  3.62%       4.97%

But you want the columns as rows in your excel, so simply transpose the dataframe:
pd.DataFrame(data_indices[0]).transpose()

Which will give:
            perfo_indice_annual_value  ... perfo_percentage_monthly_value
populaires                        100  ...                          0.96%
classics                          100  ...                           0.0%
500k                              103  ...                          3.62%
youngtimers                       105  ...                          4.97%


text:
Q: Extract all the valid URL string inside an element (JavaScript) This is probably easy but I'm not very good with javascript especially regex. I know there is a method of getting the substring with either .substr() or .substring(). It's easy for me if I know the index location of the url strings but the text is loaded from the database.
Sample html:

Some text text text text http://stackoverflow.com text text
   text http://google.com text text text.

I want each url string to push inside an array as an output.
var mystrings = new Array
var text = $('p').text();
var url = text.substr()//don't know the logic here
mystrings.push(url);
//output
mystrings[0] == 'http://stackoverflow.com'
mystrings[1] == 'http://google.com'

I also found this regex but I don't know how to incorporate it:
var regexp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

A: Checkout this JSFiddle.  Use RegExp.exec() to execute the regular expression on your text variable.  Since you have the g global modifier on the expression, the while loop will go over each matched URL in the String.
var mystrings = new Array;

var text = $('p').text();
var regexp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

while (matches = regexp.exec(text))
{
    mystrings.push(matches[0]);
}

console.log(mystrings);
// ["http://stackoverflow.com", "http://google.com"]


text:
Q: Show Hide for UILabel over constraint not working as expected for height constraint I have UILabel which I am showing and hiding on tapGesture.
I have created label programatically and set constraint programatically only.
by default UILabel is visible with heightConstraint = 230
on tapGesture method I am making heightConstraint = 0 and its hiding label correctly.
Again on tapGesture I need to show label,
so when I tap again, I can see heightConstraint = 230 again, but label is not seen in UI.
What might be issue, only hide is working and show is not working.
Following is the code for tapGesture method where I am setting height constraints.
@objc func tapLabel(gesture: UITapGestureRecognizer) {
        print("tap working")
        isExpanded.toggle()
        if(isExpanded){
            NSLayoutConstraint.activate([
                reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 230)
            ])
        }else{
            NSLayoutConstraint.activate([
                reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 0)
            ])
        }
    }

I tried to deactivate the constraint but not working.
Please find the screen shot attached.

*

*Default state when label is seen

*On Click, when label is hidden.

now after clicking again label is not showing.
Thanks in advance.

A: This behavior will add more constraints as you click
if(isExpanded){
    NSLayoutConstraint.activate([
        reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 230)
    ])
} else {
    NSLayoutConstraint.activate([
       reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 0)
    ])
}

And will cause a conflict between their values , You need
var heightCon:NSLayoutConstraint!

And inside viewDidLoad set the initial state
heightCon = reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 230)
heightCon.isActive = true

Then play with the constant property inside the click action
heightCon.constant = isExpanded ? 230 : 0
view.layoutIfNeeded()

A: First you need to keep an instance of the height constraint don't create new height constraint every time. like this
var constraint: NSLayoutConstraint?

and inside the viewDidLoad add this
constraint = label.heightAnchor.constraint(equalToConstant: 250)
constraint?.isActive = true

then inside tapLabel function add
constraint?.constant = isExpanded ? 20 : 250

Second  the most important thing when you make your height 0 you can't tap it anymore because the label height is zero then how you can tap something has zero height if you make it 20 like the example i provided the label will be clickable if you want to hide the label completely maybe you need to take another approach  than tapping the label

A: I just sorted the issue.
The issue was I was declaring
var heightCon:NSLayoutConstraint!
as local.
I just declare the same in Global.
Following is the code sorted the issue.
var heightCon:NSLayoutConstraint!
    @objc func tapLabel(gesture: UITapGestureRecognizer) {
        isExpanded.toggle()
        if let constraint = heightCon{
            constraint.isActive = false
        }
        heightCon = reminderBulletsLbl.heightAnchor.constraint(equalToConstant: isExpanded ? 230 : 0)
        heightCon.isActive = true
    }

Thanks @Sh_Khan for the help.


text:
Q: Do wide dependency and shuffle always occur at the same time in Spark? I am reading a spark book, and can hardly understand one sentence below. To me, I cannot imagine a case which is wide dependency, but we don't need shuffle. Can anyone give me an example?
"In certain instances, for example, when Spark already knows the data is partitioned in a certain way, operations with wide dependencies do not cause a shuffle." -- "High Performance Spark" by Holden Karau

A: RDD dependencies are actually in terms of partitions and how partitions are created.
Note: Below definitions are for ease of understanding:
If each of the partitions of an RDDs are created from only one partition of a single RDD, then it is a narrow dependency.
On the other hand, if a partition in a RDD is created from more than one partition(from same or different RDD), then it is a wide dependency.
Shuffle operation is required whenever data required to create a partition is not at one place(that means, it has to be taken from different locations/partitions).
If data is already grouped in one or more partitions(using operations like groupBy, partitionBy etc), you just have to take the corresponding items from each of the partitions and merge them. In this case, shuffle operation is not necessary.
For more details refer this, especially the visual example images.


text:
Q: Plot Mandelbrot with matplotlib / pyplot / numpy / python I am new to python and learning by following Python "Scientific lecture notes Release 2013.1" tutorial. Please help me solve this Mandelbrot problem in the srcreenshot below (Pg 71). Please provide step-wise commands with explanation if possible because programming concepts are new to me.
http://dl.dropbox.com/u/50511173/mandelbrot.png
I tried to solve this as follows:
import numpy as np
import matplotlib.pyplot as plt

x,y=np.ogrid[-2:1:10j,-1.5:1.5:10j]
c=x + 1j*y
z=0
for g in range(50):
  z=z**2 + c

plt.imshow(z.T, extent=[-2,1,-1.5,1.5])

I encountered the following error "TypeError: Image data can not convert to float"
What does this error exactly mean and how to correct it? I am finding it difficult to understand the imshow() function. What do the individual terms inside imshow() mean?
Thank You.

A: The Mandelbrot set is not the values of z you are trying to plot, which are giving you problems because they are complex numbers.  The Mandelbrot set is made up of the points p of the complex plane for which the recurrence relation z_n = z_n-1**2 + p remains bounded. This is checked in a practical way by comparing the result after a few iterations to some threshold. In your case, if you add the following lines after your for loop:
threshold = 2
mask = np.abs(z) < threshold

and then plot mask you should see the set plot on screen.
To understand the general workings of imshow's arguments, you will be better off reading the docs than asking here.

A: Thanks to @Jan and @Jaime. I got it working as follows, takes too much time to calculate though:
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

x,y=np.ogrid[-2:1:5000j,-1.5:1.5:5000j]

print('')
print('Grid set')
print('')

c=x + 1j*y
z=0

for g in range(500):
        print('Iteration number: ',g)
        z=z**2 + c

threshold = 2
mask=np.abs(z) < threshold

print('')
print('Plotting using imshow()')
plt.imshow(mask.T,extent=[-2,1,-1.5,1.5])

print('')
print('plotting done')
print('')

plt.gray()

print('')
print('Preparing to render')
print('')

plt.show()

A: You get this error because plt.imshow does not accept arrays of complex numbers. You can address the real or imaginary part of an array Z as Z.real or Z.imag. Thus if you want to plot the real part
plt.imshow(z.real.T, extent=[-2,1,-1.5,1.5])

would do the job.
The arguments in 'imshow' define the following things.
If z is a N-by-M matrix, it is interpreted as point values on a regular grid. By extent you specify how this grid extends in space...

A: You're trying to plot a complex value with imshow which is why you're getting that error, can use a threshold as others have suggested, but you might want to consider using np.angle or np.abs as well. You can also simplify your calculation of z using Python's built-in reduce method.
Had some fun with this one, but this shows the general idea:
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

x, y = np.ogrid[-2:1:500j, -1.5:1.5:500j]

# Increase this to improve the shape of the fractal
iterations = 9

c = x + 1j*y

z = reduce(lambda x, y: x**2 + c, [1] * iterations, c)

plt.figure(figsize=(10, 10))
plt.imshow(np.angle(z));

plt.figure(figsize=(10, 10))
plt.imshow(np.log(np.abs(z)));


text:
Q: HttpRequest DELETE with body I have to submit an http DELETE request containing a body. I know how I can do it, but in my case it uses java.net.http.HttpRequest. Unfortunately, this component only allows submission of BodyPublisher to PUT and POST requests.
My question is, is there any way to use HttpRequest for the problematic DELETE request?

A: You can use the HttpRequest.Builder::method that takes two arguments:
HttpClient client = HttpClient.newBuilder().proxy(HttpClient.Builder.NO_PROXY).build();
HttpServer server = HttpServer.create();
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/test/", new HttpHandler() {
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        byte[] bytes = exchange.getRequestBody().readAllBytes();
        exchange.sendResponseHeaders(200, bytes.length == 0 ? -1 : bytes.length);
        try (OutputStream os = exchange.getResponseBody()) {
            os.write(bytes);
        }
    }
});
server.start();
try {
    HttpRequest request = HttpRequest.newBuilder()
            .uri(new URI("http", null,
                    server.getAddress().getHostString(),
                    server.getAddress().getPort(),
                    "/test/test", null, null))
            .method("DELETE", HttpRequest.BodyPublishers.ofString("hahaha...")).build();
    var resp = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(resp);
    System.out.println(resp.body());
} finally {
    server.stop(0);
}


text:
Q: How to set browser tab title with route name in React Native currently in my app, the browser tab title is just the name of the screen. However I want to set the tab title to {APP_NAME} - {PAGE_NAME}. I am using a <Stack.Navigator/> and I know that you use the screenOptions to give a custom title, but I cannot access the route name.
<Stack.Navigator
        initialRouteName={Pages.HOME}
        screenOptions={{
          title: `MyAppName - ${route.name}`,
          header: ({ navigation, back, route }) => (
            <Navbar
              navigation={navigation}
              back={back}
              title={route.name}
              navigationOptions={[
                Pages.HOME,
                Pages.MY_MESSAGES,
                Pages.PROFILE_AND_ACCOUNT,
                Pages.MY_ACCOUNT,
                Pages.FAQ,
              ]}
              actions={[logoutAction]}
            />
          ),
        }}
      >

As you can see, the header param contains route, but I cannot/don't know how to get this into the title.
Any help would be appreciated, thanks.

A: You don't need to do this for every screen. You can customize the document title in NavigationContainer
<NavigationContainer
  documentTitle={{
    formatter: (options, route) =>
      `MyAppName - ${options?.title ?? route?.name}`
  }}
>
  {/* content */}
</NavigationContainer>

https://reactnavigation.org/docs/navigation-container/#documenttitle
Though also if you need the route name in options as mentioned in docs:
<Stack.Navigator
  screenOptions={({ route }) => ({
    title: route.name,
  })}
>

https://reactnavigation.org/docs/screen-options/#screenoptions-prop-on-the-navigator


text:
Q: jetty 9 and apache xml rpc 3.1.3: Premature end of file I have to support some old XML RPC service. After upgrade from jetty 6 to 9 I get the following error:
org.apache.xmlrpc.XmlRpcException: Failed to parse XML-RPC request: Premature end of file.
    at org.apache.xmlrpc.server.XmlRpcStreamServer.getRequest(XmlRpcStreamServer.java:71)
    at org.apache.xmlrpc.server.XmlRpcStreamServer.execute(XmlRpcStreamServer.java:199)
    at org.apache.xmlrpc.webserver.XmlRpcServletServer.execute(XmlRpcServletServer.java:112)
    at org.apache.xmlrpc.webserver.XmlRpcServlet.doPost(XmlRpcServlet.java:196)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:696)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:526)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:219)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1110)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:453)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:183)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1044)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:459)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:280)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
    at org.eclipse.jetty.io.AbstractConnection$1.run(AbstractConnection.java:505)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:607)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:536)
    at java.lang.Thread.run(Thread.java:744)

This error does not occur on every request, but arises periodically, which seems to indicate some threading problem. Any suggestions?

A: I've had the same problem. Make sure that you use "Content-Type: application/xml" in requests' headers.


text:
Q: How can I make an element's attribute only appear on hover when another element is hidden? I'm having trouble figuring out how to make the data-title only appear on hovering of the up-arrow only when the footer is down/not showing. However, I would also appreciate another solution where the data-title would still be visible when hovering the up-arrow even when the footer is up/showing. In this case, I would prefer the data-title to be displayed in its original position, up-right/0deg and on top of the up-arrow, rather than rotated 180deg and under the up-arrow.
I've tried using CSS and JavaScript to add and remove the data-title attribute, empty its innerHTML, and toggle its display, but nothing seems to work the way I want. Specifically, I was expecting the data-title to only appear on hover of an element (let's call it "Element A") when another element (let's call it "Element B") is hidden. Element A is the up-arrow, and I want the data-title to be shown on hover of Element A when Element B (the footer) is not visible on the page.
I suspect that the solution may be simple, but I'm struggling to figure it out. Any help or suggestions would be greatly appreciated.

// Get the up arrow element
const upArrow = document.getElementById("up-arrow");
const footer = document.querySelector(".slide-up-footer");
let isOpen = false;

// Add an event listener to toggle the "show" class
upArrow.addEventListener("click", toggleFooter);
upArrow.addEventListener("click", () => {
  footer.classList.toggle("show");
});
function toggleFooter() {
  if (isOpen) {
    footer.style.bottom = "-100%";
    upArrow.style.transform = "rotate(0deg)";
    upArrow.style.bottom = "0";
  } else {
    footer.style.bottom = "0";
    upArrow.style.bottom = "6%";
    upArrow.style.transform = "rotate(180deg)";
  }
  isOpen = !isOpen;
}
html {
    scroll-behavior:smooth;
  }

  body {
    font-family: 'Adobe Caslon Pro Bold', sans-serif;
    background-color: red;
    overflow: hidden;
  }
  body h1 {
    text-align: center;
  }

  .page-wrap {
    position: fixed;
    top: 10px;
    right: 10px;
    left: 10px;
    bottom: 10px;
    background: white;
    border-radius: 30px;
    padding: 20px;
    text-align: center;
    overflow: hidden;
  }

  .page-wrap h1 {
    margin: 0;
  }
  p {
    line-height: 3;
  }

  ::-webkit-scrollbar-track {
    background: none;
  }
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }
  ::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 5px;
  }
  .slide-up-footer {
    display: flex;
    flex-direction: column;
    justify-content: center;
    font: 10px Fakt Soft, sans-serif;
    position: absolute;
    bottom: -1000px; /* or another value that will hide the footer */
    width: 100vw;
    height: 8%;
    transition: all 0.7s ease-in-out;
    background-color: white;

  }

  .slide-up-footer.show {
    bottom: 0;
  }

  .footer-text {
    display: grid;
    grid-row: 1/2;
    font: 12px Fakt Soft, sans-serif;
    color: black;
    text-align: center;
    padding: 10px;
    justify-content: center;
    position: relative;
  }

  .footer-text p{
    line-height: 0;
  }
  .up-arrow {
    transition: all 0.7s ease-in-out;
    position: absolute;
    bottom: 0px;
    right: 0px;
    margin: 2rem;
    z-index: 999;
  }
  .custom-class{
    font-weight: bold;
    font: 20px Fakt Soft, sans-serif;
    color:black;
    cursor: pointer;
    z-index: 999;
  }
 .custom-class:hover::before {
  content: "FOOTER";
  font: 12px Fakt Soft, sans-serif;
  position: absolute;
  background-color: transparent;
  color: black;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Helvetica+Neue&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css" type="text/css">
    <title>Retro Step</title>

FREE SHIPPING IN PORTUGAL / IN EUROPE FROM 150€ / EASY RETURNS

            ^

A: So apply a style when the sibling as the show class to hide it from view
.slide-up-footer.show + .up-arrow > .custom-class:hover::before {
  display: none;
}

// Get the up arrow element
const upArrow = document.getElementById("up-arrow");
const footer = document.querySelector(".slide-up-footer");
let isOpen = false;

// Add an event listener to toggle the "show" class
upArrow.addEventListener("click", toggleFooter);
upArrow.addEventListener("click", () => {
  footer.classList.toggle("show");
});

function toggleFooter() {
  if (isOpen) {
    footer.style.bottom = "-100%";
    upArrow.style.transform = "rotate(0deg)";
    upArrow.style.bottom = "0";
  } else {
    footer.style.bottom = "0";
    upArrow.style.bottom = "6%";
    upArrow.style.transform = "rotate(180deg)";
  }
  isOpen = !isOpen;
}
html {
  scroll-behavior: smooth;
}

body {
  font-family: 'Adobe Caslon Pro Bold', sans-serif;
  background-color: red;
  overflow: hidden;
}

body h1 {
  text-align: center;
}

.page-wrap {
  position: fixed;
  top: 10px;
  right: 10px;
  left: 10px;
  bottom: 10px;
  background: white;
  border-radius: 30px;
  padding: 20px;
  text-align: center;
  overflow: hidden;
}

.page-wrap h1 {
  margin: 0;
}

p {
  line-height: 3;
}

 ::-webkit-scrollbar-track {
  background: none;
}

 ::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

 ::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 5px;
}

.slide-up-footer {
  display: flex;
  flex-direction: column;
  justify-content: center;
  font: 10px Fakt Soft, sans-serif;
  position: absolute;
  bottom: -1000px;
  /* or another value that will hide the footer */
  width: 100vw;
  height: 8%;
  transition: all 0.7s ease-in-out;
  background-color: white;
}

.slide-up-footer.show {
  bottom: 0;
}

.footer-text {
  display: grid;
  grid-row: 1/2;
  font: 12px Fakt Soft, sans-serif;
  color: black;
  text-align: center;
  padding: 10px;
  justify-content: center;
  position: relative;
}

.footer-text p {
  line-height: 0;
}

.up-arrow {
  transition: all 0.7s ease-in-out;
  position: absolute;
  bottom: 0px;
  right: 0px;
  margin: 2rem;
  z-index: 999;
}

.custom-class {
  font-weight: bold;
  font: 20px Fakt Soft, sans-serif;
  color: black;
  cursor: pointer;
  z-index: 999;
}

.custom-class:hover::before {
  content: "FOOTER";
  font: 12px Fakt Soft, sans-serif;
  position: absolute;
  background-color: transparent;
  color: black;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
}

.slide-up-footer.show+.up-arrow>.custom-class:hover::before {
  display: none;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css2?family=Helvetica+Neue&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="style.css" type="text/css">
  <title>Retro Step</title>

FREE SHIPPING IN PORTUGAL / IN EUROPE FROM 150€ / EASY RETURNS

      ^


text:
Q: How to mount NFS export on Mac OS X? I have FreeBSD (test.local) box configured as NFS server. And I'm trying to mount its NFS sharing form my mac (hhmm.local)
/nfs     hhmm.local

/nfs has 777 permission.
And I checked from mac that it's working,
hhmm:~ Eonil$ showmount -e test.local
Exports list on test.local:
/nfs                           test.local
hhmm:~ Eonil$

But when I try to mount it,
hhmm:~ Eonil$ mount_nfs test.local:/nfs ~/nfs
mount_nfs: can't access /nfs: Permission denied
hhmm:~ Eonil$

Wow. I cannot figure out why this doesn't work. What should I do?

A: I had the same issue with mount_nfs: can't access /: Permission denied on OS X 10.6.8 and even with the resvport option it still failed however modifying the nfs server export mount to use the insecure option worked.

A: I solved this problem with this blog post:
http://www.cyberciti.biz/faq/apple-mac-osx-nfs-mount-command-tutorial/
Core solution was giving an option resvport on mounting option. NFS volume mounted magically!

A: Assume that host 10.18.14.27 running NFS has shared path-
/home/siddiquim

On your mac, Try:
$ sudo mount -o resvport,rw  -t nfs  10.18.14.27:/home/siddiquim folder_207

Verify that contents are visible:
$ ls -ltr folder_207

A: my problem solved, NFS to mac High Sierra 10.13
Change on server NFS /etc/exports, put your client IP.
Ex: ip server:192.168.1.2  client ip:192.168.1.10
on server, sudo vi, /export/www   192.168.1.10(rw,insecure,root_squash,no_subtree_check,async)


text:
Q: Matrices: proving that $AA^t=0$ implies $A=0$ I know that applying trace of $AA^t$ gives $A=0$, but I was trying to formalise the proof I thought:
Suposse $A≠0$. Then for every $X$, $A+X≠X$.
So $(A+X)A^t≠XA^t$ for every $X$, arriving in $XA^t≠XA^t$, a contradiction, therefore $A=0$.
But I realise it may not be always true that $A+X≠X$ implies $(A+X)A^t≠XA^t$. But as we can pick any $X$, it seems that the proof is sufficient,  but not formal enough, so I am looking for an improvement in this demonstration
I now know that it is a good idea to look to $X^tAA^tX=0$ for any $X$, wich implies $A^tX=0$, concluding the proof, but why is this implication true?

A: You use that $A\neq B$ implies that $CA\neq CB$. However, this is not true in general (already for $C=0$ it is not true, but also for nonzero $C$). To say, "we can pick any $X$" is not a valid argument, I think.

A: Along the lines of your first (or last) remark: Since $\langle A^t Ax, x\rangle = \langle Ax, Ax\rangle$ vanishes for any $x$, the matrix $A = 0$.


text:
Q: Is there a difference between dynamically allocated pointer to structure and statically allocated pointer to structure in C? I was practicing queues and when I tried to created one like this
struct queue
{
  struct node *front;
  struct node *rear;
};
struct queue *q;

and the function that creates the queue
void create_queue(struct queue *q)
{
  q -> rear = NULL;
  q -> front = NULL;
}

it failed at runtime but when I allocated the pointer to the queue inside the function dynamically
it worked.
like this
struct queue* queue_create(void)
{
  struct queue* q = (struct queue*)malloc(sizeof(struct queue));
  q->rear=NULL;
  q->front=NULL;
}

A: This code:
struct queue
{
  struct node *front;
  struct node *rear;
};
struct queue *q;

creates a NULL pointer to struct queue. It does not allocate an instance of this struct (unlike your code which allocates memory dynamically).
So when you call create_queue() on this NULL pointer, you (naturally) get SIGSEGV.
To statically allocate an instance of struct queue, do this:
struct queue q;

Then you can initialize it with create_queue(&q).
P.S. The statically allocated struct queue will already be zero-initialized, so calling create_queue() on that instance is actually a no-op.

A: In this function
struct queue* queue_create(void)
{
  struct queue* q = (struct queue*)malloc(sizeof(struct queue));
  q->rear=NULL;
  q->front=NULL;
}

You are not allocating a pointer dynamically as you are saying. The pointer q is a local variable of the function that will not be alive after exiting the function.
What you are allocating dynamically is an object of the type struct queue. The address of the allocated object is assigned to the local pointer.
Also what you need is to return the pointer  from the function.
struct queue* queue_create(void)
{
  struct queue* q = (struct queue*)malloc(sizeof(struct queue));
  q->rear=NULL;
  q->front=NULL;

  return q;
}

Otherwise there will be a memory leak.
As for this declaration of a pointer in the file scope
struct queue *q;

then it is initialized as a null pointer. So using the null pointer in this function to access memory
void create_queue(struct queue *q)
{
  q -> rear = NULL;
  q -> front = NULL;
}

invokes undefined behavior.
That is what you need to allocate dynamically is an object of the structure type. Where there will be declared a pointer that will point to the allocated object is in fact unimportant. What is important is the pointer must point to a valid object of the structure type. In this case using the pointer you can change data members of the object pointed to by the pointer.