Cannot feed dataframe containing also array column in Sklearn MLPClassifier

Question: I'm rather new for Python and dataframes. I have dataframe where one column is array (mfcc data from wav, arrays in all rows have the same length 273), others are float columns.
Code is rather simple:
train_mfccs, test_mfccs, train_labels, test_labels = train_test_split(df, Y, test_size=0.1, shuffle= True)

clf = MLPClassifier(max_iter=150)
clf.fit(train_mfccs, train_labels)

I cannot put the whole dataframe in fit method because of error - ValueError: setting an array element with a sequence.
I successfully can get results if I leave in dataframe only array column, or only float columns, but not both.
Also I tried to play around with np array without results because it requires for each new column to be the same shape as the first one.
I tried simple way of adding column of the same shape and then fill the first value only.
But this gives unexpected shape (50000, 1638) though I wanted (50000,2) where:

first column is initial arrays with length of 273
second is new array with length of 273 and with first value equal to attr1.

X = np.array(list(df['mfcc']), dtype=np.float)
X0 = np.zeros((50000,273))
for index, value in enumerate(df['attr1']):
        X0[index][0] = value
X = np.hstack((X,X0))

Is this possible to achieve - one column is array, others are not?
Answer: We can just add inner array data as main dataframe columns.
Example: we have data in array column like this:

To create list of columns we can generate columns names:
mfccColNames = list(map(str, range(maxlen)))
print(mfccColNames)

So we get numbers as column names:

['0', '1', '2', '3', '4', '5', '6'... '272']

And then fill dataframe:
df_x = pd.DataFrame(df['mfcc'].to_list(), columns=mfccColNames)

This results in all inner array data added as columns to dataframe which can be used in sklearn now.
Then we can add other columns from previous dataframe as needed.


Swift MKMapView KVO

Question: Im trying to create a Key Value Observation for my user current location but I can not get the method of KVO to trigger any information. the delegate for mapView is set.
//add observer here
self.mapView.addObserver(self, forKeyPath: "userLocation", options: NSKeyValueObservingOptions.new, context: nil)

//my method
  override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print(keyPath!)
    }

Comment: See this answer: http://stackoverflow.com/questions/2473706/how-do-i-zoom-an-mkmapview-to-the-users-current-location-without-cllocationmanage/2578459#2578459 `self.mapView.userLocation.location` is the property that contains the current location coordinates.  You need to observe that property for changes.
Answer: Use CLLocationManager:
class ViewController: UIViewController, CLLocationManagerDelegate {
    // You must hold a strong reference to the location manager so make it an instance property
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self

        // Check your app's authorization status
        switch CLLocationManager.authorizationStatus() {
        case .authorizedWhenInUse, .authorizedAlways:
            // Authorized, start tracking location
            self.startUpdatingLocation()
        case .notDetermined:
            // Not authorized, ask for permission. You can also replace this with
            // locationManager.requestAlwaysAuthorization() if your app needs it
            locationManager.requestWhenInUseAuthorization()
        default:
            print("permission denied")
            break;
        }
    }

    // MARK: -
    func startUpdatingLocation() {
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse || status == .authorizedAlways {
            self.startUpdatingLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let lastLocation = locations.last else {
            return
        }

        // now do what you want with the user's location
    }
}

Remember to add NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription to your Info.plist to explain why you need to know the user's location. Also prepare for the case when the user does not give you permission to access the phone's location - you have to decide what part of your app can run with knowing the user's location.
Answer: if you want to know when your current location changes, you can try the CLLocationManager class and use his delegate method
func locationManager(_ manager: CLLocationManager,
       didUpdateLocations locations: [CLLocation])

I hope it helps :)

Swift MKMapView KVO


Using Jenkins as graphical frontend - parametrized builds

Question: I have a few build scripts which can be run from the command line. I'd like to have a web UI to run them and I thought about using Jenkins. I see that the Jenkins job supports parameters and then defined parameters are set as environment variables in the build environment. However, I would not like to have to alter my scripts to accept input from environment variables, it would be easier to continue to accept input from command line. I thought about adding the following shell command to the Jenkins job:
<code>eg <build_script> --option1 $JENKINS_PARAM1 --option2 $JENKINS_PARAM2
</code>
Then, I would not need to alter my existing build scripts. Is that a common/recommended usage of Jenkins?
Answer: Yes, This seems to be perfectly fine for me.


Global Array not saving a change made to it

Question: Public Sub changePoints(ByVal Name As String, StartPoint As Boolean, Point As Integer)

    Locations(Point).Name = Name

    If StartPoint = True Then
        For i = 0 To 19
            Locations(i).StartPoint = False
        Next
    End If
    Locations(Point).StartPoint = StartPoint
    DrawGraph()
End Sub

Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click

    GraphicalPlot.changePoints(PointNameBox.Text, MakeStart.Checked, LoadedPointValue)

End Sub

So i have 2 forms. The first form, when clicked with a point selected, brings up the second form with details of the point in an editable textbox. When you click the save button on the second form to save details, the 2nd subroutine above runs, and calls the subroutine in the first form that holds the global variable.
The information passes to the subroutine in the first form correctly. When i check the value of the global array immediately after changing it (right after the line Locations(Point).Name = Name), it says the value has been changed properly.
However, after the subroutine finishes, the global array returns to the value it had before the subroutine was called, and there is no trace of the information i input to the second form.
If it helps, the global array is of a structure:
Structure EnteredPoint
    Dim Xcoord As Integer   'Stores X co-ordinate of point
    Dim Ycoord As Integer   'Store Y co-ordinate of point
    Dim Name As String      'Stores name of point, used to check if point is unused
    Dim StartPoint As Boolean   'Checks if the point is the start point
    Dim Selected As Boolean     'Checks if the point is currently being hovered over the mouse
    Dim nextPoint As Integer    'Used to implement a linked list, making deleting and recreating points easier
End Structure

The name changing back to what it was shouldn't be possible; the only time my program changes the name outside of initialization (which sets it to "unused", or the number of points that have been created) is here.
I've googled it, showed it to my teacher, and a friend, and we couldn't find anything despite playing with it for hours. Any help would be much appreciated, since this is for my Comp4 coursework!
Edit: added for vbnet3d
Sub DrawGraph()
    'Used to draw the current state.
    G = Me.CreateGraphics
    G.Clear(Color.White)    'Sets entire background to white
    Dim placeholder As Integer = 0  'Used to store the current point being checked.
    If UsedLocations > 0 Then   'This part will only run if any points have been made
        Do Until Locations(placeholder).nextPoint = 0   'Loops until all points have been drawn

            If Locations(placeholder).StartPoint = True Then    'will only draw this if it is the starting point
                G.FillEllipse(Brushes.LightBlue, Locations(placeholder).Xcoord - 3, Locations(placeholder).Ycoord - 3, 16, 16)
            End If
            If Locations(placeholder).Selected = True Then      'Will only draw this if it is the currently selected point
                G.FillEllipse(Brushes.LightGreen, Locations(placeholder).Xcoord - 3, Locations(placeholder).Ycoord - 3, 16, 16)
            End If
            'Draws the actual Point
            G.FillEllipse(Brushes.Black, Locations(placeholder).Xcoord, Locations(placeholder).Ycoord, 10, 10)
            If UsedLocations <= 20 Then
                placeholder = Locations(placeholder).nextPoint  'Gets the next point to be checked.
            End If

        Loop
        If UsedLocations = 20 Then
            If Locations(placeholder).Selected = True Then      'Will only draw this if it is the currently selected point
                G.FillEllipse(Brushes.LightGreen, Locations(placeholder).Xcoord - 3, Locations(placeholder).Ycoord - 3, 16, 16)
            End If
            'Draws the actual Point
            G.FillEllipse(Brushes.Black, Locations(placeholder).Xcoord, Locations(placeholder).Ycoord, 10, 10)
        End If
    End If

End Sub

Comment: Probably has to do with default form references.  What are the form names?
Comment: Where is the Locations array declared?
Comment: Locations array is declared at the very top, globally, first line under public class Graphical Plot
Comment: Form names are GraphicalPlot and GraphicsMenu
Comment: Would it be possible for you to post the code of DrawGraph()?
Comment: DrawGraph() added to main body
Comment: Use explicit form instances. `GraphicalPlot.changePoints` can too easily refer to the class not the instance you see on screen
Comment: Trying to figure out if i can get that working, haven't used explicit instances very much in the past, so getting it to refer to the correct instance is confusing me a bit :/
Comment: Just a hunch... have you tried using Me.Locations?
Comment: Just tried it, it didn't seem to work, where were you thinking of using it?
Comment: Also worth noting, After trying some console outputs, it seems that before wanting to save the name, it thinks that the name is null, which I'd guess suggests a new instance is made.
Comment: I think using Structure is your culprit... see Chris Dunaway's answer.
Comment: Just tried his answer, no dice :/ The locations(point) being used by the subroutine is null for some reason.
Comment: What is `GraphicalPlot`?  @vbnet3d suggestion is valid.  Try using `Me.changePoints(...)` in the SaveButton click event.
Comment: GraphicalPlot is the class that creates the second form (GraphicsMenu), GraphicsMenu is where the savebutton is located, and calls the changepoints subroutine in GraphicalPlot
Comment: If it would help, i can message you a copy to a dropbox link of all of my code, over skype or something similar.
Comment: @Hellfire If you want to send me a dropbox link, I will check it over.
Comment: Sorry it took me so long to reply, School ended. Add me on skype (hell_fire_omega) and I'll send you the link.
Answer: The problem is that you are using a value type (Structure) in your array.  When you access the array element, you are getting a copy of the item so your changes are only made on the copy.
You will have to get the EnteredPoint from the array, change the properties as needed and then reassign the point back to the array:
Public Sub changePoints(ByVal Name As String, StartPoint As Boolean, Point As Integer)

    Dim pointToChange As EnteredPoint = Locations(Point)

    pointToChange.Name = Name

    If StartPoint = True Then
        For i = 0 To 19
            Dim tmp As EnteredPoint = Locations(i)
            tmp.StartPoint = False
            Locations(i) = tmp
        Next
    End If

    pointToChange.StartPoint = StartPoint
    Locations(Point) = pointToChange

    DrawGraph()
End Sub

If you wish to keep your original syntax, then you can change EnteredPoint to a class and it will work as you expect.
Comment: Just tried copy/pasting the edited subroutine you suggested, still no dice :/ After checking what's being used, the Locations(point) being loaded into PointToChange seems to be null.
Comment: @Hellfire - If `Locations` is an array of `EnteredPoint`, which is a structure, it cannot be null because value types cannot be null.  If the integer `Point` points to a valid index in the array, then it cannot be null.  If the integer is invalid, you will get an `IndexOutOfRangeException`.
Answer: Your issue is being caused by default form references. (See comment by @Plutonix) What this means is that you have a base class instance called "GraphicalPlot" but you also have an active instance of "GraphicalPlot" which is a separate instance. These two classes are identical in form, but do not share in-memory data (one is a model for the other). When you make the following call, it references the model form instead of the active form:
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click

    GraphicalPlot.changePoints(PointNameBox.Text, MakeStart.Checked, LoadedPointValue)

End Sub

You need to create a reference to the active form (GraphicalPlot), and pass it to GraphicsMenu using Me as the current instance reference. Something along the lines of:
GraphicsMenu.Load(Me, PointName, PointNum)

And in GraphicsMenu:
Dim GP As GraphicalPlot
Public Sub Load(ByVal PlotForm As GraphicalPlot, ByVal Name As String, pointnumber As Integer)

    GP = PlotForm

End Sub


ScheduledExecutorService. how to run two tasks after some timeinterval in 2 seperate services

Question: I am trying to implement continuously running background tasks for my app.
For that i used ScheduledExecutorService class.
I have 2 services Service A and Service B both have a task that runs all the time after some time interval. For that i used this following in Service A and Service B
This is the code which is common in both service classes.
Runnable postNotificationRunnable = new Runnable() {
            @Override
            public void run() {
            // statements here}
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    scheduledExecutorService.scheduleAtFixedRate(postNotificationRunnable, 0, 1000, TimeUnit.SECONDS);

Now the problem is when i run app both services starts but only only scheduledExecutorService of Service A runs other one doesn't run. what i am doing wrong?
P.S i am using ScheduledExecutorService for the first time.
Answer: The ScheduledExecutorService will wait for your tasks to finish, iff one takes longer than the rate you specify (in your case 1000 seconds). Have a look at the respective Javadoc:

[...] If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

Since your services seem to behave like daemons (and therefore keep running until the application is shut down), you could do it like this:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
ExecutorService pool = Executors.newCachedThreadPool();

scheduler.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        pool.execute(postNotificationRunnable);
    }
}, 0L, 1000L, TimeUnit.SECONDS);

Simply delegate the actual execution of your services to a separate pool that doesn't affect the scheduler.
Comment: When the scheduler repeats, how to know from which pool is being repeated? If he has two schedulers running, how to know after 1000L (your set repeated time) which service is repeated?


Erro "Undefined symbols" ao compilar projeto

Question: Estou tentando compilar um projeto em C++, mas está dando o seguinte erro:

Undefined symbols for architecture x86_64:

  "knapSack(int, int*, int*, int)", referenced from:

      _main in main-b722ae.o

ld: symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation)

Alguma ideia do que isso pode ser?
Estou usando o sistema MacOs X 10.9. Segue o trecho do código onde está sendo apontado o erro:
// Returns the maximum value that can be put in a knapsack of capacity W

int knapSack(int W, int wt[], int val[], int n)
{
   int i, w, profit, cont = 0;

   item* K = NULL;

   //Build table K[][] in bottom up manner

   for (i = 0; i <= n; i++)
   {
       for (w = 0; w <= W; w++)
       {
           if (i==0 || w==0)
           {
               profit = 0;

               K = insertItem(profit, K);
           }

           else if (wt[i-1] <= w)
           {
               profit = max(val[i-1] + returnItem(K, (i-1), (w-wt[i-1]), W),  returnItem(K, (i-1), w, W));

               K = insertItem(profit, K);
           }

           else
           {
               profit = returnItem(K, (i-1), w, W);

               K = returnItem(profit, K);
           }

           cont++;

            if(cont % 1000 == 0)
            {

                cout << "i = "<< i << "w = " << w << "profit = " << profit << endl;//printf("i = %d, w = %d, profit = %d \n", i, w, profit);

            }
       }
   }
   return returnItem(K, (i-1), (w-1), W);
}

Comment: Você linkou a lib na hora de compilar? Talvez o link esteja com o caminho errado, presumo que é isto que esta mensagem quer dizer "linker command failed"
Answer: O arquivo fonte onde a função "knapSack" foi definida não foi incluído no build.
Ou então, se é uma função fornecida por uma biblioteca, esta biblioteca deve ser fornecida na link-edição.
Como fazer ? Isso depende de como você está trabalhando, se é linha de comando ou se é uma IDE.
Supondo linha de comando e gcc, e supondo que você tem os arquivos knapSack.h e knapSack.cpp com a interface e a implementação da função, então você precisa incluir o arquivo knapSack.cpp na compilação, por exemplo:
g++ -o xxx main.cpp knapSack.cpp

Comment: Eu declarei a função "knapSack" em um arquivo .h, que é incluído no início do código. Não basta só isso para funcionar, em qualquer caso de chamadas de funções que estejam em outros arquivos?
Comment: Não basta só a  **declaração** uma função ou variável, é necessário também a **definição**. Note que em C++ estes são termos técnicos. Você precisa compilar o arquivo fonte onde a função knapSack está **definida**, e incluir o arquivo objeto (.o ou .obj) gerado na link-edição. Se for uma função fornecida por uma biblioteca, você precisa incluir a biblioteca na link-edição. Como você está compilando ? É na linha de comando ? É com IDE ? Você precisa dar mais informações para ter uma resposta mais específica.
Comment: Eu estou compilando na linha de comando, com o g++. Acho que entendi o que você falou. Consegui incluir os arquivos da maneira correta agora. Mas para ficar claro, eu criei um .h com o protótipo (a declaração, como você disse) da função knapSack e um .cpp para a implementação dela (a definição). Na minha main, que chama a função, eu devo chamar o .cpp?


Is it possible to specify baseline hazard in coxph?

Question: I am running simulations and I need to run a Cox model with a certain baseline hazard. The data are generated with a constant baseline hazard $A$ and I need to run coxph using this data but instead of estimating baseline hazard using Breslow formula, I need R to use baseline hazard=$B$). Is there a way to do it?
Answer: You're just doing exponential survival, e.g. parametric survival. See ?survreg in the survival package. If you specify dist='exponential' as an argument, it will assume a constant hazard function and estimate that baseline hazard along with the hazard ratios. It will not, for instance, take a user supplied baseline hazard and estimate the hazard ratios of the regression model.
As you know, when doing Cox regression, you make no assumption about the functional form of the baseline hazard, it is not estimated but factors out of the partial likelihood. So if the hazard is indeed constant, the Cox model will still estimate the right hazard ratio. What you lose by doing this is a bit of efficiency. In very small sample sizes, this is a legitimate concern.
If you want to estimate the HR with maximum likelihood, you can tweak the equations to give any baseline hazard estimate you want, even the "wrong" one ($B$ as you call it). Parametric survival models are just maximum likelihood. To do that, you need to modify the likelihood equations and come up with an estimating equation for the survival model. It shouldn't be too hard since you simply need to combine the exponential density functions dexp and pexp (for censored obs) along with nlm.
Example below:
library(survival)
set.seed(1)

## sample size
n <- 1000

## binary exposure (prevalence)
p <- 0.1
x <- rbinom(n, 1, p)

## baseline hazard / hazard ratio
a <- 0.05
h <- 1.30

## generate survival times
t <- rexp(n, rate=exp(-log(a) + log(h)*x))

## check with cox model
coxph(Surv(t) ~ x)

## parametric exponential survival model (comes from "rate" based model so opposite)
survreg(Surv(t) ~ x, dist='exp')

## unconstrained ML, gives same results as above
negLogLik <- function(param) {
  -sum(dexp(t, exp(-param[1] + param[2]*x), log=TRUE))
}
nlm(negLogLik, c(0,0))

## now with the "right" BL hazard
negLogLikBLH <- function(param) {
  -sum(dexp(t, exp(-log(a) + param[2]*x), log=TRUE))
}
exp(nlm(negLogLikBLH, c(0,0))$estimate)

## now with the "wrong" BL hazard
b <- 0.10
negLogLikBLH2 <- function(param) {
  -sum(dexp(t, exp(-log(b) + param[2]*x), log=TRUE))
}
nlm(negLogLikBLH2, c(0,0))


Remover span adicionado com checkbox

Question: Possuo o input no html

<input value ="Get" onClick={GetSelected} type="checkbox" value="SLA contratual" />

ao ser clicado é adicionado um span em uma lista

Preciso remover se clicado novamente no input, porém não estou conseguindo. Segue o script

function GetSelected() {
        var selected = new Array();
        var p = document.getElementById("teste");
        var portfolio = document.getElementById("section");
        var chks = portfolio.getElementsByTagName("INPUT");
        var span = document.createElement("span");

        for (var i =  0; i < chks.length; i++ ) {
            if (chks[i].checked) {
                selected.push(chks[i].value);
            }
        };

        if (selected.length > 0) {
            console.log("Você selecionou: " + selected.join(", "));
            span.innerHTML = selected.join(", ");
            p.appendChild(span);
        }

    };
Comment: É só um input checkbox ou são vários?
Comment: são vários, cada um dentro de uma lista
Answer: Olá,
caso não seja necessário adicionar em um array, você adicionar diretamente na lista e excluir pelo id do elemento conforme exemplo abaixo:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <input class="chbSelect" name="options" type="radio" value="Option 1" id="database_id_1">Option 1</input>

    <input class="chbSelect" name="options" type="radio" value="Option 2" id="database_id_2">Option 2</input>

    <input class="chbSelect" name="options" type="radio" value="Option 3" id="database_id_3">Option 3</input>

Comment: Funcionou perfeitamente, muito obrigado. Só uma dúvida, caso queira limitar a apenas selecionar um checkbox, como iria ficar?
Comment: Em vez de checkbox você pode trocar para radio e então todos tem que ter o a mesma tag "name", com isso, o próprio componente não permitirá ao usuário selecionar mais de um.

outra coisa que pode ser feito é colocar a linha $('#my-list li').remove(); no método GetSelected, na primeira linha, aí pode arrancar o else do if fora..

Mas se você só vai apresentar um valor, é necessário usar uma lista?
Outra coisa, se só pode selecionar um valor, o checkbox ou radio não pode ser substituído por um select (combobox)?

Se ficar com dúvida me avise que eu eu ajusto o código para você entender.
Comment: Testei com o radio porém quando selecionado e clicando novamente ele é adicionado na lista. O combobox não se aplica pq são categorias diferentes onde o usuário poderá escolher.
Comment: Olá, eu editei o código da resposta, por favor verifique se é isso que você precisa.
Comment: Como uso react o ideal seria javascript ao invés de jquery, mas na primeira tentativa modifiquei e funcionou, porém com a edição não consegui fazer funcionar o código
Answer: Não sei se entendi bem, mas se você quer inserir e remover um span numa li de acordo com os checkboxes marcados, bastaria usar um else no if dentro do for e usar .removeChild().
Ao percorrer a lista de checkboxes e o que não estiver marcado, o value não entra na array e é removido o span da lista que possua o mesmo índice.
Agora, veja que você colocou dois values no checkbox: value="Get" e value="SLA contratual". O primeiro será ignorado.
No último if me parece que você só deveria inserir o span caso o checkbox esteja marcado. Em vez de if (selected.length > 0) você usaria if (e.checked).
Veja como ficaria o código:

function GetSelected(e) {
   var selected = new Array();
   var p = document.getElementById("teste");
   var portfolio = document.getElementById("section");
   var chks = portfolio.getElementsByTagName("INPUT");
   var span = document.createElement("span");

   for (var i =  0; i < chks.length; i++ ) {
      if (chks[i].checked) {
         selected.push(chks[i].value);
      }else if(p.childNodes[i]){
         p.removeChild(p.childNodes[i]);
      }
   };

   console.log("Você selecionou: " + selected.join(", "));
   if (e.checked) {
      span.innerHTML = selected.join(", ");
      p.appendChild(span);
   }

};
span{
   display: inline-block;
   background: yellow;
   margin: 2px;
}

   <input onClick="GetSelected(this)" type="checkbox" value="SLA contratual" />
   <input onClick="GetSelected(this)" type="checkbox" value="Outra coisa" />

Remover span adicionado com checkbox


Dispatch Drawer não funciona

Question: estou tentanto implementar um drawer em meu app. Como eu quero somente em uma das minhas screens. Ao tentar implementar, eu senti algumas dificuldades. Então fiz passo a passo para não se perder.
Criei um botão e quero fazer o drawer abrir quando ele for clicado, porém não está me retornando nada.
Segue o código abaixo:
import React from 'react';
import { View, Button} from 'react-native';
import { createAppContainer, DrawerNavigator } from 'react-navigation';
import { createDrawerNavigator, DrawerActions } from 'react-navigation-drawer';
import TabsNav from './TabsLeadScreen';

const AppNavigator = createDrawerNavigator({
    Contact: {
        screen: TabsNav
    },
    Teste: {
        screen: TabsNav
    }
}, {});

const DrawerCustom = createAppContainer(AppNavigator);

function ShowScreen({ navigation }) {
    return (
        <View>
            <Button title="abrir" onPress={() => navigation.dispatch(DrawerActions.openDrawer())} />
            <DrawerCustom />
        </View>
    );
}

Estou usando o
-react-navigation: ^4.0.10
-expo: ~37.0.3
Alguém poderia me ajudar?
Obrigado!
Comment: Iae, use esse link como exemplo.
Qualquer dúvida só comentar
[https://pt.stackoverflow.com/a/446384/160305](https://pt.stackoverflow.com/a/446384/160305)
Comment: Opa, então, eu inserir um modelo igual o seu, porém quando eu dou um onclick no botão para abrir, ele continua não acontecendo nada... Ai inserir um console.log para ver o retorno dele, está retornando **false**  `estou passando esse código navigation.dispatch(DrawerActions.openDrawer())`
Answer: Se quer apenas em uma screen, cria um botão para abrir a Drawer.
const Drawer = createDrawerNavigator({
    Home: {screen: Home,},
  },
  {
    contentComponent: DrawerContent,
    contentOptions: {
      activeTintColor: "#F05B66"
    },
    headerMode: "none",
    initialRouteName: "Home",
    drawerWidth: deviceWidth - 90,

  }
)

_navigator.dispatch(DrawerActions.openDrawer())
const Logado = createStackNavigator(
  {
    Home: {screen: Home,},
    Painel: {screen: Painel,},
    Drawer: {screen: Drawer}
  },
  {
    initialRouteName: "Drawer",
    headerMode: "none",
    lazy: true,
    defaultNavigationOptions: {
      ...TransitionPresets.SlideFromRightIOS,
    },
  }
);

Comment: Então, quando eu tento fazer o onpress para dar o `DrawerActions.openDrawer())` ele não retorna nada, então inseri um console.log para ver que tipo de retorno está dando, o retorno dele é false... O que será que pode ser?

Dispatch Drawer não funciona


Simple&efficient slider module for the following purpose

Question: I'm looking for a recommendation of a rather simple, conventional, D7 carousel\rotator\slider module that will let just to replace images (without many advanced techniques).
What I do need this module to have, and doesn't very much compromise about, is these features:

Pointers (Left and right) to move between pics.
Small dots that reflect the current picture being shown.
Text that "comes" into the center of the picture from different
directions, and that Ican have full management of it's appearance
(Font-Family, size, color, etc).

Thank you very much for your help!
Comment: have you bothered to actually do any research?  have you tried any of the dozen or so sliders out there?
Answer: Views Slideshow isn't a bad way to go. It will probably take some working with css/templates/views to get it to display the way you want, but it is the most used module, so if you find yourself up against a wall using it, there's a good chance someone's already has done it and has written a tutorial, or would answer a question.
There are a few other modules out there you could look at. A quick search I found this page, which has a decent list
Also a very in-depth comparison on the different modules out there from drupal.org


Interpreting verbose output from sklearn Random Forest

Question: Just wondering what the output message below means:
[Parallel(n_jobs=-2)]: Using backend ThreadingBackend with 11 concurrent workers.
[Parallel(n_jobs=-2)]: Done  28 tasks      | elapsed: 901.9min
[Parallel(n_jobs=-2)]: Done  50 out of  50 | elapsed: 1366.7min finished

What is a task here? Does it refer to each individual estimator, hence setting n_estimators=100 creates 100 tasks? Or is it related to something else?
Comment: It's 100 [decision trees](https://towardsdatascience.com/random-forest-in-python-24d0893d51c0)..
Comment: @p._phidot_ Thanks!
Answer: #model 4 - Random Forest Classifier with tuned hyperparameters
seed=42
pipeline_rf = pipe_imb(steps=[ ("vect", text.TfidfVectorizer(lowercase=False, ngram_range=(1,2), smooth_idf=True, min_df=0.001, max_df = 0.5)),
                               ('sampler', SMOTE(random_state=seed, sampling_strategy='minority')),
                               ('clf', RandomForestClassifier(random_state=seed))])

params = {
    'clf__n_estimators'     : [300,500]}

kfold = StratifiedKFold(n_splits = 3, random_state = 42, shuffle=True)
gridSearch_rf = GridSearchCV(pipeline_rf, param_grid = params, n_jobs=-1, cv=kfold,  verbose=0))
gridSearch_rf.fit(X_train,y_train)
print('Best parameters:', gridSearch_rf.best_params_)
print('Best CV score  :', gridSearch_rf.best_score_)

You can use verbose in GridSearchCV like this. If you send your code, I can help you to solve (:
Comment: Thanks. I don't have a problem with setting up a grid search.


Mitigating Windows Server Update risk?

Question: I'm new to the IT industry; I'm not a sysadmin...I'm a road construction guy by trade. So let me know if I've mixed up any terminology, concepts, etc.

My organization's IT department is very small. We seem to be barely treading water when it comes to keeping our IT systems "up".
The thing that causes the most system outages is Windows Server updates.  Windows updates seem to bring down our application servers about once per month.
The updates are scheduled to happen automatically -- after-hours on a monthly basis.

Here's an example of a recent outage:

The application server that contains the WebSphere JVMs for our work order management system was automatically updated late at night (via the 1-month schedule).

Today, when users started using the work order management system, we got a bunch of integration/java errors from the JVM.

When investigated, it was clear that issue was caused by the updates. We've never had that issue before, and it happened right after the updates were applied.

Our sysadmin restarted the server, which seemed to solve the issue right away. We dealt with the failed integration messages, etc. and life went on (at least until the next update happens).

I know that my organization isn't the only one that struggles with with windows updates issues. It seems to be a pretty widespread problem.
But my question is:
Are there techniques for handling updates that my organization might have overlooked?
For example, it occurred to me that we could:

Manually apply the updates and restart the servers on Saturday mornings
Thoroughly test all of our systems
Have all weekend to deal with issues and restart servers if we need to (instead of doing it live during business hours).

Are there any standard practices like that for mitigating the risk that comes with updating Windows servers?
Comment: The *"right way"* might well have very little to do with the windows OS and very much with improving the general quality of the business-critical software that runs on top. You see, software targeting the windows OS should not fail on things that are normal during operation of the windows OS. From the outside it is hard to tell though, experienced admins tend to be more careful about "it happened right after X, so it must be caused by X" conclusions.
Answer: Sorry to hear about all the errors in your production environment due to the Windows server updates. I dont work with windows servers but almost pretty sure those updates can be disabled to do not apply automatically. What normally happens is that there are two environments one for testing and one for production so you dont deploy anything that has not been tested  first in your test enviroment.
You may also find interesting topics such as DevOps ITIL
Cloud Computing.
If the information was helpful please don't forget to up vote or accept the answer.

Mitigating Windows Server Update risk?


Gauss elimination in Galois Fields

Question: Suppose I have the following system of equations:
\begin{cases} A+B+C+D+P+Q=0 \\ Ax^5+Bx^4+Cx^3+Dx^2+Px+Q=0 \end{cases}
Also suppose that we are working in a $ GF(2^4) $ field.
Use the following irreducable polynomial: $g(x)=x^4+x^3+1$
How can I use the gauss elimination algorithm to find P and Q in function of the other letters?
Answer: Subtract the first equation from the second and you would get:
$$P(x-1) = A(1-x^5) + B(1-x^4) + C(1-x^3) + D(1-x^2)$$
Now find the inverse of $(x-1)$ in $GF(2^4) \cong \mathbb{Z}_2/\langle g(x) \rangle$ and multiply both sides to find out the value of $P$. As you should probably now you can use the Euclidean Algorithm to find out the inverse.
Afterwards directly from the first equation you get $Q = -A -B -C -D -P$, where you will substitute the value of $P$ from above.

Gauss elimination in Galois Fields


Java Jersey Declarative Hyperlinks Configuration

Question: I am confused by the Jersey Documentation Chapter 6
http://jersey.java.net/nonav/documentation/latest/linking.html
The configuration section (6.5) doesn't say where to add the dependency etc. What file(s) need to be edited?
I am confused what I need to do all together in order to use the @Ref attribute in my code.
EDIT/UPDATE
How do I use Jersey Hyperlinking without Maven. I've grabbed the jar file jersey-server-linking-1.9-SNAPSHOT.jar but I don't know what it depends on. Can some one give me a list of jars I need to get this working?
Answer: From the Jersey Hyperlinking POM,
here's the list of dependencies you need at runtime:
<code> <dependencies>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>el-impl</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>
</code>
Answer: The dependency appears to be a maven dependency, So you'd put it in the typical maven configuration files, I'm not all that familiar with maven. This is really to make sure the Jersey linking module libraries are included in your application.
The rest of the code samples in that section refer to modifications you need to make to web.xml.
Comment: Thanks. I'm not familiar with Maven either.


How do I tell gnuplot to get the array size from a variable when plotting binary?

Question: I want to plot binary files of variable size with a gnuplot script. The script should automatically read the size of the plot from the file size. E.g. if the file is 4096 KB (= 1024 x 1024 x 4 Byte floats) the size to be used should be binary array=1024x1024 and if it is 66 KB (= 128 x 128 x 4 Byte floats) it should be binary array=128x128. I can read the plotsize into a gnuplot variable named PLOTSIZE like this:
#!/usr/bin/gnuplot -p
reset

set palett gray
PLOTSIZE=`echo $(( $(du -B1 xy.bin | grep -oP "\d+")/4 ))`
PLOTSIZE=sqrt(PLOTSIZE)
print PLOTSIZE

plot 'xy.bin' binary array=PLOTSIZExPLOTSIZE with image  # <--- THIS LINE DOES NOT WORK
plot 'xy.bin' binary array=1024x1024 with image          # <--- BUT WITH A FIXED SIZE IT WORKS

But I don't know gnuplot's syntax to use the variable as an actual value for array=. Is there a solution that does not involve making a shell script out of my gnuplot script?
Answer: What I found out so far is, that it works with the old (deprecated) syntax of the plot binary array command:
 plot 'xy.bin' binary array=(PLOTSIZE,PLOTSIZE) with image

But that is not an ideal solution, as this syntax is deprecated. Any other ideas?
Comment: You are wrong, `array=(x,y)` is the recommended syntax, and `array=3x3` is deprecated. Most probably because of exactly the same problem like you have. From the gnuplot docs: `Note:
Gnuplot version 4.2 used the syntax array=128x128 ratherthan array=(128,128). The older syntax is now deprecated, but may still work if your copy of gnuplot was built to support
backwards compatibility.`
Answer: Preferred method (newer syntax)
Use the array=(x,y) syntax, which as you have noted, already works with variables as well as literal values.

Older method
It's certainly not going to win any beauty contests but you could use eval and sprintf like this:
ps = sprintf("%dx%d", PLOTSIZE, PLOTSIZE)
eval "plot 'xy.bin' binary array=" . ps . " with image"

If you haven't used eval before, it evaluates the contents of a string as a command. sprintf is used to produce the string '1024x1024' from the variable PLOTSIZE, which is concatenated into the plot string.
Not ideal but it means that you can avoid using the deprecated syntax.
Comment: A possible candidate for a beauty contests would be `set macros; sprintf('%dx%d', PLOTSIZE, PLOTSIZE); plot 'xy.bin' binary array=@a with image`. But the syntax `(x,y)` is the recommended one, see my comment to the other answer :)
Comment: @Christoph thanks, I've modified my answer so as not to mislead. I haven't used macros before but I guess that you need to assign `@a=sprintf(...)`
Comment: My fault. You must assign `a = sprintf(...`, the `@` is required only as prefix when using the macro.


Adding a directory to an existing .zip file

Question: First of all I would like to say that i've tried looking for the solution to this and I haven't found one where I don't have to unzip, add my folder and then zip again. I am not using any third party libraries. I would like to do this using system.io.compression if it's possible at all ... If not I would use dotnetzip as my last resort.
TL;DR.
I want to be able to add directories with files in them to an already created zip file. Is this possible using the System.Io.Compression library ?
EDIT:
using (FileStream zipToOpen = new FileStream(zipfile, FileMode.Open))
{
    using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
    {
        ZipArchiveEntry readmeEntry = archive.CreateEntry("testFolder/");
    }
}

So, using this code I am able to create a folder inside but it will be without any files in it. My question now is do I have to run this code again to get every file from my source folder to this folder inside the zip or is there a better way?
Comment: To be clear, are you saying you want to add just a folder, and not add any files to it or move files to it? Or are you adding a directory with files in?
Comment: I'm sorry I didn't make it clear but I want to add a directory with files in it. I will edit it right away
Comment: Does [How do I add files to an existing zip archive](http://stackoverflow.com/questions/22339260/how-do-i-add-files-to-an-existing-zip-archive) answer your question?
Comment: I looked at this answer but I didn't know how to modify it to my needs(I tried). I just had an idea of something else I can try using this and I'll get back to you.
Comment: @stuartd I have updated my question with the code I used(which works) for creating a folder inside.
Comment: If you add files that are in the directory to the zip file, then you don't need to add the directory itself. Unzip will create the directories needed to extract the files.
Answer: I managed to find a way to do this thanks to @stuartd. He pointed me to this answer https://stackoverflow.com/a/22339337/3182972  and I found a way to implement it into my code that creates directories with files inside them from a source location of said directories.
Here is the code:
   using (FileStream zipToOpen = new FileStream("c:\MyDestination\test.zip", FileMode.Open))
      {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
          {
             ZipArchiveEntry readmeEntry;
             DirectoryInfo d = new DirectoryInfo(c:\MySourceFolder);
             FileInfo[] Files = d.GetFiles("*");
             foreach (FileInfo file in Files)
             {
               readmeEntry = archive.CreateEntryFromFile("c:\MySourceFolder"+ "\\" + file.Name, "MySourceFolder" + "/" + file.Name);
             }
          }
      }

So what I did was go to my source directory and went through all of the files that are there and with a foreach cycle I added them to the destination folder in the zip file.
You can also get the source directory name with this code:
string sourcepath = "C:\MySourceFolder";
int ind = sourcepath.LastIndexOf("\\") + 1;
string folderName = sourcepath.Substring(ind, folder.Length - ind);

Answer: This code is ready to go in C# 4.5 + with System.IO.Compression  referenced (and having it in using clauses), it is a slight improvement of previous answer in that it encapsules the work in a function.
    public static void AddDirToZip(string source, string targetzip)
    {
        using (FileStream zipToOpen = new FileStream(targetzip, FileMode.Open))
        {
            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
            {
                ZipArchiveEntry readmeEntry;
                DirectoryInfo d = new DirectoryInfo(source);
                FileInfo[] Files = d.GetFiles("*");
                foreach (FileInfo file in Files)
                {
                    readmeEntry = archive.CreateEntryFromFile(file.FullName, d.Name + "/" + file.Name);
                }
            }
        }
    }

Comment: Note that this is not recursive, so it will only add the files, not any subdirectories! - For a nicer and more complete solution see Val's extension class [here](https://stackoverflow.com/questions/15133626/creating-directories-in-a-ziparchive-c-sharp-net-4-5)!!
Answer: This can be performed this way:
var targetDir = @"D:\test";
var zipFile = @"D:\test.zip";
using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Read))
      zipArchive.AddDirectory(targetDir, "test");

public static class ExtensionMethods;
    {

        public static void AddDirectory(this ZipArchive zip, string targetDir, string subDir = null, CompressionLevel compressionLevel = CompressionLevel.Optimal)
        {
            var ogrDir = targetDir.Replace("/", "\\");
            if (!ogrDir.EndsWith("\\"))
                ogrDir = ogrDir + "\\";

            if (subDir == null)
                subDir = "";
            else
            {
                subDir = subDir.Replace("/", "\\");
                if (subDir.StartsWith("\\"))
                    subDir = subDir.Remove(0, 1);

                if (!subDir.EndsWith("\\"))
                    subDir = subDir + "\\";
            }
            Action<string> AddDirectoryAndSubs = null;
            AddDirectoryAndSubs = delegate (string _targetDir)
            {
                string[] files = Directory.GetFiles(_targetDir);
                foreach (string file in files)
                {
                    var fileInfo = new FileInfo(file);
                    zip.CreateEntryFromFile(fileInfo.FullName, subDir + (fileInfo.Directory.ToString() + "\\").Replace(ogrDir, "") + fileInfo.Name, compressionLevel);
                }

                string[] dirs = Directory.GetDirectories(_targetDir);
                foreach (string dir in dirs)
                    AddDirectoryAndSubs(dir);
            };

            AddDirectoryAndSubs(targetDir);
        }

    }

Comment: `AddDirectoryAndSubs` can (in C# 7.0) be written as a *local function* instead of a delegate, which avoids...

_...awkward code, where you first assign null to a delegate variable..._

And it offers other improvements. See: https://stackoverflow.com/a/40949214/2115384


Search and copying nodes from one graph to another in neo4j

Question: Suppose  you have 3 graphs with where some data is shared among the graphs. Is there then a way programatically to do the following:

In graph 1 find a node
Search in graph 2 for that node (through property name)
If step 2 finds a match, then I would like to take all the nodes connected to the found node in graph 2 (including "nodes indirectly connected") and connect them to the node in graph 1.

Essentially I would like to search for a particular node in a graph, find all the nodes directly or indirectly connected to and copy the entire connection to my original node in graph 1.
Any hints on how to do this would be great. Thanks in advance.
Using Neo4j 1.9 and not too familar with Cypher queries and it is the community edition.
Answer: If you have all your 3 graphs in a single database it is simple.
do the query to find your node
START a=node.... MATCH ... WHERE ... RETURN a.prop as prop, ID(a) as id

assuming your nodes are indexed for the properties that are interesting for you, do an index lookup for that property
START a=node({id}), b=node:index(property={prop})
MATCH (b)-->(c)
CREATE (c)-[:REL_TYPE]->(a)

Comment: Does CREATE (c) connect the nodes to your original node? Thanks for the code.


Why is createMessage method on the Session interface in JMS?

Question: Why are the createMessage, createTextMessage etc methods defined on the the Session interface in JMS? I can understand why when you send or received a message you would need the session but not why would you want to create the message you are going to send from it. Why when the designers of JMS were creating the interfaces for it did they decide messages should be created from the session rather than just newed up?
Answer: (Great API design question.)
You are conceptually confusing a "JMS message" with your message content.
Yes. It appears to a bit a conflated to address message life-cycle via the session.  But if you consider the case of a disconnected node, it isn't that strange a design decision.
The salient point is to note "why would a client want to create messages if not connected?" while considering the question of "what is a 'message' if stripped off of JMS metadata"?  (Example of message metadata: message order.)
So, basically, it should be clear that minus the metadata (which is very much bound to both the session and the provider) your 'user content' really has nothing to do with JMS.  In other words, conceptually you have the tuple:
{ [meta-data] : [user-content] }

So a "message" is really the above tuple.  user-content is really just your data.  I.e., if you are provided a generic (non-bound/disconnected) interface to generically "create messages", all that is gained is the (un-necessary) creation of 'generic' 'messages' (which really just wrap your content) and lacks all the necessary 'meta-data' that would make it a proper "JMS Message".  At some point, that generic off-band message needs to be 'converted' to a proper JMS message, e.g. ordering metadata is added, timestamp is added, etc.
What did you gain from having those 'generic' "JMS" messages?  (Nothing, it appears.)
As it is, creating messages from the session is both conceptually clearer and more efficient to implement.
Answer: There is a standard interface for TextMessage and other Messages, but not a standard implementation.  This means you have more than one JMS provider you will have different implementations for these classes.
Comment: Sorry think my question might not of been very clear as this isn't really what I wanted to ask. I've added a bit more to the question to try and make it clearer.
Comment: You can't just "new up" the classes as you don't know what they are.  Only the library know this.
Answer: It's more or less a factory pattern for constructing messages. This allows implementations to decide how a message is constructed, it might need a lot of information from the current session, and allows that information to be pre-populated, and it'll be up to the implementation how to accomplish that. As the docs says:
"Each JMS provider supplies a set of message factories with its Session object for creating instances of messages. This allows a provider to use message implementations tailored to its specific needs."
Answer: Each JMS provider has its own specific implementation, message properties etc. that are initialized  by message factory. So, you need some kind of message factory anyway.
They could probably put factory methods on Connection instead of Session but they decided that it is easier that the same entity  (session in our case) will be responsible on both creating and sending of messages.
I think that these are the main reasons.


How to loop through a taxonomy vocabulary to find the top category in a nested tree?

Question: What I have so far is this
<code>$term=therm_id_that_I_already_have;

$parent = db_result(db_query("SELECT h.parent FROM {term_data} d INNER JOIN {term_hierarchy} h ON d.tid = h.tid WHERE d.tid = $term"));
$term = $parent;

$th=taxonomy_get_term($term);
</code>
probably I need a while of something...
Answer: I would recommend using taxonomy_get_parents_all(). If you have a vocabylary that looks like:

Vocabulary

Child 1 (tid=1)

Child 1.1 (tid=3)

Child 2 (tid=2)

Then you can do:
<code><?php
$parents = taxonomy_get_parents_all(3);
$top_category = array_pop($parents);
</code>
Will give you the term for tid 1.


slidetoggle table row with jQuery

Question: I'm trying to slide toggle between table rows, however this is not working, I have used this same template on a div on a previous project and this has worked. However when I try to apply the same method to a table it doesn't work as expected, it slides up the previous div in my table row. But doesn't show me the next "toggle settings div".
Unfortunately I have to work with the existing code that I have in the format of table rows.
I've broken the code down to show you want I want to be able to do. However I'm not sure if the HTML I've written is even how I should go about this.
My code is below or view my jsFiddle

Office One

Details for Office One

Office Two

Details for Office two

and my jQuery is as follows:
$(document).ready(function() {

   $('.togglesettings').hide();
   $('.togglesettings:first').show();
    $('.showpageblock').on('click', function () {
        $(this).closest('.editblocks').siblings().find('.togglesettings').slideUp();
        $(this).next('.togglesettings').slideToggle();
        $(this).parent().siblings().children().next().slideUp();
        return false;
    });
 });

Answer: First your markup is invalid - you have a tr inside another tr

Office One

Details for Office One

Office Two

Details for Office Two

then
$(document).ready(function () {

    $('.togglesettings').hide();
    $('.togglesettings:first').show();
    $('.showpageblock').on('click', function () {
        var $t = $(this).closest('.editblocks').next().find('.togglesettings').stop(true).slideToggle();
        $('.togglesettings').not($t).stop(true).slideUp();
        return false;
    });

});

Demo: Fiddle
Comment: why does it fail when I insert some inputs? http://jsfiddle.net/gutigrewal/gwLtG/2/
Comment: @gutigrewal again you created a invalid html... div cannot have `td` as a child... http://jsfiddle.net/arunpjohny/gwLtG/3/
Comment: oh ok I see, I guess its better to use nested tables then?

slidetoggle table row with jQuery


Pandas count rows before/after after current row

Question: I need to calculate some measures on a window of my dataframe, with the value of interest in the centre of the window. To be more clear I use an example: if I have a dataset of 10 rows and a window size of 2, when I am in the 5th row I need to compute for example the mean of the values in 3rd, 4th, 5th, 6th and 7th row. When I am in the first row, I will not have the previous rows so I need to use only the following ones (so in the example, to compute the mean of 1st, 2nd and 3rd rows); if there are some rows but not enough, I need to use all the rows that are present (so fpr example if I am in the 2nd row, I will use 1st, 2nd, 3rd and 4th).  How can I do that? As the title of my question suggest, the first idea I had was to count the number of rows preceding and following the current one, but I don't know how to do that. I am not forced to use this method, so if you have any suggestions on a better method feel free to share it.
Answer: What you want is a rolling mean with min_periods=1, center=True:
df = pd.DataFrame({'col': range(10)})
N = 2 # numbers of rows before/after to include

df['rolling_mean'] = df['col'].rolling(2*N+1, min_periods=1, center=True).mean()

output:
   col  rolling_mean
0    0           1.0
1    1           1.5
2    2           2.0
3    3           3.0
4    4           4.0
5    5           5.0
6    6           6.0
7    7           7.0
8    8           7.5
9    9           8.0

Answer: I assume that you have the target_row and window_size numbers as an input.  You are trying to do an operation on a window_size of rows around the target_row in a dataframe df, and I gather from your question that you already know that you can't just grab +/- the window size, because it might exceed the size of the dataframe.  Instead, just quickly define the resulting start and end rows based on the dataframe size, and then pull out the window you want:
start_row = max(target_row - window_size, 0)
end_row = min(target_row + window_size, len(df)-1)
window = df.iloc[start_row:end_row+1,:]

Then you can perform whatever operation you want on the window such as taking an average with window.mean().


Detectar destkop & mobile

Question: tenho uma função JavaScript que redireciona o visitante se ele estiver usando mobile.
Como faço o inverso, quando ele acessar o mobile por URL ex.

mobile.meusite.com

Redirecionar para

meusite.com

Answer: Você precisa colocar um ponto de exclamação (!) no if para inverter a condição, agora verificar quando não é mobile para redirecionar.
Segue o código:

Comment: não funcionou.. coloquei no página do meu 'mobile.meusite.com'
Comment: Testa agora, esqueci de alterar o nome da variável url que eu tinha trocado na declaração de url_mobile por url_desktop e esqueci de trocar na fucntion também
Comment: Uufa, foi está funcionando sim apenas eu que errei onde colocar! Obrigado cara era isso mesmo! espero que ajude mais pessoas!

Detectar destkop & mobile


I want to use Vue Fallthrough attributes, however I do not want them to be placed on the container, only on input inside component

Question: I have a checkbox component and I want to use Fallthrough attributes to provide non declared attributes to the input inside the checkbox component. However, when I place html attributes on the Vue component, the attributes are not only placed on the input in the container, but also on the container element of the checkbox component.
This is my component html
    <template>

        <v-label
          v-if="legend"
          :suffix="legendSuffix"
          :for="$attrs.id || uid"
          :helper="helperText"
        >
          {{ legend }}
        </v-label>

          <input
            :id="$attrs.id || uid"
            ref="checkboxRef"
            type="checkbox"
            v-bind="$attrs"
            v-model="inputVal"
            @input="onInput"
          />

          {{ label }}

    </template>

The common scenario for disabling attribute inheritance is when attributes need to be applied to other elements besides the root node. By setting the > inheritAttrs option to false, you can take full control over where the fallthrough attributes should be applied.
These fallthrough attributes can be accessed directly in template expressions as $attrs:
Fallthrough attributes: {{ $attrs }}

The $attrs object includes all attributes that are not declared by the component's props or emits options (e.g., class, style, v-on listeners, etc.).


Finding a basis for an eigenspace? Where do the additional vectors come from?

Question: I want to diagonalize the following matrix:
$$A =\begin{bmatrix}
    1&0&0&0 \\
    0&0&1&0 \\
    0&1&0&0\\
    0&0&0&1
\end{bmatrix}$$
And I get the following characteristic equation: $(\lambda - 1)^3(\lambda +1)$ and therefore $\lambda=1,-1$
Firstly get the basis vectors for $\lambda = 1$
$$(A - \lambda_2 I_4) =  \begin{bmatrix}
    0&0&0&0 \\
    0&-1&1&0 \\
    0&1&-1&0\\
    0&0&0&0
\end{bmatrix} \rightarrow \text{row reduce} \rightarrow \begin{bmatrix}
    0&1&-1&0 \\
    0&0&0&0 \\
    0&0&0&0\\
    0&0&0&0
\end{bmatrix}$$
So I have $x_2 = x_3$ wich yields the vector:
$$v_1 = \begin{bmatrix}
    0 \\
    1 \\
    1\\
    0
\end{bmatrix}$$
However there should be $3$ basis vectors total for $\lambda = 1$ according to the characteristic equation.
The answer key gives vectors: $$\begin{bmatrix}
    1 \\
    0 \\
    0\\
    0
\end{bmatrix} , \begin{bmatrix}
    0 \\
    0 \\
    0\\
    1
\end{bmatrix}$$
to be the other basis vectors for $\lambda = 1$, but where do these vectors come from in regards to my reduced matrix? I understand there ought to be 2 additional vectors to the one that I found but why are they the vectors given?
Answer: When you find eigenvectors of a matrix $A$ that corresponds to an eigenvalue $\lambda$
$$Av=\lambda v$$
or equivalently
$$\left(A-\lambda I\right)v=0$$
you need to find the basis of the null space of $A-\lambda I$, i.e.
$${\rm null}\left(A-\lambda I\right)=\left\{v|\left(A-\lambda I\right)v=0\right\}$$
You can easily see that in your case $e_{1}=\begin{pmatrix}1\\0\\0\\0\end{pmatrix}$ and $e_{2}=\begin{pmatrix}0\\0\\0\\1\end{pmatrix}$ indeed satisfy this criterion for the matrix $A-I$
$$\left(A-I\right)e_{1,2}=0$$
so these are also eigenvectors with $\lambda=1$.
Answer: You've found a constraint on $x_2$ and $x_3$, but there are no constraints whatsoever on $x_1$ and $x_4$, so all vectors in this eigenspace are of the form $(a,b,b,c)^T$. Can you see where the other two basis vectors came from now?
Comment: You might also want to have a look at [this](https://math.stackexchange.com/a/1521354/265466) for a detailed description of how to read the basis for the null space from a rref matrix.
Answer: I guess you're in math251 since i just finished the same question!
If you examine your matrix, you see that $x_1, x_3$ and $x_4$ are 'free' variables. The number of vectors you're going to end up with are therefore = to the number of free variables. so for $x_1$ you'll have $(1, 0, 0, 0)$, you already found $x_3$ and $x_4$ is $(0, 0, 0, 1)$
Comment: Nope, sounds like a different/class school. I'm guessing this is just one of those practice problems that are used all over.


If X and Y are normal rv's and linearly correlated, what can we say about (X+Y) and (X-Y)?

Question: If $X$ and $Y$ are normally distributed but correlated variables, what can we say about the distributions of $A = X+Y$ and $B = X-Y$?
Are $A$ and $B$ correlated? Can we prove or otherwise with a simple $R$ - script?
Comment: There is no such thing as "linear correlation". What do you mean by that?
Answer:
what can we say about the distributions of $A=X+Y$ and $B=X−Y$?

See the Bivariate case and Affine transformation sections on the Wiki page for the multivariate normal distribution.
Then you will see that
$$\begin{pmatrix}A\\B\end{pmatrix} = F\begin{pmatrix}X\\Y\end{pmatrix}$$
with
$$F=\begin{pmatrix}1 & 1 \\ 1 & -1 \end{pmatrix}$$
which yields a co-variance matrix for $\begin{pmatrix}A\\B\end{pmatrix}$ which is $F\Sigma F^\top$. Thus, the co-variance is $\sigma_X^2 - \sigma_Y^2$.

Are $A$ and $B$ correlated?

It depends as shown above.


How do I can check if a point is in inside a polygon? - I think existing Library have some problem

Question: I have a question
I used two different library
import matplotlib.path as mplPath

point = (0.3, 0.2)
poly = [(0, 0), (0, 1), (1, 0), (1,1)]
polygon = mplPath.Path( np.array(poly) )
print(polygon.contains_point(point))

return:
False
from shapely.geometry import Point, Polygon

point = Point(0.3, 0.2)
polygon = Polygon([(0, 0), (0, 1), (1, 0), (1,1)])
print(polygon.contains(point))
print( point.within(polygon) )

return:
False
False
However, two library all failed to detect (0.3, 0.2) is within the given polygon...
Why..? And, How do I can check weather a point is within more complicate polygon ?
Thank you !
Comment: Maybe you should look more closely at your "polygon". The order you specify the points is important.
Comment: In addition to @BoarGules your polygon isn't closed. [Here's a plot of the polygon and point](https://i.stack.imgur.com/NhdfK.png). You should look at the [path tutorial](https://matplotlib.org/stable/tutorials/advanced/path_tutorial.html)
Comment: @Alex Thank you, but, as I mentioned below, in a complicate case below, how I find whether to contain this point....? point = (144.977, -37.8350) poly = [[144.936868, -37.788838], [144.936665, -37.789517], [144.936607, -37.789511], [144.936551, -37.789616], [144.936633, -37.789625], [144.936439, -37.790276], [144.936387, -37.790453], [144.936223, -37.790436], ....]
Comment: You would do what you are attempting in your post, however I think you need to look at how you are generating your `Path` as these seem to not be what you are expecting.
Comment: @Alex Um.. Do you know how to generate appropriate path for making correct shape?
Should I sort these points above?
Comment: Each point is a vertex on your shape. Each consecutive pair of points is (usually) joined by a straight line. The order they are in is important to get the correct shape, so sorting will not work; this is why your original coords produced an odd result. To generate the appropriate path you need to look at what is producing those points initially as it is likely incorrect.
Answer: Your polygon is invalid because its boundary crosses itself. Even if you filled it in, it would not include the point you've specified (0.3, 0.2).
A polygon is defined by connecting the points you provide in the order you give them, then returning to the first point. So your polygon has these legs:

(0, 0), to (0, 1): straight line up the y axis
(0, 1) to (1, 0): diagonal down to the x axis, one unit out
(1, 0) to (1,1): vertical line to (1, 1)
(1, 1) to (0, 0): diagonal back to the first point, at (0, 0)

A lot of software will treat this as an invalid path, because it crosses itself. Even if it does treat this as a shape, it will be two triangles, with edges along the y axis and along the (0, 1) - (1, 1) path, with points that meet at (0.5, 0.5). Your point (0.3, 0.2) falls in the empty triangle below them (connecting (0, 0) to (0.5, 0.5) to (1, 0)).
Comment: @Alex gave a plot of the shape you defined, at https://i.stack.imgur.com/NhdfK.png . This shape does not contain the point you specified, and it seems like your code is telling you that correctly. Try using `Polygon([(0, 0), (0, 1), (1,1), (1, 0)])` instead and you may get the answer you expected. (Or you may need to add `(0, 0)` to the end of the list; I don't have much experience with these libraries.)
Comment: Thank you for your rapid explanation but, in a complicate case below, how I find whether to contain this point....?

point = (144.977, -37.8350)

poly = [[144.936868, -37.788838], [144.936665, -37.789517], [144.936607, -37.789511], [144.936551, -37.789616],
                [144.936633, -37.789625], [144.936439, -37.790276], [144.936387, -37.790453], [144.936223, -37.790436], ....]
Comment: Should I search appropriate connected lines...?

But, How?
Comment: @Dae-YoungPark The additional `point` you gave is also not in the  `poly` you gave. All the `y` values in `poly` are above -37.8, and `point` has a `y` value below -37.8. When I run `poly.contains(point)`, I get `False`, which is the correct answer.
Comment: @Dae-YoungPark You haven't given a polygon definition that actually includes a point yet, so your code may be working correctly. But if your bigger polygon definition has vertices that are out of sequence like the first example (or don't have any defined sequence), then you might want to create a polygon that is the convex hull of your points, instead of a polygon that uses them directly as vertices?


Copy single bytes of integer value to vector of unsigned chars

Question: I receive an int value foo in a function from which I need to create an std::vector of unsigned char.
The size of the vector must not be larger than needed. That means, only if  foo > 255 the size of the vector may be 2. If foo > 0xFF the size of the vector may be 3 and if foo > 0xFFFFFF the vector has to have a size of 4.
I can't seem to wrap my head around getting the right size of the vector depending on the size of the int foo and then accessing the correct bytes of the int to push_back on the vector.
Any help is appreciated! Thanks!
This is what I have so far:
    size_t foo2= foo;
    size_t bytes = 0;
    while (foo2!= 0)
    {
        foo2/= (1u << CHAR_BIT);
        bytes++;
    }
    std::vector<unsigned char> myVec(bytes);

    for (size_t i = 0; i < bytes; i++)
        myVec[bytes-1-i]=(*((char*)&foo+ i));

Comment: Sometimes, Code examples communicates better...
Comment: Do you have any particular endianness requirement? Starting from the low byte and using `push_back` will, for example, make your vector little-endian.
Answer: Why not do it simple?
size_t foo2 = foo;

std::vector<unsigned char> myVec;
myVec.clear();

//special case if myVec should not be empty for foo = 0
if(foo2 == 0){
    myVec.push_back(0);
}

while(foo2 > 0){
    unsigned char current_part = (unsigned char) (foo2 % 256);
    myVec.push_back(current_part);
    foo2 /= 256;
}

And then maybe reverse, depending on the desired endian. (#include < algorithm >
std::reverse(myVec.begin(), myVec.end());)
(my code assumes that foo >= 0, btw, one might want to catch that or do an assert)
Comment: `foo2 % 255 ... foo2 /= 255` When calculating a decimal representation of a number, do you divide it by 9?
Comment: @n.m. Huh, sometimes I make some stupid mistakes. Thanks, changed that.
Comment: `(unsigned char) foo2` is already range 0-255, it adds nothing to use `% 256`.
Comment: @M.M I'm making mistakes all the day, it seems. Fixed that.


How to re-add a drive when RAID is in degraded mode?

Question: I am running an unmanaged Ubuntu server and due to recent performance issue and sent a request to the provider only to receive the following response:
"Dear Client,
as requested we have checked your drives. Both drives pass a test without any error and do not show any critical value here. We noticed the RAID is degraded state so you will need to re-add the drive to array here:
-----------------%<-----------------
Personalities : [raid1]
md3 : active raid1 sda4[0]
      1839089920 blocks super 1.2 [2/1] [U_]

md2 : active raid1 sda3[0]
      1073610560 blocks super 1.2 [2/1] [U_]

md1 : active raid1 sda2[0]
      523968 blocks super 1.2 [2/1] [U_]

md0 : active raid1 sda1[0]
      16768896 blocks super 1.2 [2/1] [U_]

unused devices: <none>
-----------------%<-----------------"

Google says that U_ indicates a failed drive, which appears to be in contradiction to what the support said. How do I proceed from here?
Something like
mdadm /dev/mdX -r /dev/sdaY
mdadm /dev/mdX -a /dev/sdaY

And if so, what is X and Y for my case?  If more info is needed about my configuration, please let me know.
EDIT, more info below:
root@Ubuntu-1204-precise-64-minimal /home # df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/md2       1008G   26G  931G   3% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
udev             16G  4.0K   16G   1% /dev
tmpfs           3.2G  504K  3.2G   1% /run
none            5.0M     0  5.0M   0% /run/lock
none             16G     0   16G   0% /run/shm
none            100M     0  100M   0% /run/user
/dev/md1        488M   66M  397M  15% /boot
/dev/md3        1.7T   31G  1.6T   2% /home

root@Ubuntu-1204-precise-64-minimal /home # mdadm -D /dev/md0
/dev/md0:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:41 2013
     Raid Level : raid1
     Array Size : 16768896 (15.99 GiB 17.17 GB)
  Used Dev Size : 16768896 (15.99 GiB 17.17 GB)
   Raid Devices : 2
  Total Devices : 1
    Persistence : Superblock is persistent

    Update Time : Wed Dec 21 03:50:13 2016
          State : clean, degraded
 Active Devices : 1
Working Devices : 1
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:0
           UUID : 872ad258:c42ccb36:e9e19c96:98b55ee9
         Events : 816844

    Number   Major   Minor   RaidDevice State
       0       8        1        0      active sync   /dev/sda1
       1       0        0        1      removed

root@Ubuntu-1204-precise-64-minimal /home # mdadm -D /dev/md1
/dev/md1:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:41 2013
     Raid Level : raid1
     Array Size : 523968 (511.77 MiB 536.54 MB)
  Used Dev Size : 523968 (511.77 MiB 536.54 MB)
   Raid Devices : 2
  Total Devices : 1
    Persistence : Superblock is persistent

    Update Time : Wed Dec 21 07:30:55 2016
          State : clean, degraded
 Active Devices : 1
Working Devices : 1
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:1
           UUID : 18cb39fc:9eaea61c:0074a6c2:661b5862
         Events : 387

    Number   Major   Minor   RaidDevice State
       0       8        2        0      active sync   /dev/sda2
       1       0        0        1      removed

root@Ubuntu-1204-precise-64-minimal /home # mdadm -D /dev/md2
/dev/md2:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:42 2013
     Raid Level : raid1
     Array Size : 1073610560 (1023.87 GiB 1099.38 GB)
  Used Dev Size : 1073610560 (1023.87 GiB 1099.38 GB)
   Raid Devices : 2
  Total Devices : 1
    Persistence : Superblock is persistent

    Update Time : Wed Dec 21 07:58:52 2016
          State : active, degraded
 Active Devices : 1
Working Devices : 1
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:2
           UUID : eb9be750:7ff778b4:31fd7ce9:9d86d191
         Events : 38799724

    Number   Major   Minor   RaidDevice State
       0       8        3        0      active sync   /dev/sda3
       1       0        0        1      removed

root@Ubuntu-1204-precise-64-minimal /home # mdadm -D /dev/md3
/dev/md3:
        Version : 1.2
  Creation Time : Wed Nov  6 08:02:42 2013
     Raid Level : raid1
     Array Size : 1839089920 (1753.89 GiB 1883.23 GB)
  Used Dev Size : 1839089920 (1753.89 GiB 1883.23 GB)
   Raid Devices : 2
  Total Devices : 1
    Persistence : Superblock is persistent

    Update Time : Wed Dec 21 07:57:41 2016
          State : clean, degraded
 Active Devices : 1
Working Devices : 1
 Failed Devices : 0
  Spare Devices : 0

           Name : rescue:3
           UUID : c9b748ef:332d3bf9:5fa8fef1:5b433b0a
         Events : 7429895

    Number   Major   Minor   RaidDevice State
       0       8        4        0      active sync   /dev/sda4
       1       0        0        1      removed

Comment: If the controller ejected a drive from the array, even if no hard error is shown I never thrust back a disk. I already seen a drive without error repluged and it corrupted the array data.
Comment: Are you seeking a way to fix that drive problem, or how to deal with the support answer ?
Comment: Please note that I have reverted your spell correction (readd is really readd, or re-add, not read).
Comment: Maybe https://www.howtoforge.com/replacing_hard_disks_in_a_raid1_array ?
Answer: Adding Back a RAID 1 Member
To add a RAID member back into the array, use:
mdadm <RAID Device> -a <Device to add into the array>

For example:
$ mdadm /dev/md0 -a /dev/sdc1
mdadm: re-added /dev/sdc1

If you check again using mdadm --detail , you'll see that /dev/sdc1 is shown as "rebuilding":
Number   Major   Minor   RaidDevice State
   0       8       17        0      active sync   /dev/sdb1
   2       8       33        1      spare rebuilding   /dev/sdc1

This means that the newly added member is being synchronised with the data on the other member; if you now check proc/mdstat, you can see the synchronisation progress - as a percentage and a bar chart:
$ cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid1 sdc1[2] sdb1[0]
      976759936 blocks [2/1] [U_]
      [>....................]  recovery =  1.2% (12409024/976759936) finish=195.2min speed=82312K/sec

unused devices: <none>

Verify that you can still see your files on the RAID drive following the addition of the new RAID member:
$ ls /mnt/raid1
Music  lost+found  Images Films Misc

Comment: Thanks, but this tutorial assumes only one disc has failed, but in my configuration all discs have U_ and none has UU. I edited the post with more info.
Comment: http://aplawrence.com/Linux/rebuildraid.html feels closer to your scenario ?
Comment: If you're running zfs, I really recommend reading http://docs.oracle.com/cd/E19253-01/819-5461/gamno/index.html
Answer: I solved my own issue. I did not understand that mdX are partitions and sda and sdb are actual physical discs. So sdb was missing, so I needed to add it back. I executed the following commands:
sgdisk -R /dev/sdb /dev/sda
sgdisk -G /dev/sdb
mdadm /dev/md0 -a /dev/sdb1
mdadm /dev/md1 -a /dev/sdb2
mdadm /dev/md2 -a /dev/sdb3
mdadm /dev/md3 -a /dev/sdb4

After a day of resync (can be observed with)
cat /proc/mdstat

What I see today looks good again:
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md3 : active raid1 sdb4[2] sda4[0]
      1839089920 blocks super 1.2 [2/2] [UU]

md1 : active raid1 sdb2[2] sda2[0]
      523968 blocks super 1.2 [2/2] [UU]

md2 : active raid1 sdb3[2] sda3[0]
      1073610560 blocks super 1.2 [2/2] [UU]

md0 : active raid1 sdb1[2] sda1[0]
      16768896 blocks super 1.2 [2/2] [UU]

Comment: Congratulations !
Answer: Before adding the drive as suggested by @Tolsadus its a good idea to check your drive health using smartmontools by executing short and long tests:
Initially you have to ensure that the hard disk supports SMART and is enabled:
smartctl -i /dev/sdb
short test:
smartctl -t short /dev/sdb
long test:
smartctl -l selftest /dev/sdb
Comment: I've seen this only now. Can I possibly run these tests AFTER I added sdb? Everything seems fine right now.
Comment: Yes you can this after adding the disk
Comment: I assume this is what their support team did to check the disks in the first place, but I agree that it is a good idea to run the tests again yourself.


jQuery array displaying separation commas

Question: I have the following jQuery array, with the HTML code for multiple images stored in it:
var images = [ "my first image's code, second image's code, etc, etc" ];

I then have them displayed like so:
$('.gallary').prepend(''+images+'');

This works perfectly, except for one thing; the commas (,) which separate the image codes within the array show up on the site between the displayed images. What am I doing wrong here?
Comment: Show your actual code for `images` and what you want exactly.
Comment: do you have a single string in the array as above? Or is it an array of strings?
Answer: If comma is your problem, it is so because when an Array is typecasted to String, Array.join gets called, which joins with default separator, which is a comma ,
So you've to manually add a empty separator, if you don't want them and you can safely remove those extra string quotes.
$('.gallary').prepend(images.join('')); // should remove the ,

Comment: @Joie then please do accept my answer by clicking the tick mark if it helped. Also glad to have helped you :)
Answer: Here are other ways that should work wore efficiently:
ADORABLE DEMO
var images = ["",
              "",
              "",
              ""].join('');
// with jquery
$(images).appendTo('.gallery');

plain js is fast too:
// equiv to `$(images).appendTo(thing);`

document.querySelector('.gallery').innerHTML += images;


Outcome of Function - Python

Question: I'm creating a utility program whose functions will be used as part of another program.
This is my function (EDITED):
def push_up (grid):
   new_grid = up_down_swapper(grid)

   new_grid = zero_DR(new_grid)

   for i in range(4):
     for j in range(3):
        if new_grid[i][j] == new_grid[i][j+1]:
            new_grid[i][j+1] = (new_grid[i][j])+(new_grid[i][j])
            new_grid[i][j] = 0
        else:
            pass

new_grid = zero_DR(new_grid)

grid = up_down_swapper(new_grid)
#print(grid) - shows the grid as the expected outcome. But outside of the function it  doesn't change

and here is how it's used:
push.push_up (grid)

As you guys can see it isn't being assigned to a value like
new_grid = push.push_up (grid)

I cannot change the main program ( this is an assignment and  this is what I've been told to do.)
My problem is how do I get the function to change the value of the parameter? I'm not sure if I'm making sense but something like this:
def square(x):
    x = x*x

value = 3
square(value)
print(value)

This will output 3, but I'm wanting 9. How would I go about doing this?
Here is a pastebin of the main code:
http://pastebin.com/NAxWL14h
Comment: ...you do appear to be modifying `grid` in-place. What exactly is the problem?
Comment: I think this is a scope problem. See related article: http://stackoverflow.com/questions/370357/python-variable-scope-question
Comment: my problem is that "grid" isn't changing outside of the function. I have edited the question to show the new code.
Answer: The short answer is that because of how Python passes parameters, you can't do this. For your square example, there is no way to change the value of value without assigning the result of square(value) to it.
However, you don't need to change what grid is pointing to. In part of your code
for i in range(4): #add numbers that are equal
    for j in range(3,-1,-1):
        if grid[i][j] == grid[i][j-1]:
            grid[i][j-1] = (grid[i][j])+(grid[i][j])
            grid[i][j] = 0
        else:
            pass

You are changing the values held within grid. So think about it this way:
>>> list_to_add_to = []
>>> def add_to_list(a_list):
...     a_list.append('test')
...
>>> print(list_to_add_to)
[]
>>> add_to_list(list_to_add_to)
>>> print(list_to_add_to)
['test']

I did not change what list_to_add_to refers to, but I was still able to modify it. This is referred to as "modifying in-place".
So instead of trying to create a new grid and return that result, you have two options:

Modify the contents of grid
Create a new grid (calling it something else like new_grid) and work with that. Then at the end of your function, copy everything from new_grid into grid.
Comment: I have attempted both options but I'm not getting a change in the "grid" outside of the function. I've shown this in the Original Post
Comment: @Itachi Saying `grid = up_down_swapper(new_grid)` does not copy anything into `grid`. `grid[i][j] = new_grid[i][j]` does.
Answer: There is a difference between

having a name refer to a different value / object and
modifying the object a name refers to.

The first one is done with an assignment:
a = []
b = a
b = [3]
print(a) # still prints []

The second one is only possible with mutable objects (e. g., lists are ok, tuples not):
a = []
b = a
b.append(3)
print(a) # prints [3]

When you do a function call, you essentially do the same:
def f(b):
    b = [3]

only changes what b points to inside the function.
However,
def g(b):
    b.append(3)

changes the list object provided by the caller.
Exactly this is the point: the function in your assignment should modify grid in-place. Instead, you assign it a different object, which won't propagate back to the caller.
Comment: How would I go about modifying grid in-place?
Comment: @Itachi Either by assigning to certain index positions, such as `grid[i][j] = 123`, as you already do, or by e. g. `grid.append(123)` to increase the size. As soon as you do `new_grid = some_operation(grid)`, the connection to the "original one" is lost.

Outcome of Function - Python


Excel formula to calculate the distance between multiple points using lat/lon coordinates

Question: I'm currently drawing up a mock database schema with two tables: Booking and Waypoint.

Booking stores the taxi booking information.

Waypoint stores the pickup and drop off points during the journey, along with the lat lon position. Each sequence is a stop in the journey.

How would I calculate the distance between the different stops in each journey (using the lat/lon data) in Excel?
Is there a way to programmatically define this in Excel, i.e. so that a formula can be placed into the mileage column (Booking table), lookup the matching sequence (via bookingId) for that journey in the Waypoint table and return a result?
Example 1:
A journey with 2 stops:
1   1   1   MK4 4FL, 2, Levens Hall Drive, Westcroft, Milton Keynes 52.002529   -0.797623
2   1   2   MK2 2RD, 55, Westfield Road, Bletchley, Milton Keynes   51.992571   -0.72753

4.1 miles according to Google, entry made in mileage column in Booking table where id = 1
Example 2:
A journey with 3 stops:
6   3   1   MK7 7DT, 2, Spearmint Close, Walnut Tree, Milton Keynes 52.017486   -0.690113
7   3   2   MK18 1JL, H S B C, Market Hill, Buckingham              52.000674   -0.987062
8   3   1   MK17 0FE, 1, Maids Close, Mursley, Milton Keynes        52.040622   -0.759417

27.7 miles according to Google, entry made in mileage column in Booking table where id = 3
Comment: While it is easy to calculate distances over straight lines on a map ("loxodromic distances") and not that difficult over great circles ("orthodromic distances"), calculating reasonably accurate mileages over land requires much more complicated solutions to minimum-length path problems over graphs representing the routes -- which in turn requires good route databases. I'd recommend to use off-the-shelf specialised software for this function, unless you don't really care about accuracy. If that's the case, let me know and I'll find the formulas... I have them somewhere...
Comment: checkout:   http://www.cpearson.com/Excel/latlong.aspx
Comment: @jsalvata Thanks for getting back to me. Accuracy isn't really an issue :)
Comment: Here's a good link: http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates.  One poster makes mention of 'haversine', which is the name of the formula to calculate distances on a sphere.  Google 'haversine excel' and you aught to get some results.
Answer: If you want to find the distance between two points just use this formula and you will get the result in Km, just convert to miles if needed.
Point A: LAT1, LONG1
Point B: LAT2, LONG2
ACOS(COS(RADIANS(90-Lat1)) *COS(RADIANS(90-Lat2)) +SIN(RADIANS(90-Lat1)) *SIN(RADIANS(90-lat2)) *COS(RADIANS(long1-long2)))*6371
Regards
Answer: Until quite recently, accurate maps were constructed by triangulation, which in essence is the application of Pythagoras's Theorem. For the distance between any pair of co-ordinates take the square root of the sum of the square of the difference in x co-ordinates and the square of the difference in y co-ordinates. The x and y co-ordinates must however be in the same units (eg miles) which involves factoring the latitude and longitude values. This can be complicated because the factor for longitude depends upon latitude (walking all round the North Pole is less far than walking around the Equator) but in your case a factor for 52o North should serve. From this the results (which might be checked here) are around 20% different from the examples you give (in the second case, with pairing IDs 6 and 7 and adding that result to the result from pairing IDs 7 and 8).
Answer: Since you say accuracy is not important, and assuming distances are small (say less than 1000 miles) you can use the loxodromic distance.
For this, compute the difference of latitutes (dlat) and difference of longitudes (dlon). If there were any chance (unlikely) that you're crossing meridian 180º, take modulo 360º to ensure the difference of longitudes is between -180º and 180º. Also compute average latitude (alat).
Then compute:
distance= 60*sqrt(dlat^2 + (dlon*cos(alat))^2)

This distance is in nautical miles. Apply conversions as needed.
EXPLANATION: This takes advantage of the fact that one nautical mile is, by definition, always equal to one minute-arc of latitude. The cosine corresponds to the fact that meridians get closer to each other as they approach the poles. The rest is just application of Pythagoras theorem -- which requires that the relevant portion of the globe be flat, which is of course only a good approximation for small distances.
Answer: It all depends on what the distance is and what accuracy you require. Calculations based on "Earth locally flat" model will not provide great results for long distances but for short distance they may be ok. Models assuming Earth is a perfect sphere (e.g. Haversine formula) give better accuracy but they still do not produce geodesic grade results.
See Geodesics on an ellipsoid for more details.
One of the high accuracy (fraction of a mm) solutions is known as Vincenty's formulae. For my Excel VBA implementation look here https://github.com/tdjastrzebski/Vincenty-Excel


Change order (weight) of blocks before page load programatically

Question: Is there a way to change order of blocks before page load (according to current node id for expample)? In hook_preprocess_page or something like that? I don't want to use any modules for this.
Answer: You can use hook_block_list_alter to achieve this. Be aware that the <code>$block->weight</code> attribute won't be affected at this point in the proceedings, but there are solutions in the comments to this problem.
Comment: It means that order of blocks in `hook_block_list_alter(&$blocks)` function can be changed simply by resorting blocks in `&$blocks` array, right? Thx.