text:
Q: How to fix "TypeError: 'dict' object is not callable" in requests My goal for this code is to send an email using Mailgun. I'm using calling it from Flask using the requests library:
contact.py
def index():
  data = request.form.to_dict()
  send_email(data)
  return "Success!"

send_email()
def send_email(data: dict):
  data = format_data(data)

  return requests.post(
    API_URL,
    auth={ "api": API_KEY },
    data=data,
  )

I know it has something to do with the send_email() function but I'm currently stuck at how to solve it.

EDIT: Here's the full traceback:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python3/dist-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "contact.py", line 9, in index
    send_email(data)
  File "/home/david-hermes/Desktop/Projects/frontend/web/single-page-resume/send_email.py", line 44, in send_email
    data=data,
  File "/usr/lib/python3/dist-packages/requests/api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 494, in request
    prep = self.prepare_request(req)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 437, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/lib/python3/dist-packages/requests/models.py", line 309, in prepare
    self.prepare_auth(auth, url)
  File "/usr/lib/python3/dist-packages/requests/models.py", line 540, in prepare_auth
    r = auth(self)
TypeError: 'dict' object is not callable
127.0.0.1 - - [31/Jan/2019 21:01:28] "POST / HTTP/1.1" 500 -

A: You are using the api argument incorrectly. You want to pass in the username and password combination as a tuple:
auth=("api", API_KEY),

The Mailgun API indeed requires you to pass in the API key as a Basic Auth password, but to send a Basic Authentication header using the auth keyword argument you either pass in a HTTPBasicAuth() instance or a tuple:

Making requests with HTTP Basic Auth is very simple:
>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>

In fact, HTTP Basic Auth is so common that Requests provides a handy shorthand for using it:
>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
<Response [200]>

Providing the credentials in a tuple like this is exactly the same as the HTTPBasicAuth example above.


text:
Q: Why can I conclude $A=\overline{A}{}^{\intercal}$ My problem:
Suppose $A \in \mathscr{M}(n,\mathbb{C})$ is such that for all $z \in \mathbb{C}^n-\{0\}$:
$$z^TA \mbox{ }\overline{z} > 0$$
Can I conclude $A=\overline{A}{}^{\intercal}$?
My attempt:
I would like to prove that $A$ necessarly represent an Hermitian product but I am not able to do it.

A: Not necessarily, take:
$$A = \begin{pmatrix}10 & 1 \\ 0 & 10\end{pmatrix}.$$

A: Any matrix $A$ which is $A=B+C$ with $B$ positive-definite hermitian and $C$ skew-hermitian will have the posited property: certainly $z^\top B \overline{z}>0$ (for non-zero $z$), and a direct computation shows that $z^\top C\overline{z}=0$ for all vectors $z$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iphone textfield display cursor i'm developing a calculator for iphone. The design is similar to this:

The problem is that i can't show the cursor in my textField because the input is managed from buttons like the image. Moreover [textField becomeFirstResponder ] doesn't work because it shows the default keyboard.
So i tried to
textResultado.inputView = scrollView;

but then the tabBarController can't receive touch events because my custom keyboard contained  in the scroll view is over it.
The caption is from an app in the AppStore so must be a way in order to solve this problem (show the cursor in a TextField using a different inputView and the tabBar still working fine).
Anyone can help me?

A: Create an input view which is invisible and then make textResultado the first responder.
textResultado.inputView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
[textResultado becomeFirstResponder];

A: I discover that using this solution you can have strange flickering of the gui on iPhone 4 with iOS 6.1.3. iPhone 3Gs with iOS 6.1.3 works correctly.
The flicker appears when text area is selected and a dialog window appears. Closing the dialog window causes flickering.


text:
Q: How can I change the name of another Excel workbook I'm referencing in my code by entering the file name into a cell? Here's what I'm trying to do.
My Excel workbook, InspectionFormTemplate3.4.xlsm, exists as a template to copy over data from various other workbooks that have a totally different format. The code works for copying the data over, but I have 1500 reports to convert and every time I have to manually go into my code and ctrl+f replace all instances it references the report to be converted. Instead, I enter data into a cell (S50) and tried replacing the referenced file name with a variable I named oldfilename. That is what gives me an error, and that's what I'm stuck on.
I've looked around for hours in order to find something that does what I'm trying to do, but I have no real experience with VBA at all. I think this is probably just a simple syntax error.
So, here's what I tried so far with my current code.
Private Sub ConvertButton_Click()

Dim oldfilename As String
oldfilename = Range("S50")

'Name of bldg and date
Workbooks("InspectionFormTemplate2018.3.4.xlsm").Worksheets("COVER PAGE").Range("C9").Value = Workbooks("ReporttoConvert.xls").Worksheets("Cover Page").Range("B5").Value

Obviously here, "ReporttoConvert" is a placeholder for an actual workbook name. It works when I manually insert file names, but I need it to look more like this instead:
Workbooks("oldfilename")

in order for it to change to whatever I input as the file name in cell S50. I'm sure this is probably pretty simple, but I have no clue what this would be called or how to do it.

A: Try this, your macro enabled workbook should be saved in the same folder as the other workbooks, else you will have to change 'ThisWorkbook.path...
Dim OpenWb As String
OpenWb = ThisWorkbook.Worksheets("COVER PAGE").Range("S50").Value

Workbooks.Open Filename:=ThisWorkbook.Path & "\" & OpenWb

ThisWorkbook.Worksheets("COVER PAGE").Range("C9").Value = Workbooks(OpenWb).Worksheets("Cover Page").Range("B5").Value


text:
Q: HTML link of image doesn' work

I have this block of html in my home page. Images show but link does not work. In fact if I remove the style it starts to work. I am very confused.

A: Some element was overlapping your links, just add z-index: 1; in your
 style, jaunt got the answer!

A: Add the class on-top to the images and use the below CSS.
HTML:

CSS:
.on-top {
    position: relative;
    z-index: 1;
}

A: You need to add a z-index to the div that surrounds your links.
Right now
is sitting on top of the div you're having issues with.
Add this to the div that you are having issues with:

A: What is happening is that you have another DIV that happens to be overlapping this
I would change the first line to something like this and it should work

A: Okay so you can either set z-index:1 in the parent div or you can apply
position:absolute;
top:0;
right:0;

and
position:absolute;
top:0;
right:40px;

to the img tags inside the a tags instead of the parent div. I'm sure there are other ways too, but these seems the easiest.


text:
Q: Como ordeno dias de la semana en el index de un dataframe en python? Tengo un problema al leer con pandas un archivo .csv asigno una columna como index pero no puedo ordenarla de Lunes-Domingo, he intentado con librerías de tiempo y cambiar el formato de str a date, pero nada.
import pandas as pd

dataset_vc = pd.read_csv("videoconferencia.csv")
dataset_vc.head()

datavc = dataset_vc.pivot(index='Día', columns='Semana', values='Horas')
datavc

Gracias, y perdón si la forma en que genero la consulta no es la correcta, saludos.

A: Ya que no proporcionas un csv con datos de prueba, crearé uno a base de repetir los mismos números (aleatorios) para tres semanas:
Semana,Día,Horas
Semana 01,Lunes,21983
Semana 01,Martes,38847
Semana 01,Miércoles,457849
Semana 01,Jueves,384245
Semana 01,Viernes,428789
Semana 01,Sábado,8329849
Semana 01,Domingo,446234
Semana 02,Lunes,21983
Semana 02,Martes,38847
Semana 02,Miércoles,457849
Semana 02,Jueves,384245
Semana 02,Viernes,428789
Semana 02,Sábado,8329849
Semana 02,Domingo,446234
Semana 03,Lunes,21983
Semana 03,Martes,38847
Semana 03,Miércoles,457849
Semana 03,Jueves,384245
Semana 03,Viernes,428789
Semana 03,Sábado,8329849
Semana 03,Domingo,446234

El truco es, tras leer este csv, hacer que la columna Día sea de tipo "categorical", en lugar de la cadena que es ahora mismo. El tipo de datos "categorical" permite especificar el orden interno de las categorías, además de ser más eficiente en memoria cuando se tienen unas pocas categorías (7 en este caso, una por día) repetidas muchas veces en una columna.
Se hace así:
df = pd.read_csv("videoconferencia.csv")
dias_ordenados = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"]

df.Día = pd.Categorical(df.Día, dias_ordenados)

Con eso, el resto de tu código ya funciona como querías:
datavc = df.pivot(index='Día', columns='Semana', values='Horas')
datavc


text:
Q: Add Footer with page numbers to itextsharp pdf - RunDateFont? I'm using code provided here How to Add Page number in Footer in PDF by Itextsharp to create a header and footer with page numbering using iTextSharp. Visual Studio is specifically pointing out 'PageEventHelper' does not contain a definition for 'RunDateFont' and no extension method 'RunDateFont' accepting a first argument of type 'PageEventHelper' could be found (are you missing a using directive or an assembly reference?)
What am I missing?
Here is a simplified version of my code:
namespace MyWebApp     {
public partial class _Default : Page
    {

 protected void Button_Click(object sender, EventArgs e)
        {
         using (MemoryStream myMemoryStream = new MemoryStream())
            {
Document document = new iTextSharp.text.Document();
                PdfWriter myPDFWriter = PdfWriter.GetInstance(document, myMemoryStream);
                PageEventHelper pageEventHelper = new PageEventHelper();
                myPDFWriter.PageEvent = pageEventHelper;

                var response = HttpContext.Current.Response;
                response.Clear();
                response.ContentType = "application/pdf";

               // myPDFWriter.PageEvent = new Footer();

                document.Open();

            document.Add(clienttable);
            document.NewPage();//page break OR New Page

            document.Add(new Paragraph("This is a second page."));

            document.Close();

            byte[] content = myMemoryStream.ToArray();

            myPDFWriter.Flush();
            response.OutputStream.Write(myMemoryStream.GetBuffer(), 0, myMemoryStream.GetBuffer().Length);
            response.OutputStream.Flush();
            response.OutputStream.Close();
            response.End();
        }
    }
// some other functions

}

    public class PageEventHelper : PdfPageEventHelper
        {
            PdfContentByte cb;
            PdfTemplate template;

            public override void OnOpenDocument(PdfWriter myPDFWriter, Document document)
            {
                cb = myPDFWriter.DirectContent;
                template = cb.CreateTemplate(50, 50);
            }

            public override void OnEndPage(PdfWriter myPDFWriter, Document document)
            {
                base.OnEndPage(myPDFWriter, document);

                int pageN = myPDFWriter.PageNumber;
                String text = "Page " + pageN.ToString() + " of ";
                float len = this.RunDateFont.BaseFont.GetWidthPoint(text, this.RunDateFont.Size);

                iTextSharp.text.Rectangle pageSize = document.PageSize;

                cb.SetRGBColorFill(100, 100, 100);

                cb.BeginText();
                cb.SetFontAndSize(this.RunDateFont.BaseFont, this.RunDateFont.Size);
                cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin));
                cb.ShowText(text);

                cb.EndText();

                cb.AddTemplate(template, document.LeftMargin + len, pageSize.GetBottom(document.BottomMargin));
            }

            public override void OnCloseDocument(PdfWriter myPDFWriter, Document document)
            {
                base.OnCloseDocument(myPDFWriter, document);

                template.BeginText();
                template.SetFontAndSize(this.RunDateFont.BaseFont, this.RunDateFont.Size);
                template.SetTextMatrix(0, 0);
                template.ShowText("" + (myPDFWriter.PageNumber - 1));
                template.EndText();
            }
    }


text:
Q: Notification in Tizen How can i get the list of notifications occurring on the tizen device in a native c code? I am writing a native c code which will run on the tizen device, and the list of notifications need to be printed continuously in my native application

A: There is a getAll() API if you are writing a webapp.
https://developer.tizen.org/development/articles/how-use-tizen-notification-api
You can refer to the webruntime code to see what it is doing.


text:
Q: how to random placement of UIButton and value i have a question view and will show 4 answers, only 1 are correct.
but i do not want the same button to be always the correct answer.
i will like to know how do i do a random placement of 4 UIButton and value every time.

when user go to this question again the answer will be in differ button

my placement of X,y,W,H
button 1
5,219,230,45
button 2
5,273,230,45
button 3
244,224,230,45
button 4
244,273,230,45

A: I have implemented code for same at my side and it works fine.
-(void)randomAllocation
{
    NSMutableArray* allstring = [[NSMutableArray alloc]initWithObjects:@"Correct",@"Wrong",@"Wrong1",@"Wrong2", nil];

    NSMutableArray* outcomeOFrandom = [[NSMutableArray alloc]init];

    for (int i=0; i<[allstring count]; i++) {
        int temp = 0;

        while (temp==0) {

            int randomInt  =  arc4random()  % 4;

            BOOL result = [outcomeOFrandom containsObject:[allstring objectAtIndex:randomInt]];
            if (result==FALSE ) {

                UIButton* btn = [[UIButton alloc]init];
                [btn setTitle:[allstring objectAtIndex:randomInt] forState:UIControlStateNormal];
                [btn setBackgroundColor:[UIColor blackColor]];

                NSLog(@"tital=%@",[allstring objectAtIndex:randomInt]);

                if (i==0) {
                    [btn setFrame:CGRectMake(5,219,230,45)];
                }
                else if(i==1)
                    [btn setFrame:CGRectMake(5,273,230,45)];
                }
                else if(i==2) {
                    [btn setFrame:CGRectMake(244,224,230,45)];
                }
                else if(i==3) {
                    [btn setFrame:CGRectMake(244,273,230,45)];
                }

                [outcomeOFrandom addObject:[allstring objectAtIndex:randomInt]];
                [self.view addSubview:btn];
                [btn release];

                temp=1;
                break;
            }

        }

    }

}

A: You can create the buttons in same position always and randomize the labels on the button. If you are using an array to provide labels like val1, val2, val3 etc, you can randomize the array.

A: I would suggest do not change the position of buttons rather what you can do is change the currentTitle property of the buttons randomly and once the user clicks the button ; you can get the currentTitle of the button and check if it is the correct answer or not.

A: Out of 4 options only one is correct so why you worry, just give tag to your UIButton. In touchUpInside event or any action you've specified on it. Just match the correct answer tag with user touched button tag.
You should set some logic to set answer with different button tag randomly.

A: You should create button and add them as subView. When you need to put button at random location, you can use:
[button1 setFrame:CGRectMake(5,219,230,45)];
[button2 setFrame:CGRectMake(5,273,230,45)];
[button3 setFrame:CGRectMake(244,224,230,45)];
[button4 setFrame:CGRectMake(244,273,230,45 )];

A: i dont think you need to set your button's x and y here. just set the tag of your buttons, say tag 1 - 4, generate random number 1 - 4 (possible tag of your buttons),  save your buttons to NSArray and do a loop like:
NSArray *buttonsArr = [[NSArray alloc]initWithObjects:button1,button2, button3, button4, nil];
int randomInt = (arc4random() % 4) + 1;
for (int i = 0; i < [buttonsArr count]; i++) {
    if ([(UIButton*)[buttonsArr objectAtIndex:i] tag] == randomInt) {
        [[buttonsArr objectAtIndex:i] setTitle:@"correct" forState:UIControlStateNormal];
    }else{
        [[buttonsArr objectAtIndex:i] setTitle:@"wrong" forState:UIControlStateNormal];
    }
}

A: I happened to be working on a similar game app, so got some code which will definitely help. Check it out below. Note that I've put it in that you'd call a 'correctAnswerMethod' and a 'wrongAnswerMethod' for the correct and incorrect button clicks.
// Define the four buttons in their respective frames, create the first button as the correct one, we'll shuffle it later.
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setTitle:@"Correct Answer" forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(correctAnswerMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];

UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setTitle:@"Wrong Answer 1" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(wrongAnswerMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];

UIButton *button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button3 setTitle:@"Wrong Answer 2" forState:UIControlStateNormal];
[button3 addTarget:self action:@selector(wrongAnswerMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button3];

UIButton *button4 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button4 setTitle:@"Wrong Answer 3" forState:UIControlStateNormal];
[button4 addTarget:self action:@selector(wrongAnswerMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button4];

//Create an array with the rectangles used for the frames
NSMutableArray *indexArray = [NSMutableArray arrayWithObjects:
                              [NSValue valueWithCGRect:CGRectMake(5, 219, 230, 45)],
                              [NSValue valueWithCGRect:CGRectMake(5, 273, 230, 45)],
                              [NSValue valueWithCGRect:CGRectMake(244, 219, 230, 45)],
                              [NSValue valueWithCGRect:CGRectMake(244, 273, 230, 45)], nil];

//Randomize the array
NSUInteger count = [indexArray count];
for (NSUInteger i = 0; i < count; ++i) {
    int nElements = count - i;
    int n = (arc4random() % nElements) + i;
    [indexArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

//Assign the frames
button1.frame = [((NSValue *)[indexArray objectAtIndex:0]) CGRectValue];
button2.frame = [((NSValue *)[indexArray objectAtIndex:1]) CGRectValue];
button3.frame = [((NSValue *)[indexArray objectAtIndex:2]) CGRectValue];
button4.frame = [((NSValue *)[indexArray objectAtIndex:3]) CGRectValue];

A: create your own class with these 4 buttons. In this class you can store the positions of your buttons. then you can add a member function (something like the following) which will draw them:
-(void)drawButtonsWithIncorrectAtIndex:(int)index


text:
Q: How to get a button press to ease in and ease out in CSS3? I'm trying to get my nav-bar header logo to ease in and out on click/release.
Currently, when you click the logo, the image eases correctly but when you release it snaps back and doesn't ease back into the normal size.
What am I doing wrong with the CSS3?

  .navbar-brand {
    height: 40px;
    width: 182px;
    text-indent: 100%;
    overflow: hidden;
    white-space: nowrap;
    background: url('https://www.sketchappsources.com/resources/source-image/twitterlogo_1x.png') no-repeat left center;
    background-size: auto 40px;
    transform: scale(1, 1);
    transition-timing-function: ease-in;
    transition: 0.2s;
  }

    .navbar-brand:active {
      transition-timing-function: ease-out;
      transition: .5s;
      transform: scale(.95, .95);
    }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>
  Navbar

        Home (current)

        Link

        Disabled

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>

A: Use
transition: ease-in-out all .5s
instead of
transition-timing-function and transition
At the moment you are only easing in, not out. You must animate the element in this case, not the :active.
JSfiddle.. https://jsfiddle.net/ataue61h/2/


text:
Q: Save reports according to choice from a sub form I have a main form called (frmcarSearch) that displays table data called (tblCar).
The form contains three drop-down menu (cmbCar, cmbType, cmbGroup) that allow user to filter data and display them in a sub-form called (frmCarSub)
and there are three buttons to save the filtered data btnPrint, btnPDF, btnExcel.
The question is: How to write a code for each button so that the report displays (or save) the data in the sub-form according to the choice from each drop-down menu?

The code for each combo box:
Private Sub cmbCar_AfterUpdate()
    Me.cmbGroup.Value = ""
    Me.cmbType.Value = ""

    Me.frmCarSub.SetFocus
    Me.frmCarSub.Form.Filter = "[CarNum]= '" & [cmbCar] & "'"
    Me.frmCarSub.Form.FilterOn = True
End Sub

Private Sub cmbType_AfterUpdate()
    Me.cmbGroup.Value = ""
    Me.cmbCar.Value = ""

    Me.frmCarSub.SetFocus
    Me.frmCarSub.Form.Filter = "[TypeName]='" & [cmbType] & "'"
    Me.frmCarSub.Form.FilterOn = True
End Sub

Private Sub cmbGroup_AfterUpdate()
    Me.cmbCar.Value = ""
    Me.cmbType.Value = ""

    Me.frmCarSub.SetFocus
    Me.frmCarSub.Form.Filter = "[CarGroupName]= '" & [cmbGroup] & "'"
    Me.frmCarSub.Form.FilterOn = True
End Sub

I used this code for btnPrint button
Private Sub btnPrint_Click()
    If IsNull([cmbCar]) Then
        DoCmd.OpenReport "rptCar", acViewPreview
    Else
        DoCmd.OpenReport "rptCar", acViewPreview, , "[CarNum]='" & [cmbCar] & "'"
    End If
End Sub

But the problem with this code is that I have to use three buttons for the three menus and this is illogical.
Thank you.

A: You could define a function such as the following with the module for your form:
Function FilterString() As String
    If Not IsNull(cmbCar) Then FilterString = " AND [CarNum]= '" & cmbCar & "'"
    If Not IsNull(cmbType) Then FilterString = FilterString & " AND [TypeName]= '" & cmbType & "'"
    If Not IsNull(cmbGroup) Then FilterString = FilterString & " AND [CarGroupName]= '" & cmbGroup & "'"

    FilterString = Mid(FilterString, 6)
End Function

Then, define another function such as:
Function SetFilter()
    Me.frmCarSub.SetFocus
    Me.frmCarSub.Form.Filter = FilterString
    Me.frmCarSub.Form.FilterOn = True
End Function

Then, the event handlers for each of your comboboxes become:
Private Sub cmbCar_AfterUpdate()
    SetFilter
End Sub

Private Sub cmbType_AfterUpdate()
    SetFilter
End Sub

Private Sub cmbGroup_AfterUpdate()
    SetFilter
End Sub

Finally, the Print button event handler can become:
Private Sub btnPrint_Click()
    If FilterString = vbNullString Then
        DoCmd.OpenReport "rptCar", acViewPreview
    Else
        DoCmd.OpenReport "rptCar", acViewPreview, , FilterString
    End If
End Sub

And the user also has the ability to filter by more than one field.


text:
Q: Making a Username and Password with Javascript I've seen other questions similar to this, but I've tried answers and it doesn't appear to do what I want (if it does and I just can't see that it does, please just let me know in the comments. I'm pretty new to this).
I want to password protect a website (this is a personal family website, so I'm not worried about encryption or anything, unless it's super easy to do with javascript) so that only my family can get on. I want the passwords to be personalized.
HTML CODE
<form id="usr-psswd">
  Name: <input type="text" name="name" id="name">
  Username: <input type="text" name="usr" id="usr">
  Password: <input type="text" name="psswd" id="psswd">
  <input type="button" onclick="submission()" value="Submit">
</form>

Script Code
function submission(){
  var name = document.getElementByID = "name";
  var psswd = document.getElementByID = "psswd";
  var usr = document.getElementByID = "usr";

  var name = new Array();
  var usr = new Array();
  var psswd = new Array();
}

My Question: how do I get javascript to put the input into an array that stays on the page so that when you try to get to index.html (which is where the password protection is) so that they don't have to set this up every time?
Also, if it's simple enough, how can I run multiple passwords through encryption and keep it on the webpage so that if someone happens to get on here the passwords are safe?
Yes, I realize that the var name var psswd and var usr are repeated twice. That's because I'm too lazy to name them different things right now. I just need to know how to put var name = document... into var name = new.... Thanks!

A: I know you said that you wanted to do a simple authentication for the site, but doing it in JavaScript is unsafe and the usernames/passwords are easily retrieved.
If you want something very simple and fast to do.. I suggest you do this by using .htaccess for authentication:
To do this, The system requires two files -- the .htaccess file and .htpasswd file:
The .htaccess Code:
AuthType Basic
AuthName "restricted area"
AuthUserFile /home/user/html/protect-me-dir/.htpasswd
require valid-user

The above code protects a directory called protect-me-dir at root level. The AuthUserFile value is always specific to your hosting configuration. If you don't know what the value should be, do a phpinfo() and find the DOCUMENT_ROOT value.

The .htpasswd Code:
your_username:your_password
another_user:another_password
you_get:the_idea

The .htpasswd file contains the usernames and passwords of allowed users. One per line.

Otherwise, I'd probably do something fancier by maybe having a proper login using a combination of PHP and a database for example.
I hope this helps.


text:
Q: how can I disable ubuntu system startup code display? how can I disable ubuntu system startup code display? Like the picture as follows:

A: Open /etc/default/grub
and edit the GRUB_CMDLINE_LINUX_DEFAULT line like the following:
GRUB_CMDLINE_LINUX_DEFAULT="quiet"

Then sudo update-grub for the changes to take effect.


text:
Q: NetBeans Debugger Attach Configurations How can I remove the items in the list of the most recent debugger sessions?  This shows up when you click the drop-down arrow inside the "Debug Project" button.
Where does NetBeans store this information?

A: probably somewhere in ~/.netbeans/nbversion/config/Preferences/


text:
Q: SparkHadoopWriter Failing with NPE at UserProvider I am using Spark to write data to Hbase, I can read data just fine but write is failing with following exception.  I found similar issue that got resolved by adding *site.xml and hbase JARs.  But it is not working for me. I am trying to read data from a table write data to another table.  i can read data just fine but getting exception while writing.
     JavaPairRDD<ImmutableBytesWritable, Put>  tablePuts = hBaseRDD.mapToPair(new PairFunction<Tuple2<ImmutableBytesWritable, Result>, ImmutableBytesWritable, Put>() {
            @Override
            public Tuple2<ImmutableBytesWritable, Put> call(Tuple2<ImmutableBytesWritable, Result> results) throws Exception {
                        byte[] accountId = results._2().getValue(Bytes.toBytes(COLFAMILY), Bytes.toBytes("accountId"));
                        String rowKey = new String(results._2().getRow();
String accountId2 = (Bytes.toString(accountId));
                        String prefix = getMd5Hash(rowKey);
                        String newrowKey = prefix + rowKey;
                        Put put = new Put( Bytes.toBytes(newrowKey) );
                        put.addColumn(Bytes.toBytes("def"), Bytes.toBytes("accountId"), accountId);

                    }
                });
    Job newAPIJobConfiguration = Job.getInstance(conf);
        newAPIJobConfiguration.getConfiguration().set(TableOutputFormat.OUTPUT_TABLE, OUT_TABLE_NAME);
        newAPIJobConfiguration.setOutputFormatClass(org.apache.hadoop.hbase.mapreduce.TableOutputFormat.class);
        newAPIJobConfiguration.setOutputKeyClass(org.apache.hadoop.hbase.io.ImmutableBytesWritable.class);
        newAPIJobConfiguration.setOutputValueClass(org.apache.hadoop.io.Writable.class);
        tablePuts.saveAsNewAPIHadoopDataset(newAPIJobConfiguration.getConfiguration());

Exception in thread "main" java.lang.NullPointerException
        at org.apache.hadoop.hbase.security.UserProvider.instantiate(UserProvider.java:123)
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:214)
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:119)
        at org.apache.hadoop.hbase.mapreduce.TableOutputFormat.checkOutputSpecs(TableOutputFormat.java:177)
        at org.apache.spark.internal.io.HadoopMapReduceWriteConfigUtil.assertConf(SparkHadoopWriter.scala:387)
        at org.apache.spark.internal.io.SparkHadoopWriter$.write(SparkHadoopWriter.scala:71)
        at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply$mcV$sp(PairRDDFunctions.scala:1083)
        at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply(PairRDDFunctions.scala:1081)
        at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply(PairRDDFunctions.scala:1081)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
        at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
        at org.apache.spark.rdd.PairRDDFunctions.saveAsNewAPIHadoopDataset(PairRDDFunctions.scala:1081)
        at org.apache.spark.api.java.JavaPairRDD.saveAsNewAPIHadoopDataset(JavaPairRDD.scala:831)
        at com.voicebase.etl.s3tohbase.HbaseScan2.main(HbaseScan2.java:148)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:879)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:197)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:227)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:136)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)


text:
Q: load data in control select with angular 7 reactive forms I'm doing some tests in Angular 7 I want to load a Select of a form with the data of an array and later obtain its values. This seems to be working worse in console errors I would like to know how to solve them and what they should be. I leave the code of both the template and the component and also leave the errors of the console.
I'm trying not to use the template but the component.
[TEMPLATE][HTML]
https://ibb.co/NKJtjWD
<mat-toolbar color="primary">
  MAPS
</mat-toolbar>

  <mat-card>

Powered by https://www.googlemapsgenerator.com/nl/ & http://lnk.direct/7Lf4

      <form [formGroup]='forma' (ngSubmit)='buscar()' >

          Nombre
          <input
          type="text"
          class="form-control"
          id="nombre"
          aria-describedby="emailHelp"
          placeholder="Enter email"
          formControlName="nombre"
          >

          Select
          <select
          class="form-control"
          formArrayName="selectValues"
          [(ngModel)]="array"
          >
          <option  *ngFor="let i of array; let idx= index" [ngValue]="c" >{{i}}</option>
          </select>

          <button type="submit" class="btn btn-outline btn-primary">Enviar</button>

      </form>

    {{forma.valid}}
  </mat-card>

[COMPONENT]

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'mapas';
  forma: FormGroup;
  array: any[] = ['a','b','c'];

//Para poner mas validaciones se ponen entre [] y no separados por coma ya que el tercer parametro es para validaciones async
  constructor(){
    this.forma = new FormGroup({
      'nombre': new FormControl('Mathias', Validators.required),
      'selectValues': new FormArray([
        new FormControl(this.array)
      ])
    })
  }

  buscar(){
    console.log(this.forma.value);
    console.log(this.forma.value['selectValues'])
    this.forma.reset();
  }
}

and this is chrome console outputs:
AppComponent.html:26 ERROR Error:
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.


text:
Q: Subtracting or Multiplying Fractions $\frac{3}{4}-\frac{1}{2}$ This is the given scenario to help visualize the problem at hand.  A bird feeder is filled with $\frac{3}{4}$ of a full bag of seeds.  The birds ate $\frac{1}{2}$ of what was in the bird feeder.  What fraction of a full bag of bird seed is left in the bird feeder?
The previous scenario involved the same numbers but it asked what fraction of a full bag of bird seed were eaten.  I was able to concluded that $\frac{3}{8}$ of the full bag of seeds was eaten.  You are not able to use the formula: $\frac{3}{4}-\frac{1}{2}$ on this scenario because you are taking fractions of each other, not just the whole bag of seeds.
Does that justification sound correct?  With that justification, how could I solve the question that is asking for the fraction of a full bag of bird seed left in the feeder? Could I use $\frac{3}{4}-\frac{1}{2}$ to answer that? I know that $\frac{3}{4}-\frac{1}{2} = \frac{1}{4}$ but that is not seeming like a correct answer to the scenario. Please help me, I don't completely understand this.

A: Well the important thing, when dealing with fractions of stuff, is not just the fraction itself but what the fraction is of. $\frac{1}{2}$ of the distance to your closest library is far less than $\frac{1}{2}$ of the distance to the moon (I hope).
In this assignment, you've got $\frac{3}{4}$ of a bag of seeds on the feeder, and half of that is eaten. That means the birds eat $\frac{1}{2}$ (a half  $=0.5=50$%) of what's in the feeder, not $\frac{1}{2}$ of the whole bag, hence $\frac{3}{4} \times \frac{1}{2} = \frac{3}{8}$. Simple subtraction won't give the correct result because the two fractions are of different things: $\frac{1}{2}$ is a fraction of the seeds on the feeder while $\frac{3}{4}$ is a fraction of the entire bag of seeds.


text:
Q: An electronic copy of Vishik's work on $p$-adic $L$-functions for modular forms This question is very simple.

Would someone be so nice as to send me an electronic copy of M. M. Vishik, Non-Archimedean measures connected with Dirichlet series, Mat. Sb. (N.S.), 1976, Volume 99(141), Number 2, 248–260?

This is the English translation of the Math Sbornik article in which Vishik constructs $p$-adic $L$-function for finite slope, non-critical eigencsupforms. My e-mail is accessible from my profile.

A: Vishik's article you are asking for can be downloaded for free from Math-Net.Ru
here.


text:
Q: read only list with automatic properties is there a way to do this with automatic properties ?
private IList<string> List;
    public IList<String> list
    {
        get { return List.ToList().AsReadOnly(); }
        set { List = value; }
    }

A: No there is not.  Automatic properties do little more than wrap simple return and assignment statements around a backing field.   The only customization allowed is accessibility.  If you want to do anything other than the most basic property, you'll need to use a full property.

A: try this
private IList List;
    public IList list
    {
        get { return List.ToList().AsReadOnly(); }
        private set { List = value; }
    }


text:
Q: Renaming variables in FriCAS sandbox output I'm playing with FriCAS in sandbox and the problem is,
When asked to find indefinite integral (as well as in many other cases), FriCAS outputs auto-generated variables in a rather unsightly manner, for example,
integrate(x^x, x)

outputs $\int_{}^x\%A^{\%A}\mathbb{d}\%A$ which is quite ugly.
The question is, is there a way to prettify the output? How can I substitute $\%A$ with $t$, for example?

A: Okay, so I contacted the guys at the fricas google group, as IV_ suggested in his comment to the question. Thanks again for pointing me there!
Waldek Hebisch posted the following code that solves my problem:
)expose OutputFormTools

subst_of(f, ls, lf) ==
    symbol?(f) =>
        s := symbol(f)
        k := position(s, ls)
        k > 0 => lf(k)
        f
    atom?(f) => f
    la := arguments(f)
    nla := [subst_of(fi, ls, lf) for fi in la]
    construct(operator(f), nla)$OutputFormTools

It would perform the necessary dummy variable substitution when used like this:
iif := integrate(x^x, x)::OutputForm;
subst_of(iif, [%A], [t])

Which will produce a much cleaner answer, $\int_{}^{x}t^t\mathbb{d}t$, and that was precisely what I was looking for.


text:
Q: Easiest way to deploy ASP web app on ubuntu VPS? I already deployed a web app on MS Azure, it was almost one click installation.
Is there a similar way to deploy ASP .Net web app on DigitalOcean.com Ubuntu VPS without Docker?

A: Actually after few weeks of searching and experimenting, I found that Docker is the easiest way to deploy ASP.Net cross machines and OS. This a github repo I made  for Docker basics:
https://github.com/aladin002dz/docker-basics


text:
Q: Create Android apps in Eclipse sharing common library is it possible to create java libraries the apps can use shared?
It is totally clear to me how to create a library project and how to use it while shared between several another projects, compile each project into different apps.
But in this case the library gets compiled into each app separated.
What I want is to create a library, compile it, install it into the device (or emulator) and several apps calling into this library.
And when it is needed to change something the apps use shard in this library, I just re-work the library, re-compile it, replace it on device (or emulator), and the apps use the new library, all apps use the new functions.
Is it possible?
I googled it, but I couldn't find the solution.
I am using Win + Eclipse, I can't use native code (since I know only Java).
Thanks
UPDATE: Thank you for your suggestions, I know about using Services and Activities started explicitly in order to share functionality.
I asked about libraries because I am investigating the possibilites. If there is no way to use common library, what is the purpose of uses-library...  in the app manifest?
Thank you

A: It's more likely that you need a service as a library. Have you considered this possibility? You can create it as a separate application, define an interface for your service and use it in other apps. So as the interface does not change this will not influence on other apps that depends on this service.

A: The Android model installs each application as a separate user (UID) on the device and the users have no access to other application's/user's files.  Therefore, you can't share libraries as such.
As Yury suggested, you might need a service or an activity that can be invoked from multiple applications.


text:
Q: The gothicized metric and the Palatini formalism In the Palatini formalism of GR, we had two results treating the metric $g_{\mu\nu}$ and the connection $\Gamma^\alpha_{\mu\nu}$ separately as dynamical variables, which are

*

*The vaccum field equations of GR.

And

*

*That the connection is necessarily the metric connection.

The later was obtained from varying the action w.r.t. the symmetric connection and we thus obtain:
$\nabla_\alpha (\sqrt{-g}g^{\mu\nu})=0$ , where we deduced the last result.
Now my question is how to obtain $\nabla_\alpha g_{\mu\nu}=0$ to be able to reach to such a result?
p.s. Ray D'Inverno called the tensor density $\sqrt{-g}g^{\mu\nu}$ a gothicized metric.

A: The main idea answering this question was from this and here I'd like to answer in detail:
We only have this:  $\nabla_\lambda \sqrt{-g} g^{\mu\nu}=0$  ------(1
I will need some formulas which I will deduce firstly.
$\delta^\mu_\nu=g^{\mu\alpha} g_{\alpha \nu} \implies \nabla_\lambda \delta^\mu_\nu=g_{\alpha \nu}\nabla_\lambda g^{\mu\alpha} +g^{\mu\alpha} \nabla_\lambda g_{\alpha \nu}$
$\implies g_{\alpha \nu}\nabla_\lambda g^{\mu\alpha} =-g^{\mu\alpha} \nabla_\lambda g_{\alpha \nu}$
$\implies \nabla_\lambda g^{\mu\beta}=-g^{\mu \alpha} g^{\beta\nu}\nabla_\lambda g_{\alpha \nu}$       -------(2
We take as a priliminary (From the calculus of matrices) $\partial_\lambda \sqrt{-g}=\frac{1}{2}\sqrt{-g}g^{\mu\nu}\partial_\lambda g_{\mu\nu}$------(3
Now the tricks begin:
$\nabla_\lambda \sqrt{-g}=\partial_\lambda \sqrt{-g}- \Gamma^\zeta_{\zeta\lambda} \sqrt{-g}$ $~~~~~~~~~~as$ $\sqrt{-g}$ is a scalar density of weight +1.
$~~~~~~~~~~~~~= \frac{1}{2}\sqrt{-g}g^{\mu\nu}\partial_\lambda g_{\mu\nu}- \Gamma^\zeta_{\zeta\lambda} \sqrt{-g}$ $~~~~~~~~~$Using (3
$~~~~~~~~~~~~=\frac{1}{2}\sqrt{-g}g^{\mu\nu}\partial_\lambda g_{\mu\nu}-\sqrt{-g}g^{\mu\nu} \left(\frac{1}{2}\Gamma^\zeta_{\mu\lambda}g_{\zeta\nu}+\frac{1}{2}\Gamma^\zeta_{\nu\lambda}g_{\mu\zeta}\right)$
$~~~~~~~~~~~~=\frac{1}{2}\sqrt{-g}g^{\mu\nu}\nabla_\lambda g_{\mu\nu}$------(4
Now,
$\nabla_\lambda (\sqrt{-g}g^{\alpha\beta})=\sqrt{-g}\nabla_{\lambda}g^{\alpha\beta}+g^{\alpha\beta}\nabla_\lambda\sqrt{-g}$
Now use (1 and (3 to obtain:
$\nabla_\lambda (\sqrt{-g}g^{\alpha\beta})=-\sqrt{-g}g^{ \alpha\mu} g^{\beta\nu}\nabla_\lambda g_{\mu \nu}+\frac{1}{2}\sqrt{-g}g^{\alpha\beta}g^{\mu\nu}\nabla_\lambda g_{\mu\nu}$
$~~~~~~~~~~~~~~~~~~~~~~~=\sqrt{-g}\left(-g^{ \alpha\mu} g^{\beta\nu}+\frac{1}{2}g^{\alpha\beta}g^{\mu\nu}\right)\nabla_\lambda g_{\mu\nu}$
$~~~~~~~~~~~~~~~~~~~~~~~=0$
Contracting with $g_{\alpha\beta}$ we get
$g^{\mu\nu}\nabla_\lambda g_{\mu\nu}=0$------(5
Now here another trick:
$4 \nabla_\lambda \sqrt{-g}=\nabla_\lambda (g_{\mu\nu}g^{\mu\nu}\sqrt{-g})$
$~~~~~~~~~~~~~~~~=g_{\mu\nu}\nabla_\lambda (g^{\mu\nu}\sqrt{-g}) + \sqrt{-g} (g^{\mu\nu} \nabla_\lambda g_{\mu\nu})$
Now using (1 and (5 we get:
$\nabla_\lambda \sqrt{-g}=0$
And from this using leibniz in (1 we can get easily: $\nabla_\lambda g^{\mu\nu}=0$ and hence using a simple calculation we get $\nabla_\lambda g_{\mu\nu}=0$. And the results of the Palatini formalism then follows easily.


text:
Q: Storyboard: Perform a segue on condition I have this set up in my storyboard:
ViewController
LogInViewController
WebViewController
I have modal segues from VC to LIVC and WVC. In VC's viewDidAppear I run some code to determine if LIVC needs to be displayed, if not then I display WVC. I do this by calling this method:
- (void) pushToMainView : (NSString*) strSegue  {

    if (self.didLoad) {
        [self performSegueWithIdentifier:strSegue sender:self];
    }

}

If the LIVC presented, what I need to happen is, once the login is validated display the WVC. However I get an error:
Attempt to present <WebViewController: 0x7a45ef90> on <ViewController: 0x78694bd0> whose view is not in the window hierarchy!

I'm thinking this is because the current stack order is in VC hierarchy LIVC is next. How would I be able to remove LIVC and bring in WVC.


text:
Q: How can I combine scroll-behavior: smooth with overflow-anchor: auto? I am attempting to combine scroll-behavior: smooth; with the overflow-anchor CSS property to ensure classic 'stay at the bottom' chat app behavior:

*

*New message elements appear at the bottom of the chat area.

*When the chat area isn't scrolled all the way down, existing elements stay on screen (ie, no scrolling happens) when new elements are added

*When the chat area is scrolled all the way down, and new elements are added, the chat area scrolls down.

I have the scrolling behavior working - please run the code snippet below - but the scrolling isn't smooth:

let chatArea = document.querySelector('.chat-area');
let anchor = document.querySelector('.anchor');

// https://ajaydsouza.com/42-phrases-a-lexophile-would-love/
let messages = [
  'I wondered why the baseball was getting bigger. Then it hit me.',
  'Police were called to a day care, where a three-year-old was resisting a rest.',
  'Did you hear about the guy whose whole left side was cut off? He's all right now.'
];

function randomMessage() {
  return messages[(Math.random() * messages.length) | 0];
}

function addMessage() {
  let message = document.createElement('div');
  message.className = 'message';
  message.innerText = randomMessage();
  chatArea.insertBefore(message, anchor);
}
setInterval(addMessage, 1000);
.chat-area {
  scroll-behavior: smooth;
}

.chat-area * {
  overflow-anchor: none;
}

.anchor {
  overflow-anchor: auto;
  height: 1px;
}

.message {
  border: 1px solid black;
  padding: 12px;
  margin: 6px;
  background-color: #ccc;
}

As you can see from running the code snippet above, everything works it's just like scroll-behavior: smooth doesn't seem to be having an effect.
How can I combine scroll-behavior: smooth with overflow-anchor: auto?


text:
Q: auto complete title tags Not sure if this is possible and could just be crazy easter monday boredom! But just thought it could save me some hassle.
Im wondering if when you link some text that text could be duplicated in the title tag, ie:
these are the words

Could jquery do this? Something like look for text in  and duplicate in title?

A: yes, this could be done.
$(function() {
   $("a").each(function(index, element) {
     $(element).attr('title',$(element).text());
   });
});

A: You could loop through all of the links using this code:
 $('a').each(function() {
    var text = $(this).text();
    $(this).attr('title', text );
});

The first part gets the link text and then it makes the title that text.


text:
Q: Reformat data in Excel Anyone know how I can make the unique items in first column as the rows with the EARLY, LATE, ONTIME as the columns? I tried a pivot table but it seems to only be good for summing, counting...etc. I don't need operations done on the values.
Thanks.


text:
Q: Error when including OpenCv framework in a Native Extension for IOS I'm creating an ANE for IOS that implements the OpenCV framework, but when I compile the app on Flash Builder I get this error:
Error occurred while packaging the application:

Undefined symbols for architecture armv7:
  "__ZNKSt3__120__vector_base_commonILb1EE20__throw_length_errorEv", referenced from:
      __ZNSt3__16vectorIN2cv3VecIiLi128EEENS_9allocatorIS3_EEE8__appendEm in opencv2(matrix.o)
      __ZNSt3__16vectorIN2cv3VecIiLi64EEENS_9allocatorIS3_EEE8__appendEm in opencv2(matrix.o)
      __ZNSt3__16vectorIN2cv3VecIiLi32EEENS_9allocatorIS3_EEE8__appendEm in opencv2(matrix.o)
      __ZNSt3__16vectorIN2cv3VecIiLi16EEENS_9allocatorIS3_EEE8__appendEm in opencv2(matrix.o)
      __ZNSt3__16vectorIN2cv3VecIiLi12EEENS_9allocatorIS3_EEE8__appendEm in opencv2(matrix.o)
      __ZNSt3__16vectorIN2cv3VecIiLi9EEENS_9allocatorIS3_EEE8__appendEm in opencv2(matrix.o)
      __ZNSt3__16vectorIN2cv3VecIiLi8EEENS_9allocatorIS3_EEE8__appendEm in opencv2(matrix.o)
      ...
ld: symbol(s) not found for architecture armv7
Compilation failed while executing : ld64

The error occurred after I added this line
<option>-framework opencv2</option>

to the linkerOption on the platformOptions.xml
Any idea?

A: Problem solved.
I've added this line
<option>-lc++</option>

to the platformOptions.xml.
Now OpenCV works great in my actionscript native extension.


text:
Q: Warning: Invalid argument supplied for foreach() when retrieving data from database I am attempting to retrieve data from two tables and echo the results out, the sql appears to be correct but it tells my the argument is invalid.
heres my code:
// Retrieve all information related to this post
    function get_post_data($post_id){

        //test the connection
        try{
            //connect to the database
            $dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
        //if there is an error catch it here
        } catch( PDOException $e ) {
            //display the error
            echo $e->getMessage();
        }

        $sql = 'SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = $post_id';
        $result = $dbh->query( $sql );

        foreach($result as $row):

            echo $row['img_id'];

        endforeach;

    }

A: The $post_id in your query won't be being expanded because the string is single quoted.
It should work better with:
$sql = "SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = $post_id";

or:
$sql = 'SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = '.$post_id;

A: You need to tell PDO to throw errors:
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

That will probably tell you what is happening (except for a potential problem when creating the pdo object the line before it...).
I would also recommend switching to prepared statements to avoid potential sql injection or malformed query problems.
And I hope that is not your real password...


text:
Q: TypeError: The added layer must be an instance of class Layer. Found: Tensor("input_1:0", shape=(None, 64, 64, 3), dtype=float32) -Python I actually try to make a convolutional neural network in order to classify dogs and cat ( i'm newbie in Machine Learning so don't judge me too bad :)  ). I got the exactly the same error from the title of this post. To be honest, i tried to learn myself from Keras API documentation, tried to catch some tips from stackoverflow,github,towardsdatascience and others. Some said that error belongs to different versions of tensorflow and keras libraries,others said that it belongs to syntax. I will leave my code here,tell me where i made mistakes,i'm open to learn new tips.
#IMPORTING LIBRARIES
import tensorflow as tf
import pandas as pd
import keras
from keras.preprocessing.image import ImageDataGenerator

#IMAGE DATA PREPROCESSING

#preprocessing the training set
train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
training_set = train_datagen.flow_from_directory(
        directory = r"C:\Users\Cucu\Downloads\training_set",
        target_size=(64 , 64),
        batch_size=32,
        class_mode='binary')

#preprocessing the test set
test_datagen = ImageDataGenerator(rescale=1./255)
test_set = test_datagen.flow_from_directory(
        directory = r"C:\Users\Cucu\Downloads\test_set",
        target_size=(64 , 64),
        batch_size=32,
        class_mode='binary')

#BULDING THE CNN
#
#
#initialising the cnn
cnn = tf.keras.models.Sequential()

#convolution
cnn.add(tf.keras.layers.Conv2D(filters = 32 , kernel_size = 3 , activation = 'relu' ))
cnn.add(keras.Input(shape=(64, 64, 3)))

#pooling
cnn.add(tf.keras.layers.MaxPool2D( pool_size = 2 , strides = 2))

#adding a SECOND CONVOLUTIONAL LAYER
cnn.add(tf.keras.layers.Conv2D(filters = 32 , kernel_size = 3 , activation = 'relu'))
cnn.add(tf.keras.layers.MaxPool2D( pool_size = 2 , strides = 2))

#flattening
cnn.add(tf.keras.layers.Flatten())

#full connection
cnn.add(tf.keras.layers.Dense(units = 128 , activation = 'relu'))

#adding the output layer
cnn.add(tf.keras.layers.Dense(units = 4 , activation = 'sigmoid'))

and the error(exactly as the title) is:
TypeError: The added layer must be an instance of class Layer. Found: Tensor("input_1:0", shape=(None, 64, 64, 3), dtype=float32)

Massive apreciation to those who can give me some tips. I know this is an extra full beginner level,but you know,sometimes you have to learn along the way of practical experience:)

A: replace :
#convolution
cnn.add(tf.keras.layers.Conv2D(filters = 32 , kernel_size = 3 , activation = 'relu' ))
cnn.add(keras.Input(shape=(64, 64, 3)))

by :
cnn.add(tf.keras.Input(shape=(64, 64, 3)))
cnn.add(tf.keras.layers.Conv2D(filters = 32 , kernel_size = 3 , activation = 'relu' ))

Usually, the Input layer is the first one of your network and you should choose between kerasand tf.keras (the second one preferably)


text:
Q: Get matplotlib automatic y tick values in a list Edit:
I tried the following.
auto_y_ticks=list(axes2.get_yticklabels())

But still the output is not a list of tick values. It shows as Matplotlib text.
The following code produces bar and line plot in the same graph.
In the secondary y axis, the ytick values range from -1 to +1.
My question is, how do I store these values in a list?
from matplotlib import pyplot as plt
import numpy as np

plt.figure()
N = 5
menMeans = (20, 35, 30, 35, 27)
menStd = (2, 3, 4, 1, 2)
width = 0.35       # the width of the bars
womenMeans = (25, 32, 34, 20, 25)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)
plt.ylim(0.0, 65.0)
plt.bar(ind, menMeans, width, color='r', yerr=menStd, label='Men means')
plt.bar(ind+width, womenMeans, width, color='y', yerr=womenStd, label='Women means')
plt.ylabel('Bar plot')

x = np.linspace(0, N)
y = np.sin(x)
axes2 = plt.twinx()
axes2.plot(x, y, color='k', label='Sine')
axes2.set_ylim(-1, 1)
axes2.set_ylabel('Line plot')

plt.show()

auto_y_ticks=list(What's the logic)

A: Starting from your code,
axes2.get_yticks()

gives
array([-1.  , -0.75, -0.5 , -0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ])

Which is what you're after, right?


text:
Q: Can parameters be variable I know that we can use parameters to make generic modules, and to improve readability of code. My question is whether we can have these parameters themselves as a variable. Something like this:
module parameterModule #(parameter p1, ...)(<ports>);
  ...
  ...
endmodule

module changingParameterModule (output [p1_width-1:0] p1);
  ...
  ...
endmodule

Here, I want p1 port of the changingParameterModule to be treated as the parameter p1 for the parameterModule. Is this possible?
I use icarus-verilog and Quartus Prime Lite.

A: No this is not possible; parameters are compile time constants. Module port outputs have the potential to change at any time, and their values don't even get computed until after compilation is over.


text:
Q: capturing response header in Jmeter and use it as variable in another request I want to capture response Header Location : specifically 100 number so i can use it as variable in another request. How can i do this ?
Request
Remote Address: 57.98.32.25:80
Request URL:http://57.98.32.25/new_events
Request Method:POST
Status Code:200 OK
Response Headers
Cache-Control:no-cache
Connection:close
Content-Encoding:gzip
Content-Length:105
Content-Type:text/html;
Date:Thu, 27 Aug 2015 06:37:31 GMT
Location:http://57.98.32.25/new_events/100
Server:Apache/2.2.15

A: You can do it via Regular Expression Extractor configured as follows:

*

*Field to check: Response Headers

*Reference Name: anything meaningful, i.e. location

*Regular Expression: new_events/(\d+)

*Template: $1$

You may also need to switch "Apply to" value to "Main sample and sub-samples" if there are redirects and the Location header is not available in the main sample, use View Results Tree listener to determine it.
Refer extracted value as ${location} or ${__V(location)} where required.


text:
Q: Bootstrap data-toggle breaks ng-show and vice versa I have a form switcher using two radio buttons:
                <form>

                                <input type="radio" name="formSwitcher" id="gNr" ng-model="vm.formSwitcher" value="gNr" /> Form for new G

                                <input type="radio" name="formSwitcher" id="pNr" ng-model="vm.formSwitcher" value="pNr" /> Form for new P

                </form>

   <form> ... </form>

   <form> ... </form>

This is working as expected, I choose a radio button and the appropriate forms show/hide accordingly.
When I add data-toggle="buttons" to the 2nd line above,
, the ng-hide stops working BUT the change in visual state (appearing pressed or unpressed) works fine.

When I remove the data-toggle I don't get the variation in button color to show which of the radios is selected (the radio black dot still appears correctly).
Why would data-toggle="buttons" stop ng-show from working? The customer wants to see the button/radio change color on select.

A: The problem for me was jQuery.

*

*When including bootstrap.min.js it wanted to include jQuery. You can remove bootstrap.min.js & jQuery in which just put an ng-class on the label to set the active state.

Reference Mart's fiddle from above for ng-class examples.

*If removing jQuery is not an option for you:
The other option is in the comments above saying just to remove the data-toggle. From there you can throw a style="display:none" directly on your radio inputs or create a class in your style sheet.

A: You have extra
.
Remove them and it should work like in this fiddle.


text:
Q: Use overload function in httpGet with route attribute I have an api web service,
I want to use overload functions option in c#, I have 2 methods with the same name and the routes get duplicate Route
[Route("getConfigVal")]
    [HttpGet]
    public long getConfigVal(int key, double sResult)
    {
        try
        {
            return _service.getConfigVal(key, ref sResult);
        }
        catch (Exception ex)
        {
            return ex.HResult;
        }

    }

    [Route("getConfigVal")]
    [HttpGet]
    public long getConfigVal( int key, DateTime sResult)
    {
        try
        {
            return _service.getConfigVal(key, ref sResult);
        }
        catch (Exception ex)
        {
            return ex.HResult;
        }

    }


text:
Q: How do I create a custom 404 error page for a missing Amazon S3 Object I am currently using my AWS S3 to store attachments, so I created an s3 bucket for it.  So when I uploaded an attachment and I can view the attachment via the link:
[bucket].s3.amazonaws.com/[object name]
And if I delete that attachment above and then go to the link above, I get the following message:

    NoSuchKey
    The specified key does not exist.
    test/test.jpg
    [some request id]

    [some host id]

So I tried to create an html display "Attachment has been deleted".  So what I tried is make the bucket a static website and set the routing rules to redirect to an html page I place in the bucket if the HttpErrorCodeReturnedEquals is 404.  But that only works if I tried it using this url:
[bucket].s3-website-us-[region].amazonaws.com/[invalid object name]
If I try using the link below, it doesn't work:
[bucket].s3.amazonaws.com/[invalid object name]
Is there any other way I can redirect to an error html page if the object doesn't exist using the link above ([bucket].s3.amazonaws.com/[invalid object name])?
Thanks,
Thomas

A: It is a big but easy process. I can't give you the solution in detail here. But, I can give you a link that will help you. I have done the same thing that is in the link. If you have any doubts just comment here.
Link: http://blog.celingest.com/en/2013/12/12/cloudfront-configuring-custom-error-pages/


text:
Q: When to use stored procedures and triggers vs the applicative layer I have a dilemma, which I hope you will have some expert opinions on.
I have a table called CARDS with a column STATUS. If a record's status changes from 'download' to 'publish', I have to insert the record reference into another table called CARD_ASSIGNMENTS. Additionally, the record needs to be added into CARD_ASSIGNMENTS as many times as there are active records in SCANNERS.
In other words, if there are two active scanners, I will end up with two records in CARD_ASSIGNMENTS as below:
ID   CARD_ID   SCANNER_ID   STATUS_ID
1    1         1            4
2    1         2            4

My dilemma is that I'm not quite sure what would be the most efficient way to execute the above. I've considered the following options:

*

*From PHP - Do one UPDATE query and then the INSERT queries.

*Create a stored procedure, which will take care of updating the CARDS record and adding records into the CARD_ASSIGNMENTS. Then, just call that stored procedure from PHP.

*Create an ON UPDATE trigger for the CARDS table which will take care of processing INSERTS into the CARD_ASSIGNMENTS table.

PS. A simplified version of my database is available on MySQL Fiddle
Thanks,
Kate

A: Interesting question.
I'm going to give you clues about how to approach the problem.
So, you have to start by defining precisely three things:

*

*the expected functionality

*the access policy to the functionality

*the technical upgrade policy

Here I'll detail these points.
So, the first point is that you have to define your functionality. By doing so, you will be able to tell whether adding a card implies always, in all the possible paradigms (sorry for the pedantic word I can't find a more proper one) of your information system, that this card MUST exist in the other table according to the specifications you provided. This 1-1 functional link must be said TRUE or FALSE. This is really important.
Said with other words, if there's at least one possibility that one day you don't want to copy that record to the other table, it means the trigger is a wrong solution, or at least it should be thought with an emergency mode (for example a variable inside that allows it to not get executed in some conditions) setup on.
Then comes the second point, about the access policy. You have to know whether the allowed accessing systems will do so by using your application layer or if they could develop their own (SAAS style). If so, your php layer will be useless and the stored procedure is an excellent option, since every single technical and business layer will go trough it yes or yes.
The last thing to know is whether you're possibly going to upgrade your php layer one day. In most of the cases the answer is yes. If so, you might have to modify the part containing this sql logic you're talking about. Then, having everything into a stored procedure vs storing it hardcoded into the php will definitely save you time, and improve stability.

Left brain right brain, I'm going to tell you my personal opinion afterall. I really love going with stored procedures but not using any triggers. If the environment allows it, I would go for an underlying batch, calling a set of defined stored procedures, concentrating the activity outside of the online scope.
The advantages are the following:

*

*none or less risks of interruption of the online workflow since you reduce the number of operations

*different schedule to alliviate the database load

*more secure policy since executing the stored procedure requires only one grant, while using the same sql with php would require insert/update grants

*better logging quality: you can have a log per job

*better emergency response: when a job fails (if well thought) you can restart it, and that's it.

Long post, but that was interesting and I really wanted to share these ideas.
Cheers!

A: I would use triggers. Some developers say, that if you have too many triggers and stored procedures, the database lives its own life, that means you never know what is going to happen on insert, update etc. But in my opinion, triggers may help you a lot to keep database consistent, so even if someone inserts data directly from some administration tool, the integrity is still kept, because all necessary commands are executed. If you choose stored procedures, you would still have to know, that you need to call this procedure to insert any new data.


text:
Q: What permission is required for a MySQL user to create a database? Is it possible for a user other than root to create a database?
 GRANT SELECT, CREATE ON *.* TO 'myguy'@'thatmachine' IDENTIFIED BY PASSWORD '*12057DFA2BFBD8760D4788735B1C3E26889D7ECE' |
 GRANT ALL PRIVILEGES ON `db1`.* TO 'myguy'@'thatmachine'
 GRANT ALL PRIVILEGES ON `db2`.* TO 'myguy'@'thatmachine'

I wonder what privilege is missing here? Also, why does the first line have a password attached to it?
UPDATE
Let me further clarify what the point of my question is. I have two database machines, source and target. There are many customer databases on the source machine. I need to move those source databases to the other target machine.
The databases are in the form of mysqldump'ed .sql files, which are sftp'd from source to target. Target user, not root, must then recreate the databases locally from each .sql file, perform some actions, then drop the database.
I can't find a way to give these privileges to the target user without giving him global privileges on *.*, which effectively makes that user as dangerous as root.

A: As Izkata and Evan Donovan have mentioned in the comments, the best way to achieve this is to give myguy all privileges on the database myguy_%.
You can do this with the following sql:
grant all privileges on 'myguy_%'.* to myguy@localhost identified by 'password';

This way you don't have to bother with other existing databases, and myguy is able to create new databases to his heart's content.

A: Absolutely you can.
http://dev.mysql.com/doc/refman/5.1/en/privileges-provided.html#priv_create

A: The password field is what that particular user's password is when logging into MySQL itself. I'm not exactly sure what you mean when you say you wonder what privileges are missing. What exactly are you trying to do?


text:
Q: Memory Error with numpy on several large arrays So I am trying to carry out the following calculations on a series of large arrays but I keep getting the error:
MemoryError

In total there are 9 grain_size arrays 2745 by 2654 (Note: I could use just a single float here instead of an array as it is an array of the same number in every cell and this doesn't change), 9 g_pro arrays 2745 by 2654 and the 9 arrays I create below.
So I guess my questions would be is there a way to work around this issue?
# Create empty arrays to store the information
Fs1 = np.zeros_like(g_pro_1, dtype = float)
Fs2 = np.zeros_like(g_pro_1, dtype = float)
Fs3 = np.zeros_like(g_pro_1, dtype = float)
Fs4 = np.zeros_like(g_pro_1, dtype = float)
Fs5 = np.zeros_like(g_pro_1, dtype = float)
Fs6 = np.zeros_like(g_pro_1, dtype = float)
Fs7 = np.zeros_like(g_pro_1, dtype = float)
Fs8 = np.zeros_like(g_pro_1, dtype = float)
Fs9 = np.zeros_like(g_pro_1, dtype = float)

# Check where the condition is true
np.putmask(Fs1, np.logical_and(grain_size_1_array > 0.0000625, grain_size_1_array <= 0.002), g_pro_1)
np.putmask(Fs2, np.logical_and(grain_size_2_array > 0.0000625, grain_size_2_array <= 0.002), g_pro_2)
np.putmask(Fs3, np.logical_and(grain_size_3_array > 0.0000625, grain_size_3_array <= 0.002), g_pro_3)
np.putmask(Fs4, np.logical_and(grain_size_4_array > 0.0000625, grain_size_4_array <= 0.002), g_pro_4)
np.putmask(Fs5, np.logical_and(grain_size_5_array > 0.0000625, grain_size_5_array <= 0.002), g_pro_5)
np.putmask(Fs6, np.logical_and(grain_size_6_array > 0.0000625, grain_size_6_array <= 0.002), g_pro_6)
np.putmask(Fs7, np.logical_and(grain_size_7_array > 0.0000625, grain_size_7_array <= 0.002), g_pro_7)
np.putmask(Fs8, np.logical_and(grain_size_8_array > 0.0000625, grain_size_8_array <= 0.002), g_pro_8)
np.putmask(Fs9, np.logical_and(grain_size_9_array > 0.0000625, grain_size_9_array <= 0.002), g_pro_9)

Fs = Fs1 + Fs2 + Fs3 + Fs4 + Fs5 + Fs6 + Fs7 + Fs8 + Fs9
Fs[self.discharge == -9999] = -9999

The code that worked for me now is:
Fs = np.zeros_like(g_pro_1, dtype = float)

    grain_array_list = [self.grain_size_1, self.grain_size_2, self.grain_size_3,    self.grain_size_4, self.grain_size_5, self.grain_size_6, self.grain_size_7, self.grain_size_8, self.grain_size_9]
    proportions_list = [g_pro_1, g_pro_2, g_pro_3, g_pro_4, g_pro_5, g_pro_6, g_pro_7, g_pro_8, g_pro_9]

    for proportion, grain in izip(proportions_list, grain_array_list):
        if grain > 0.0000625 and grain <= 0.002:
            print grain
            Fs = Fs + proportion

    Fs[self.discharge == -9999] = -9999

A: Your example requires 9*2745*2654*sizeof(float) Bytes, i.e. 500 MiB, to store the grain_size arrays and again as much to store the g_pro arrays. To run the logical_and functions, the parameter arrays with the results of the comparisons must be stored, adding another 100 Mib. Maybe you really simply run out of memory eventually?
You could either try

*

*to increase the physical or swap memory available on your system, or

*to create and process the Fs<n> arrays one after another rather than having each of them in memory at the same time

A: Every time you see lines of code that only differ by a single character, you should be using a loop. In your case, you are holding data that you are not using in memory. Your workflow is basically

*

*get a grain_size_array

*apply a mask to grain_size_array

*add the mask to a placeholder (Fs)

*dispose of the mask and grain_size_array
In terms of code, you need something like:
g_pro_1 = load() # however you get that
Fs = np.zeros_like(g_pro_1, dtype = float)
Fs_tmp = np.zeros_like(g_pro_1, dtype = float)
for i in range(10):
    g_pro = load() # whatever
    grain_size_array = load() # whatever
    np.putmask(Fs_tmp, np.logical_and(grain_size_array > 0.0000625, grain_size_array <= 0.002), g_pro_1)
    Fs += Fs_tmp


text:
Q: How to vectorize a loop through a matrix numpy Suppose I have a matrix that is 100000 x 100
import numpy as np

mat = np.random.randint(2, size=(100000,100))

I wish to go through this matrix, and if each row contains entirely either 1 or 0 I wish to change a state variable to that value. If the state is not changed, I wish to set the entire row the value of state. The initial value of state is 0.
Naively in a for loop this can be done as follows
state = 0

for row in mat:
    if set(row) == {1}:
        state = 1
    elif set(row) == {0}:
        state = 0
    else:
        row[:] = state

However, when the size of the matrix increases this takes an impractical amount of time. Could someone point me in the direction in how to leverage numpy to vectorize this loop and speed it up?
So for a sample input
array([[0, 1, 0],
       [0, 0, 1],
       [1, 1, 1],
       [0, 0, 1],
       [0, 0, 1]])

The expected output in this case would be
array([[0, 0, 0],
       [0, 0, 0],
       [1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

A: Approach #1: NumPy-Vectorized
Here's a vectorized one -
def check_all(a, state): # a is input matrix/array
    # Get zeros and ones all masks
    zm = (a==0).all(1)
    om = (a==1).all(1)

    # "Attach" boundaries with False values at the start of these masks.
    # These will be used to detect rising edges (as indices) on these masks.
    zma = np.r_[False,zm]
    oma = np.r_[False,om]

    omi = np.flatnonzero(oma[:-1] < oma[1:])
    zmi = np.flatnonzero(zma[:-1] < zma[1:])

    # Group the indices and the signatures (values as 1s and -1s)
    ai = np.r_[omi,zmi]
    av = np.r_[np.ones(len(omi),dtype=int),-np.ones(len(zmi),dtype=int)]

    # Sort the grouped-indices, thus we would know the positions
    # of these group starts. Then index into the signatures/values
    # and indices with those, giving us the information on how these signatures
    # occur through the length of the input
    sidx = ai.argsort()
    val,aidx = av[sidx],ai[sidx]

    # The identical consecutive signatures are to be removed
    mask = np.r_[True,val[:-1]!=val[1:]]
    v,i = val[mask],aidx[mask]

    # Also, note that we are assigning all 1s as +1 signature and all 0s as -1
    # So, in case the starting signature is a 0, assign a value of 0
    if v[0]==-1:
        v[0] = 0

    # Initialize 1D o/p array, which stores the signatures as +1s and -1s.
    # The bigger level idea is that performing cumsum at the end would give us the
    # desired 1D output
    out1d = np.zeros(len(a),dtype=a.dtype)

    # Assign the values at i positions
    out1d[i] = v

    # Finally cumsum to get desired output
    out1dc = out1d.cumsum()

    # Correct the starting positions based on starting state value
    out1dc[:i[0]] = state

    # Convert to 2D view for mem. and perf. efficiency
    out = np.broadcast_to(out1dc[:,None],a.shape)
    return out

Approach #2: Numba-based
Here's another numba-based one for memory and hence perf. efficiency -
@njit(parallel=True)
def func1(zm, om, out, start_state, cur_state):
    # This outputs 1D version of required output.

    # Start off with the starting given state
    newval = start_state

    # Loop through zipped zeros-all and ones-all masks and in essence do :
    # Switch between zeros and ones based on whether the other ones
    # are occuring through or not, prior to the current state
    for i,(z,o) in enumerate(zip(zm,om)):
        if z and cur_state:
            cur_state = ~cur_state
            newval = 0
        if o and ~cur_state:
            cur_state = ~cur_state
            newval = 1
        out[i] = newval
    return out

def check_all_numba(a, state):
    # Get zeros and ones all masks
    zm = (a==0).all(1)
    om = (a==1).all(1)

    # Decide the starting state
    cur_state = zm.argmax() < om.argmax()

    # Initialize 1D o/p array with given state values
    out1d = np.full(len(a), fill_value=state)
    func1(zm, om, out1d, state, cur_state)

    # Broadcast into the 2D view for memory and perf. efficiency
    return np.broadcast_to(out1d[:,None],a.shape)

A: You can do this without any loops by leveraging np.accumulate:
R = 5 # 100000
C = 3 # 100

mat   = np.random.randint(2, size=(R,C))
print(mat) # original matrix

state    = np.zeros((1,C))                        # or np.ones((1,C))
mat      = np.concatenate([state,mat])            # insert state row
zRows    = np.isin(np.sum(mat,1),[0,C])           # all zeroes or all ones
iRows    = np.arange(R+1) * zRows.astype(np.int)  # base indexes
mat      = mat[np.maximum.accumulate(iRows)][1:]  # indirection, remove state
print(mat) # modified

#original
[[0 0 1]
 [1 1 1]
 [1 0 1]
 [0 0 0]
 [1 0 1]]

# modified
[[0 0 0]
 [1 1 1]
 [1 1 1]
 [0 0 0]
 [0 0 0]]

The way it works is by preparing an indirection array for rows that need to be changed.  This is done from an np.arange of row indexes in which we set to zero the the indexes that will need replacement.  Accumulating the maximum index will map each replaced row to an all-zero or all-one row before it.
For example:
  [ 0, 1, 2, 3, 4, 5 ] # row indexes
  [ 0, 1, 0, 0, 1, 0 ] # rows that are all zeroes or all ones (zRows)
  [ 0, 1, 0, 0, 4, 0 ] # multiplied (iRows)
  [ 0, 1, 1, 1, 4, 4 ] # np.maximum.accumulate

This gives us a list of indexes where row content should be taken from.
The state is represented by an extra row inserted at the beginning of the matrix before performing the operation and removed afterward.
This solution will be marginally slower for very small matrices (5x3) but it can give you a 20x speed boost for larger ones (100000x100: 0.7 second vs 14 seconds).

A: Here is a simple and fast numpy method:
import numpy as np

def pp():
    m,n = a.shape
    A = a.sum(axis=1)
    A = np.where((A==0)|(A==n))[0]
    if not A.size:
        return np.ones_like(a) if state else np.zeros_like(a)
    st = np.concatenate([np.arange(A[0]!=0), A, [m]])
    v = a[st[:-1],0]
    if A[0]:
        v[0] = state
    return np.broadcast_to(v.repeat(st[1:]-st[:-1])[:,None],(m,n))

I made some timings using this
state=0
a = (np.random.random((100000,100))<np.random.random((100000,1))).astype(int)

simple test case:
0.8655898020006134   # me
4.089095343002555    # Alain T.
2.2958932030014694   # Divakar 1
2.2178015549980046   # & 2


text:
Q: Galois group of the polynomial $f(X)=(X^4+1)(X^4-2)$ Here is my attempt:
Let $\alpha=e^{i\frac{\pi}{4}}$ and $\beta=\sqrt[4]{2}$ two roots of the polynomial. Then, the other ones are given by $\alpha\omega$, $\alpha\omega^2$, $\alpha\omega^3$ $\beta\omega$, $\beta\omega^2$ and $\beta\omega^3$, where $\omega=e^{i\frac{\pi}{2}}$. Hence, the splitting field of $f$ is $K_f=\mathbb{Q}(\alpha,\beta,\omega)$. The minimal polynomial of $\alpha$, $\beta$ and $\omega$ are $p_\alpha(X)=X^4+1$, $p_\beta(X)=X^4-2$ and $p_\omega(X)=X^2+1$, so the Galois group has order 32.
However, the solution given to this exercise says that the Galois group is $\mathcal{D}_4$. Can someone tell me where my mistake is?
Thanks in advance.

A: $\omega = \alpha^2$, so $K_f = \mathbb{Q}(\alpha, \beta)$. Also be careful:
$$\deg(\mathbb{Q}(\alpha, \beta, \omega) : \mathbb{Q}) \neq \deg(\mathbb{Q}(\alpha) : \mathbb{Q}) \deg(\mathbb{Q}(\beta) : \mathbb{Q}) \deg(\mathbb{Q}(\omega) : \mathbb{Q}).$$
You have to compute this adding one element at a time:
$$\deg(\mathbb{Q}(\alpha, \beta, \omega) : \mathbb{Q}) = \deg(\mathbb{Q}(\alpha,\beta,\omega) : \mathbb{Q}(\beta,\omega)) \deg(\mathbb{Q}(\beta,\omega) : \mathbb{Q}(\omega)) \deg(\mathbb{Q}(\omega) : \mathbb{Q}).$$
So for instance
$$\deg(\mathbb{Q}(\alpha,\beta,\omega) : \mathbb{Q}(\beta,\omega)) = 2$$
since $\alpha$ is a root of $X^2 - \beta \in \mathbb{Q}(\beta,\omega)[X]$.

A: The roots of $x^4-2$ are $\sqrt[4]{2}, i \sqrt[4]{2}, - \sqrt[4]{2}, -i \sqrt[4]{2}$. Thus, the splitting field of $x^4-2$ already contains $i$. Therefore, adding $\sqrt{i}$ makes $x^4+1$ split as well.


text:
Q: How to serialize Observables to the cloud and back I need to split processing sequence (like in this question How to organize sequence of data processors with .net RX) into several computation units in Azure environment.
The idea is to serialize Observable sequence to Azure Queues(or Service Bus) and to deserialize it back.
If producer or consumer is failed other party should be able to continue producing/consuming.
Could anyone suggest an elegant way to do so and what to use (Azure Queues or Service Bus)?
Has anyone used TCP Observable provider - http://rxx.codeplex.com/wikipage?title=TCP%20Qbservable%20Provider for such problems is it safe to the failures of one of the parties?

A: Imagine you have a messaage queue with the following API
class MQ {

    public MQ();

    // send a single message from your message queue
    public void send(string keyPath, string msg);

    // Receive a single message from your message queue
    public async Task<string> receive(keyPath);

}

To make this RX compatible
class MQRX: IObserver<string> {
    MQ _mq;
    string _keyPath

    MQRX(string keyPath){
        _mq = mq;
        _keyPath = keyPath;
    }

    IObservable<string> Observe(){
        return Observable.Defer(()=> mq.receive(keyPath).ToObservable() ).Repeat();
    }

    void OnNext(string msg){
        _mq.send(msg);
    }

    void OnError(Exception e){
        // The message queue might not
        // support serializing exceptions
        // or it might or you might build
        // a protocol for it.
    }
}

To use it in a fault tolerant way. Note Retry will resubscribe if there is an exception
thrown upstream delivered by OnError
new MQRX("users/1/article/2").
    Retry().
    Subscribe((msg)=>Console.Writeln(msg));

On the writing side for example you could send a message every two seconds and retry
the subscription to the generator if there is an error. Note there is unlikely to be
an error in Observable.Interval that just generates a message every time interval but
imagine reading from a file or some other message queue.
var mq = new MQRX("users/1/article/2");

Observable.Interval(TimeSpan.FromSeconds(2)).
    Select((x)=>x.ToString()).

Note you probably should use the IObservable Catch extension method rather than
blindly retrying as you might get the same error over and over again.
        Retry().
        Subscribe(mq);

A: I wrote my own UDP to RX wrapper in 30 lines of VB code and it handles timeouts. TCP wrappers would be similar I guess.
Imports System.Reactive
Imports System.Reactive.Linq
Imports System.Reactive.Threading.Tasks
Imports System.Threading
Imports System.Net
Imports System.Net.Sockets

Public Module UDP
    ''' <summary>
    ''' Generates an IObservable as a UDP stream on the IP endpoint with an optional
    ''' timeout value between results.
    ''' </summary>
    ''' <param name="timeout"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function StreamObserver(
                localPort As Integer,
                Optional timeout As Nullable(Of TimeSpan) = Nothing
                ) As IObservable(Of UdpReceiveResult)

        Return Linq.Observable.Using(Of UdpReceiveResult, UdpClient)(
            Function() New UdpClient(localPort),
            Function(udpClient)
                Dim o = Observable.Defer(Function() udpClient.
                                                                ReceiveAsync().
                                                                ToObservable())
                If Not timeout Is Nothing Then
                    Return Observable.Timeout(o.Repeat(), timeout.Value)
                Else
                    Return o.Repeat()
                End If
            End Function
        )
    End Function
End Module

You could do the same for the write side if you needed. Then you just use normal RX techniques for
serializing your data into UDP frames.
new UDP.StreamObserver(8080, TimeSpan.FromSeconds(2)).
        Select( function(udpResult) MyDeserializeFunction(udpResult)).
        Subscribe( sub (result) DoSomething(result),
                   sub(error) DoSomethingWithError )


text:
Q: Configuring jmx_exporter with tomcat I am trying to expose some of my spring application metrics (Spring). The metrics are mainly database connection metrics. To do so, I started by configuring a hikari connection pool, then I used jmx. To export the metrics to prometheus then visiualize them with Grafana, I tried to used jmx_prometheus_exporter [https://github.com/prometheus/jmx_exporter][1]
I downlaoded the jmx_exporter jar and then I added this line in my Tomcat8 service (in the folder init.d)

export JAVA_OPTS="$JAVA_OPTS
  -javaagent:/home/monitoring/jmx_prometheus_javaagent-0.3.0.jar=9095:/home/monitoring/config-jmx-tomcat.yaml"

This the config file file for tomcat (config-jmx-tomcat.yaml)
lowercaseOutputLabelNames: true lowercaseOutputName: true rules:
- pattern: 'Catalina<type=GlobalRequestProcessor, name=\"(\w+-\w+)-(\d+)\"><>(\w+):'   name: tomcat_$3_total   labels:
    port: "$2"
    protocol: "$1"   help: Tomcat global $3   type: COUNTER
- pattern: 'Catalina<j2eeType=Servlet, WebModule=//([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), name=([-a-zA-Z0-9+/$%~_-|!.]*), J2EEApplication=none, J2EEServer=none><>(requestCount|maxTime|processingTime|errorCount):'   name: tomcat_servlet_$3_total   labels:
    module: "$1"
    servlet: "$2"   help: Tomcat servlet $3 total   type: COUNTER
- pattern: 'Catalina<type=ThreadPool, name="(\w+-\w+)-(\d+)"><>(currentThreadCount|currentThreadsBusy|keepAliveCount|pollerThreadCount|connectionCount):' name: tomcat_threadpool_$3   labels:
    port: "$2"
    protocol: "$1"   help: Tomcat threadpool $3   type: GAUGE
- pattern: 'Catalina<type=Manager, host=([-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]), context=([-a-zA-Z0-9+/$%~_-|!.]*)><>(processingTime|sessionCounter|rejectedSessions|expiredSessions):' name: tomcat_session_$3_total   labels:
    context: "$2"
    host: "$1"   help: Tomcat session $3 total   type: COUNTER

In my application This is how I define the connection pool and MbeanServer....
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (foo)");
HikariPoolMXBean poolProxy = JMX.newMXBeanProxy(mBeanServer, poolName, HikariPoolMXBean.class);
int idleConnections = poolProxy.getIdleConnections();

When I try to acceed to localhost:9095/metrics, I find nothing, and the catalina logs, tomcat logs, show nothing.
My questions are:

*

*Are the steps that I am following are correct or not?

*How can I debug or where should I see the errors?

*I keep finding tutorials showing conifgs with jmx remote . When to use this ?
thank you in advance for your response.


text:
Q: Meteor loginWithFacebook permissions not being asked I am using Meteor.loginWithFacebook:
 Meteor.loginWithFacebook({
      // https://developers.facebook.com/docs/reference/fql/permissions/
      requestPermissions: ['read_friendlists','user_about_me','user_birthday',
      'user_education_history', 'user_friends', 'user_likes', 'user_photos',
      'user_religion_politics', 'user_work_history'],
      loginStyle: "popup"
    }, function (err,res) {
      if(err)  alert(err)
      else console.log(res)
    });

But when my actual login box pops up, thought the user is logged in and I get access to all their publicly availabe information, it doesn't actually request any of the specified permissions (and I therefore don't have access to them). Is there something in my code I need to change in order to have the permissions actually be requested?

A: @kittyminky you right
the solution is
Accounts.ui.config({ requestPermissions: { facebook: [the_permissons_you_want] } });

A: on my case using Accounts.ui.config yields an error since i only have Accounts defined, Accounts.ui isn't defined for me.
Perhaps because i didn't add that package, but must be a way without using the .ui ?