text:
Q: How can I create a popup google form in google sheets? I am looking to create a popup google form that appears when you press a menu item in the sheet. I can get it to show but I can't answer the questions.
Here is my current code:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menubuttons1 = [ {name: "Input", functionName: "ask"} ];
ss.addMenu("Sales", menubuttons1);
}

function ask() {
var form = FormApp.openById("1LdHO6bazGUsrmanRUbUwj28-gTiv2pJwUEfj8NzinjA"),
    formUrl = form.getPublishedUrl(),
    response = UrlFetchApp.fetch(formUrl),
    formHtml = response.getContentText(),
    htmlApp = HtmlService
  .createHtmlOutput(formHtml)
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setTitle('Sales Input')
  .setWidth(450)
  .setHeight(500);  SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
}

And here is the google sheet and form:
Sheet: https://docs.google.com/spreadsheets/d/1aGkZjDgMkRrFiPqCy5zy-bORGxuPKnSgYzP0vhy4bso/edit#gid=0
Form: https://docs.google.com/forms/d/1LdHO6bazGUsrmanRUbUwj28-gTiv2pJwUEfj8NzinjA/edit

A: In your situation, how about the following modification?
Modified script:
In this modification, I modified the function ask.
function ask() {
  var form = FormApp.openById('1LdHO6bazGUsrmanRUbUwj28-gTiv2pJwUEfj8NzinjA');
  var formUrl = form.getPublishedUrl();
  var formHtml = `<iframe id="inlineFrameExample" src="${formUrl}" style="border:none; width:400px; height:400px;"></iframe>`;
  var htmlApp = HtmlService
    .createHtmlOutput(formHtml)
    .setSandboxMode(HtmlService.SandboxMode.IFRAME)
    .setTitle('Sales Input')
    .setWidth(420)
    .setHeight(420);
  SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
}


text:
Q: Two domains in one DNS zone file I manage an authoritative DNS server for my organizations DNS.
We recently purchased additional domain names which end in a different domain than the one my organization has.
For example, my organizations domain is AAA.GOV.CA (www.aaa.gov.ca, ftp.aaa.gov.ca and so on)
Due to management issues, we were required to purchase domain names that end in .COM such as mike.com, david.com etc.
I need to point all the new domain names to my main web server, which I will do using the CNAME, so
mike.com  IN CNAME www.aaa.gov.ca
david.com IN CNAME www.aaa.gov.ca

And so on.
Can I add these domain names to my authoritative named file for my AAA.GOV.CA or do I have to create another zone for .COM and define them in there ?
I searched the previous questions, but didn't find anything which is similar to mine.
We are running BIND version 9.

A: While it isn't possible to mix domains within the same zone file, it is certainly possible to use a single zone file for multiple domains, if all those domains share the same DNS entries.
For example:
@     IN   A   10.10.0.5
www   IN   A   10.10.0.5
ns    IN   A   10.10.0.2
ftp   IN   A   10.10.0.8

Using that (partial) zone file for all your domains would result in:
AAA.GOV.CA has the same IP as MIKE.COM and DAVID.COM
NS.AAA.GOV.CA is the same as NS.MIKE.COM and NS.DAVID.COM
FTP.AAA.GOV.CA is the same as FTP.MIKE.COM and FTP.DAVID.COM
WWW.AAA.GOV.CA is the same as WWW.MIKE.COM and WWW.DAVID.COM
...etc...
If that is not an acceptable setup, then you will need to create a separate zone file.  From what you describe, it sounds like two zone files would suffice:

*

*one zone file for AAA.GOV.CA with full entries, and real A records

*one zone file that is used by both MIKE.COM and DAVID.COM that contains CNAME references into the AAA.GOV.CA zone

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proxy server in C - Multiple I have a proxy server code written in C. The program accepts arguments, eg google.com 9000 80
And then in your browser as you enter localhost: 9000 get google.com page. But I'd like to be able to create several tunnels at once but I do not know how to do it, because in the main function is infinite loop on of which is the basis of the work program.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <string.h>
#include <signal.h>
#include <assert.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/ftp.h>
#include <arpa/inet.h>
#include <arpa/telnet.h>
#define BUF_SIZE 4096

extern int sys_nerr, errno;

    char client_hostname[64];

    void set_nonblock(int fd)
    {
        int fl;
        int x;
        x = fcntl(fd, F_GETFL, &fl);
        if (x < 0) {
        exit(1);
        }
        fl |= O_NONBLOCK;
        x = fcntl(fd, F_SETFL, &fl);
        if (x < 0) {
        exit(1);
        }
    }

    int serwer_gniazdo(char *addr, int port)
    {
        int addrlen, s, on = 1, x;
        static struct sockaddr_in client_addr;

        s = socket(AF_INET, SOCK_STREAM, 0);
        if (s < 0)
        perror("socket"), exit(1);

        addrlen = sizeof(client_addr);
        memset(&client_addr, '\0', addrlen);
        client_addr.sin_family = AF_INET;
        client_addr.sin_addr.s_addr = inet_addr(addr);
        client_addr.sin_port = htons(port);
        setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, 4);
        x = bind(s, (struct sockaddr *) &client_addr, addrlen);
        if (x < 0)
        perror("bind"), exit(1);

        x = listen(s, 5);
        if (x < 0)
        perror("listen"), exit(1);

        return s;
    }

    int otworz_host(char *host, int port)
    {
        struct sockaddr_in rem_addr;
        int len, s, x;
        struct hostent *H;
        int on = 1;

        H = gethostbyname(host);
        if (!H)
        return (-2);

        len = sizeof(rem_addr);

        s = socket(AF_INET, SOCK_STREAM, 0);
        if (s < 0)
        return s;

        setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, 4);

        len = sizeof(rem_addr);
        memset(&rem_addr, '\0', len);
        rem_addr.sin_family = AF_INET;
        memcpy(&rem_addr.sin_addr, H->h_addr, H->h_length);
        rem_addr.sin_port = htons(port);
        x = connect(s, (struct sockaddr *) &rem_addr, len);
        if (x < 0) {
        close(s);
        return x;
        }
        set_nonblock(s);
        return s;
    }

    int sock_addr_info(struct sockaddr_in addr, int len, char *fqdn)
    {
        struct hostent *hostinfo;

        hostinfo = gethostbyaddr((char *) &addr.sin_addr.s_addr, len, AF_INET);
        if (!hostinfo) {
        sprintf(fqdn, "%s", inet_ntoa(addr.sin_addr));
        return 0;
        }
        if (hostinfo && fqdn)
        sprintf(fqdn, "%s [%s]", hostinfo->h_name, inet_ntoa(addr.sin_addr));
        return 0;
    }

    int czekaj_na_polaczenie(int s)
    {
       int newsock;
    static struct sockaddr_in peer;
    socklen_t len;
    len = sizeof(struct sockaddr);
    newsock = accept(s, (struct sockaddr *) &peer, &len);
        if (newsock < 0) {
        if (errno != EINTR)
            perror("accept");
        }
        sock_addr_info(peer, len, client_hostname);
        set_nonblock(newsock);
        return (newsock);
    }

    int zapis(int fd, char *buf, int *len)
    {
        int x = write(fd, buf, *len);
        if (x < 0)
            return x;
        if (x == 0)
            return x;
        if (x != *len)
            memmove(buf, buf+x, (*len)-x);
        *len -= x;
        return x;
    }

    void klient(int cfd, int sfd)
    {
        int maxfd;
        char *sbuf;
        char *cbuf;
        int x, n;
        int cbo = 0;
        int sbo = 0;
        fd_set R;

        sbuf = (char *)malloc(BUF_SIZE);
        cbuf = (char *)malloc(BUF_SIZE);
        maxfd = cfd > sfd ? cfd : sfd;
        maxfd++;

       while (1)
       {
        struct timeval to;
        if (cbo)
            {
            if (zapis(sfd, cbuf, &cbo) < 0 && errno != EWOULDBLOCK) {
                    exit(1);
            }
        }
        if (sbo) {
            if (zapis(cfd, sbuf, &sbo) < 0 && errno != EWOULDBLOCK) {
                    exit(1);
            }
        }

        FD_ZERO(&R);
        if (cbo < BUF_SIZE)
            FD_SET(cfd, &R);
        if (sbo < BUF_SIZE)
            FD_SET(sfd, &R);

        to.tv_sec = 0;
        to.tv_usec = 1000;
        x = select(maxfd+1, &R, 0, 0, &to);
        if (x > 0) {
            if (FD_ISSET(cfd, &R)) {
            n = read(cfd, cbuf+cbo, BUF_SIZE-cbo);
            if (n > 0) {
                cbo += n;
            } else {
                close(cfd);
                close(sfd);
                _exit(0);
            }
            }
            if (FD_ISSET(sfd, &R)) {
            n = read(sfd, sbuf+sbo, BUF_SIZE-sbo);
            if (n > 0) {
                sbo += n;
            } else {
                close(sfd);
                close(cfd);
                _exit(0);
            }
            }
        } else if (x < 0 && errno != EINTR) {
            close(sfd);
            close(cfd);
            _exit(0);
        }
        }
    }

    int main(int argc, char *argv[])
    {
        char *localaddr = (char *)"127.0.0.1";
        int localport = atoi(argv[1]);
        char *remoteaddr = (char *)(argv[2]);
        int remoteport = atoi(argv[3]);
        int client, server;
        int master_sock;

        if (4 != argc)
        {
            fprintf(stderr, "usage: %s port host port\n", argv[0]);
            exit(1);
        }

        assert(localaddr);
        assert(localport > 0);
        assert(remoteaddr);
        assert(remoteport > 0);

        master_sock = serwer_gniazdo(localaddr, localport);

        for (;;)
        {
            if ((client = czekaj_na_polaczenie(master_sock)) < 0)
                continue;
            if ((server = otworz_host(remoteaddr, remoteport)) < 0)
                continue;
            if (!fork()) {
                klient(client, server);
            }

            close(client);
            close(server);
        }

        printf("Koniec programu");

        return 0;
    }

A: The answer is simple: use threads!
Here is a tutorial how to do it:
http://www.binarytides.com/server-client-example-c-sockets-linux/
Some other examples of servers handling multiple connections, if you don't like threads:
http://martinbroadhurst.com/server-examples.html
And if you don't want mess things up (which is always easy in multithreaded code), I recommend reading answer to this question:
Tips to write thread-safe UNIX code?
To make long story short: you need to watch out for any variable that is shared between threads, like globals, statics and arguments passed by pointer. You must avoid situations, when two threads try to write in the same place (for example client_hostname global variable) and then try to read from it, because you may end up with a situation, when you loose one of the values and have two threads from two different clients sharing the same hostname.
Also keep in mind one more thing: three best C programmers I have ever met in person consider multithreading programming as the most difficult part of their job. You are now tackling complicated and complex problem. Don't be discouraged if you failed at first, everyone did at first.
Also, a bit of advice: never mix up two different languages for naming variables. Since you can't get rid of English (because libraries are in English), I advise you to stop using Polish words. Usually it is a standard in most companies to only use English in their source code anyway - even if they are located in non-English speaking country.


text:
Q: As keyword with tablename alias in hive not working Unable to use as keyword for tablename alias  in HIVE ql
select a.day , a.buyer , b.name ,b.age ,b.id, a.work , a.year
from tracker AS  a ,caller   AS b ;

gives

mismatched input 'AS' expecting EOF near 'tracker'

A: select a.day , a.buyer , b.name ,b.age ,b.id, a.work , a.year from tracker a ,caller b ;

try this

A: The normal alias assignment with 'AS' keyword as used in some other RDBMS is not supported in PIG. I guess Rony's solution should work fine.


text: Q: Rewriting MFC functions use C++ standard library I'm writing a Windows service (to operate a binary file) use C++ standard library in Visual Studio 2015 and I want to re-write some functions are developed in MFC. I have a question that how can I rewrite (or use another instead) class CObject that used in the MFC application.


text:
Q: Open ng-bootstrap modal programmatically I've got an angular 4 page including a ng-bootstrap modal. My code looks like this.
foo.html
[...]
<button class="btn btn-sm btn-secondary material-icons"
(click)="open(content)">search</button>

<ng-template #content let-c="close" let-d="dismiss">
    content in here
</ng-template>
[...]

foo.ts
[...]
constructor(private modalService: NgbModal) { }
[...]
open(content) {
   let options: NgbModalOptions = {
     size: 'lg'
   };

   this.modalService.open(content, options);
}
[...]

Now when I click the button the modal opens. What I want to do now is open the model on ngChanges.
ngOnChanges(changes: any) {
   open(content)
}

My problem is: How do I get the "content" here? Is there any way to get the ng-template programmatically? Thanks in advance!

A: To access the content element inside the class, declare:
@ViewChild('content', { static: false }) private content;
                         ^for Angular8+

and add the corresponding import at the top of the class:
import { ViewChild } from '@angular/core';

and finally call open method for that element on change detection:
ngOnChanges(changes: any) {
   this.open(this.content);
}

A: from Angular 8 you should also pass static option: {static: false} in ViewChild
import { ViewChild } from '@angular/core';

@ViewChild('content', { static: false }) private content;

constructor(private modalService: NgbModal) { }

this.modalService.open(this.content);


text:
Q: Scheduling task in R using Rselenium not working I try to automatically run an R script in Windows 8 using task scheduler as petermeissner explains in this thread. Below I pasted (part of) the script. The script does everything until remDr$getPageSourece(). I get a pop-up message saying 'R for Windows front-end has stopped working'. However, if I run the script in R (so not using scheduler) no error occurs. What can be possibly wrong?
pacman::p_load(RSelenium)
appurl <- "https://prod.beeline.com/ucb/Security/NewLogin.aspx?Url=%2fucb"
setwd("../downloaded")

RSelenium::checkForServer()
RSelenium::startServer()

Sys.sleep(5)

remDr <- RSelenium::remoteDriver(browserName="chrome") #For chrome make sure the file 'chromedriver is under 'downloaded'. Also this file can be found on TFS

remDr$open(silent=T)
remDr$navigate(appurl)
Sys.sleep(1)
remDr$findElement(using = "css selector","#beelineForm_UserLoginForm_userNameText")$sendKeysToElement(list("username"))
Sys.sleep(1)
remDr$findElement(using = "css selector","#beelineForm_UserLoginForm_passwordText")$sendKeysToElement(list("passwd"))
remDr$findElement("css selector", "#loginButton")$clickElement()

appurlNew <- "https://prod.beeline.com/ucb/Procurement/Request/ProcurementRequestListScreen.ascx"
Sys.sleep(1)

remDr$navigate(appurlNew)
Sys.sleep(3)

x <- getwd()
write(x, file="workingdir1.txt")

remDr$getPageSource()

EDIT: I tried re-running the script in R and now it also seems to block at remDr$getPageSource(). R says it 'searches for a function definition' until the session aborts.


text:
Q: ¿Como acceder a métodos(setters y getters) de objetos de diferentes clases en un arrayList en java? tengo un duda con los arrayList:
Tengo una clase Vehículo, y de ella se desprende dos hijos, uno Moto y otro Auto. Necesito hacer una lista de Vehiculos en general, motos, autos, etc. Paso las clases que use:
public class Vehiculo {
    // ATRIBUTOS
    private double precio;
    private String marca;
    private String modelo;

    // METODOS
    // Constructor
    public Vehiculo (String marca,String modelo,double precio){
      this.precio=precio;
      this.marca=marca;
      this.modelo=modelo;
    }
    // getters
    public double getPrecio() {
        return precio;
    }

    public String getMarca() {
        return marca;
    }

    public String getModelo() {
        return modelo;
    }

    // setters
    public void setPrecio (int precio) {
        this.precio=precio;
    }

    public void setMarca (String marca) {
        this.marca=marca;
    }

    public void setModelo (String modelo) {
        this.modelo=modelo;
    }

}

Luego tengo la clase Motos:
public class Moto extends Vehiculo{
  // Atributos
  private int cilindrada;

  // METODOS
  // Constructor - sub class constructor-using super()
  public Moto (String marca,String modelo,int cilindrada,int precio){
    super(marca,modelo,precio);
    this.cilindrada=cilindrada;
  }
  // getters
  public int getCilindrada() {
    return cilindrada;
  }
  // setters
  public void setCilindrada (int cilindrada) {
    this.cilindrada=cilindrada;
  }
}

Luego tengo la clase Auto
public class Auto extends Vehiculo{
  // Atributos
  private int puertas;
  // METODOS
  // Constructor - sub class constructor-using super()
  public Auto (String marca,String modelo,int puertas,int precio){
    super(marca,modelo,precio);
    this.puertas=puertas;
  }
  // getters
  public int getPuertas() {
    return puertas;
  }
  // setters
  public void setPuertas (int puertas) {
    this.puertas=puertas;
  }
}

Luego en el main creo los objetos de clases moto y auto,
    Auto auto1 = new Auto("Peugeot","206",4,200000);
    Moto moto1 = new Moto("Honda","Titan",125,60000);

y luego los agrego al arraylist,
ArrayList<Vehiculo> arrayList = new ArrayList<Vehiculo>();
    arrayList.add(auto1);
    arrayList.add(moto1);

Hasta ahí todo perfecto. El tema es que al querer acceder a un método getter especifico de clase Moto o de Auto, no me deja.
¿Como puedo acceder? por ejemplo no me deja hacer:
System.out.println(arrayList.get(1).getCilindrada() );

pero si me deja acceder a get o set de la clase padre Vehiculo
System.out.println(arrayList.get(1).getPrecio() );

Desde ya muchas gracias. Saluos

A: Puedes tener dos listas:
ArrayList<Motos> listaDeMotos = new ArrayList();
listaDeMotos.add(moto1);

ArrayList<Autos> listaDeAutos = new ArrayList();
listaDeAutos.add(auto1);

O si necesitas agregar todos en una sola lista entonces necesitas saber que que estás hablando cuando iteras. Por ejemplo:
Vehiculo vehiculo = listaDeAutosYVehiculos.get(i);
if (vehiculo instanceof Moto) {
  Moto moto = (Moto)vehiculo;
  System.out.println(moto.getCilindrada() );
 //aquí con este objeto moto puedes accesar todos los métodos de vehículo y de moto.
}
else if (vehiculo instanceof Auto) {
  Auto auto = (Auto)vehiculo;
  System.out.println(auto.getPuertas());
  //con el objeto auto accesas los métodos de auto y de vehículo.
}
else { ??? }

A: Lo que yo veo es que:
En la posicion 0 tines a auto1 con estos atributos: ("Peugeot","206",4,200000)
Y en la poscion 1 tienes a moto1 con sus atributos: ("Honda","Titan",125,60000)
Y para acceder a sus atributos seria algo como esto
 arrayList.get(0).getPuertas();  //metodos de Auto/Vehiculo
 arrayList.get(1).getCilindrada(); //metodos de Moto/Vehiculo

A: No puedes acceder a esos métodos, porque no le pertenecen a la clase padre Vehiculos, son solo de Moto y Auto, como bien te mencionaron arriba, lo único que te quedaría por hacer sería la forma de iterar tu lista de vehículos.
Como por ejemplo:
Auto auto = new Auto("Audi", "A3", 4, 1000000);
Moto moto = new Moto("Yamaha", "Ninja", 2, 50000);

List<Vehiculo> vehiculos = new ArrayList<>();
vehiculos.add(moto);
vehiculos.add(auto);

for (Vehiculo vehiculo: vehiculos)
{
  if (vehiculo instanceof Auto)
  {
    System.out.println(((Auto) vehiculo).getPuertas());
  }

  if (vehiculo instanceof Moto)
  {
    System.out.println(((Moto) vehiculo).getCilindrada());
  }
}


text:
Q: Copy multiple ranges to one array I have excel file that contains 10 columns. i have to select multiple columns based on their names then copy all values in one array.
first step i tried to get the columns index
string columnsName;
var columnsNumbers = new List<int>();
for (int i = 1; i < range.Columns.Count; i++)
{
   columnsName = ((Range) range.Cells[1, i]).Value2;
   if(columnsName.Equals("Empl, "+DateTime.Now.Year,StringComparison.OrdinalIgnoreCase))
     columnsNumbers.Add(i);
   if (columnsName.Equals("Test, " + DateTime.Now.Year, StringComparison.OrdinalIgnoreCase))
      columnsNumbers.Add(i);
   if (columnsName.Equals("Jour, " + DateTime.Now.Year, StringComparison.OrdinalIgnoreCase))
      columnsNumbers.Add(i);
   if (columnsName.Equals("Actual, Other Suppliers, " + DateTime.Now.Year, StringComparison.OrdinalIgnoreCase))
      columnsNumbers.Add(i);
   if (columnsName.Equals("FutureR, " + DateTime.Now.Year+1, StringComparison.OrdinalIgnoreCase))
      columnsNumbers.Add(i);
 }

Now that i added the target indexes in a list, how can i got the values of the stored column indexes and store all in 2d array?

A: google helps...
here you can see how to get a range between two cells
together with this (which does quite the opposite, writing an array to a range) you will probably find out how to read a range into an array ...
once you have all your arrays for the columns, all you have to do is to find out which dimensions your final array should have, create it, and then start to copy


text:
Q: Finding Sync of Columns in R Data
    v1 <- c(52.9799999999814, 53.4200000000128, 52.0899999999965, 57.9700000000012,
    60.679999999993, 0.300000000017462, 1.76999999998952, 61.1900000000023,
    58.9599999999919, 1.73000000001048, 0.269999999989523, 6.92000000001281,
    60.5299999999988, 60.859999999986, 59.5599999999977, 61.0600000000268,
    60.6299999999756, 60.9700000000012, 60.1600000000035, 60.4599999999919,
    60.0900000000256)

    v2 <- c(52.679999999993, 53.140000000014, 52.8899999999849, 57.6700000000128,
    60.5199999999895, 2.04000000000815, 61.890000000014, 59.5699999999779,
    2.05999999999767, 6.98000000001048, 60.7399999999907, 60.7799999999988,
    59.7300000000105, 60.9100000000035, 60.3299999999872, 60.5500000000175,
    60.6600000000035, 60.3499999999767, 60.7300000000105, 60.6700000000128,
    60.3799999999756)

tv3 <- data.frame(v1,v2)

    tv3$v5 <- tv3$v2 - tv3$v1
    tv3$v5
     [1]  -0.30  -0.28   0.80  -0.30  -0.16   1.74  60.12  -1.62 -56.90   5.25  60.47  53.86  -0.80
    [14]   0.05   0.77  -0.51   0.03  -0.62   0.57   0.21   0.29

So you see, the difference should remain smaller, if it is larger, like in this case, at particular row, it gets 60.
So basically if we remove the 0.30 row in just V1 and shift it one cell up, The difference wouldn't hike upto 60.
So the 0.30 is noise value and that's what I have to figure and put it in V3
My desired results are the following.
    v1       v2     V3
    52.98   52.68   0.3
    53.42   53.14   0.27
    52.09   52.89
    57.97   57.67
    60.68   60.52
    1.77    2.04
    61.19   61.89
    58.96   59.57
    1.73    2.06
    6.92    6.98
    60.53   60.74
    60.86   60.78
    59.56   59.73
    61.06   60.91
    60.63   60.33
    60.97   60.55
    60.16   60.66
    60.46   60.35
    60.09   60.73

So notice here that all the sequence of columns seem to be in sync with just a difference of few points.
May be my case requires implementation of Needleman-Wunsch Algo


text:
Q: Can I force SSL to secure a Dotnetnuke Module Edit Page? I have a DNN modules where I don't care if the VIEW page does not use SSL.
However, when a module editor loads my modules' EDIT page in the admin template (my module is the only module on the page) I want to load the page securely using SSL, if the site has SSL capability.
Is this possible?

A: Yes, just put the following at the start of the modules's code behind.
// Force Page to use SSL if it can.
if (PortalSettings.SSLEnabled && !Request.IsSecureConnection)
{
  DotNetNuke.Security.PortalSecurity.ForceSecureConnection();
}


text:
Q: Excel: transpose rows to columns and merge I would like to present some data in Excel in a table. I have a sheet with three columns: date, time_spent and user_id. Every row is a data record. I want a table with a column for every date and every value with time spent below the date.
Using the transpose function under paste special I get this:

However I would like only one column per unique date, so the amount of columns decrease like this:

Does someone know how to do this?\
I have more than 10000 rows, so manually is too much effort...
Using Pivot Tables as Tim Biegeleisen suggested I cannot get what I want either, I'm not an expierenced user of Pivot Tables so probably I'm doing something wrong:

Excel file as shown in above picture

A: Here is one way of using a Pivot Table as suggested by Tim above in the comments, but you must use it on your original, non-transposed data:  (and note which parameters go to which areas.

A disadvantage of the Pivot table is that the column headers are text strings and not dates.  If your version of Excel is 2010+, you can use Power Pivot or Get and Transform to do a better job:

*

*Open the Query Editor, change the format of the Date column, and Pivot the column:

Then Save the results:

A: *

*Advanced filter dates to unique values in a new column

*Copy and transpose them to make your column titles

*Insert a new column B with the formula =TEXT(A2,"yyyyddmmm")&COUNTIF($A$2:A2,A2) and fill down

*Below your new column headers put in the formula =IFERROR(VLOOKUP(TEXT(H$1,"yyyyddmmm")&ROW()-1,$B$2:$C$8,2,FALSE),"") and fill down and across. You will need to fill it down to cover the maximum number of instances of each date.

*Adding a sumif to this table and your initial table would be a good way to check you got everything.


text:
Q: How to append system time to the file name in oracle? I am very new to oracle.I need to create a file with the system timestamp from oracle. Please let me know how do  i do that.
More over I need to write any exceptions or errors thrown by my pl/sql code to a file and exit after an error. How do i do this?
Thanks,
Priya.R

A: It seems you want to look into the UTL_FILE Oracle supplied package, as you're trying to use PL/SQL to create the file.
You can generate the file this way:
(You'll need to create an Oracle DIRECTORY first, pointing to the OS location of the file:
CREATE OR REPLACE DIRECTORY DIR AS 'your OS directory';

Note that the name 'DIR' is used in the sample code that follows. You will also require the CREATE DIRECTORY privilege, and then grant read and write permissions on the directory to the user who will use it:
GRANT READ,WRITE ON DIR TO user1;

)
DECLARE
  v_logfile VARCHAR2(100);
  v_FH      UTL_FILE.FILE_TYPE;
BEGIN
  v_logfile := TO_CHAR(SYSDATE,'YYYYMMDD HH24MISS')||'_process.log';
  v_FH      := UTL_FILE.FOPEN(DIR, v_logfile, 'w');
  UTL_FILE.PUTLINE(v_FH, 'Some text on a new line');
  UTL_FILE.FCLOSE(v_FH);
END;

A: This is how you can get a dynamic filename in SQL Plus
SET TERMOUT OFF

DEFINE dynamic_filename = idle
COLUMN which_dynamic NEW_VALUE dynamic_filename

SELECT   'prefix_'
       ||TO_CHAR( SYSDATE, 'YYYYMMDD' )
       ||'_'
       ||TO_CHAR( SYSDATE, 'HH24MISS' )
       ||'.log'   which_dynamic
  FROM dual;

SET TERMOUT ON

SPOOL &dynamic_filename

SELECT * FROM dual;

SPOOL OFF

The file gets created in the default directory for SQL Plus (on windows this is the "Start In:" property of the shortcut)
To place the output in a known directory amend the SPOOL command to something like...
SPOOL c:\output_dir\&dynamic_filename

To get an SQL Plus script to exit after an error then include this command...
WHENEVER SQLERROR EXIT SQL.SQLCODE ROLLBACK


text:
Q: как в WPF проверить завершение события SizeChanged на элементе DataGridColumnHeader? На  странице существует DataGrid в который динамически добавляются элементы типа DataGridTextColumn
Layers.Columns.Add(itemCollumn);

также описаны вот такие стили:
<Style TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="SeparatorBrush" Value="#D5D505" />
    <Setter Property="Margin" Value="-1,0,0,0" />
    <Setter Property="Height" Value="S0" />
    <EventSetter Event="Click" Handler="ClickHeader" />
    <EventSetter Event="SizeChanged" Handler="SizeChatget" />
</Style>

Событие SizeCharget срабатывает при изменение ширины колонки при зажатой левой кнопки мыши, существует ли подобное событие которое сработает когда я отпущу левую кнопку мыши, то есть когда изменение ширины завершиться, или как это возможно реализовать???
<DataGrid x:Name="Layers"
          Grid.Row="3"
          Grid.Column="1"
          Grid.ColumnSpan="6"
          Width="750"
          Height="50"
          GridLinesVisibility="All" />


text:
Q: An urn contains two red balls and four white balls. Sample successively five times at random and with replacement, so that the trials are independent. An urn contains two red balls and four white balls. Sample successively five times at random and with replacement, so that the trials are independent.
(a) Compute the probability that no two balls drawn consecutively in the sequence of five balls have the same color.
(b) How would your answer to part (a) change if the sampling is without replacement?
For (a). I am not sure the correct way of thinking this. I was listing all the possible cases of drawing the same ones consecutively and then use complement rule to figure out the probability. Is that the right way of thinking?

A: Hint: For the first draw, you can start with White or Red. After that, you must draw a ball of the opposite color on every draw. This gives two "valid" sequences: $WRWRW$ or $RWRWR$.

 So, the probability for part (a) would be $$\left(\dfrac{4}{6}\right)\left(\dfrac{2}{6}\right)\left(\dfrac{4}{6}\right)\left(\dfrac{2}{6}\right)\left(\dfrac{4}{6}\right) + \left(\dfrac{2}{6}\right)\left(\dfrac{4}{6}\right)\left(\dfrac{2}{6}\right)\left(\dfrac{4}{6}\right)\left(\dfrac{2}{6}\right) = \left(\dfrac{2}{3}\right)^3\left(\dfrac{1}{3}\right)^2+\left(\dfrac{2}{3}\right)^2\left(\dfrac{1}{3}\right)^3 \approx 4.94\%$$
 The probability for part (b) would be different because there are not enough red balls for $RWRWR$. This leaves $WRWRW$ as the only possible valid outcome, with probability $$\left(\dfrac{4}{6}\right)\left(\dfrac{2}{5}\right)\left(\dfrac{3}{4}\right)\left(\dfrac{1}{3}\right)\left(\dfrac{2}{2}\right) \approx 6.67\%$$ This may seem surprising because although there are fewer valid outcomes, the probability of its occurrence is actually higher.


text:
Q: In how many ways can $14$ people be seated in a row if there are $8$ men and they must sit next to one another? In how many ways can 14 people be seated in a row if:
a.) there are 7 men and 7 women and no two men or two women sit next to each other?
My attempt: Since no two men or women can sit next to each other I calculated $(7-1)! \cdot (7-1)! = 518400$
b.) there are 8 men and they must sit next to one another?
My attempt: If 8 men must sit next to one another, then there are 6 women left. What I did was calculate $(6 + 1)! = 5040$
Is this the correct approach?

A: For b. you forgot to permute men so you have to multiply it by $8!$, so it is $8!\cdot 7!$
For a. Why do you have $6!^2$?, you have 7 men and 7 women, so it is $7!\cdot 7! \cdot 2$, since you can start with a man or you start with a woman.

A: Recall that the number of permutations of $n$ distinct objects is $n!$ (not $(n-1)!$ or $(n+1)!$).
For (a). The 7 men and the 7 women are alternated and the row can start with a man or with a woman (2 cases). Therefore the number of ways is
$$2\cdot 7!\cdot 7!$$
For (b). We have a block of 8 men and 6 women, and the last man in the block can be in position $8$th to $14$th (7 cases). Therefore the number of ways is
$$7\cdot 8!\cdot 6!$$


text:
Q: Android Studio add test folder or module to existing project I want to add testing to my android app in Android Studio 1.4. When I try to create and add them to /test folder under a root folder they aren't executed. Also, I tried to create a separate module for tests but there are no Test Module in a wizard. How can I add and run Junit tests?
Thank you in advance.

A: https://stackoverflow.com/a/28630023/4955008
This helped me a lot, Studio recognized folder as a test and it passed.


text:
Q: Reading .pdf from raw folder in project Here I'm trying to read a .pdf file from my assets folder and the error shows "THIS DOCUMENT CAN NOT BE OPENED". I tried copying .pdf file to the sd card and then read it from there but it wasn't successful. Here is the code. Please help me.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    File fileBrochure = new File("/sdcard/fleetman.pdf");
    if (!fileBrochure.exists())
    {
         CopyAssetsbrochure();
    }

    /** PDF reader code */
    File file = new File("/sdcard/fleetman.pdf");

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file),"application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try
    {
        getApplicationContext().startActivity(intent);
    }
    catch (ActivityNotFoundException e)
    {
         Toast.makeText(MainActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
    }
}

//method to write the PDFs file to sd card
    private void CopyAssetsbrochure() {
        AssetManager assetManager = getAssets();
        String[] files = null;
        try
        {
            files = assetManager.list("");
        }
        catch (IOException e)
        {
            Log.e("tag", e.getMessage());
        }
        for(int i=0; i<files.length; i++)
        {
            String fStr = files[i];
            if(fStr.equalsIgnoreCase("fleetman.pdf"))
            {
                InputStream in = null;
                OutputStream out = null;
                try
                {
                  in = assetManager.open(files[i]);
                  out = new FileOutputStream("/sdcard/" + files[i]);
                  copyFile(in, out);
                  in.close();
                  in = null;
                  out.flush();
                  out.close();
                  out = null;
                  break;
                }
                catch(Exception e)
                {
                    Log.e("tag", e.getMessage());
                }
            }
        }
    }

A:   try this, hope it ll help you

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

    }

    private void CopyReadPDFFromAssets()
    {
        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), "pdfdemofile.pdf");
        try
        {
            in = assetManager.open("pdfdemofile.pdf");
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

            copyPdfFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e)
        {
            Log.e("exception", e.getMessage());
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/pdfdemofile.pdf"),
                "application/pdf");

        startActivity(intent);
    }

    private void copyPdfFile(InputStream in, OutputStream out) throws IOException
    {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }

Add in Manifest File
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


text:
Q: .net winform Grid Alternatives? I am using vb.net / Winform 2010.
I am looking for a free (or very cheap) alternative to the DataGridView, one that looks more like what I see on ads for XTraGrid. Something that will multiple lines per records, and for lines to be rolled up, and expanded by clicking, etc.

A: Check out this open source grid control.  http://www.codeproject.com/KB/grid/csharpgridcontrol.aspx


text:
Q: Changing display server in Ubuntu 18.04 I'm using Ubuntu 18.04 LTS on Linux kernel 4.15.0.
I've learned that casting the entire screen can't yet be done with Wayland.
Is there any workaround for this, or should I change my display server entirely?
If so, Can someone walk me through changing my display server from Wayland to something else that can support casting a whole screen?
Edit: I'm now able to cast my entire screen, probably due to a patch.


text:
Q: SQL query, return randomly ordered rows with limits, possible? I am thinking of returning a randomly ordered SQL response where the results are mixed up randomly, with a limit.
The thing is I need All the rows back, basically divided into groups (chunks of rows). I hope I am clear.
For example, from table A:
ID   |   NAME    |   PROFESSION
++++++++++++++++++++++++++++++++
1    |  Jack     |   Carpenter
2    |  Rob      |   Manager
3    |  Phil     |   Driver
4    |  Mary     |   Cook
5    |  Tim      |   Postman
6    |  Bob      |   Programmer

The query would return something like this:
With a limit of 0,2:
6    |  Bob      |   Programmer
4    |  Mary     |   Cook

With a limit of 2,2:
1    |  Jack     |   Carpenter
5    |  Tim      |   Postman

With a limit of 4,2:
3    |  Phil     |   Driver
2    |  Rob      |   Manager

Note: all the table rows were returned. In my page I need to have a << >> buttons that will show the user the needed "group"s of data.
How do I go about writing such a query ?

A: A better name for your explained problem would be randomly shuffled records. That is true that the order is random but since the order needs to be remembered, you have no choice but to save it in a column. You can do this by saving a randomly populated field and ordering your records based on that. This way you have ordered your records in no specific order while the order is remembered for future select queries. And whenever you got tired of the order, you can update the mentioned field with new randomly generated values to shuffle them again. This is the technique used by players to shuffle a playlist without replaying a song twice.
[EDIT]
While the first given solution stands as the general answer, there's a hack you can use in MySQL to randomly order records. In this way, all you need to store for remembering an order is its seed.
SELECT * FROM tbl ORDER BY RAND(s);

For instance, if you want each user see the records in some different randomly ordered, you can use their user_id as the seed. This way the order each user will ever see the records in, will remain the same while it is random and different from other users.

A: I can think of two things here:

*

*If the data in the table is huge, add a column that tells the group to which a row belongs. When the user clicks on >> or << buttons, get the rows for that particular group.

*If you are dealing with small amount of data, you could do this in the code itself.

A: If you use ORDER BY RAND() then you will have to flag selected records somewhere which is no advisable.
You can use some intelligent algorithm with combination of total_pages and ID e.g.
SELECT *
FROM  my_table
ORDER BY MOD(ID, total_pages);

A: Add a column to the table called something like random_col
Then each time you need to randomise the table you run
UPDATE table SET random_col = RAND()

And now each time you want to retrieve results you run a normal select
SELECT * FROM table ORDER BY random_col ASC LIMIT x,y

And the results will appear in the same order until you randomise them again by running the 'UPDATE'


text:
Q: Nginx remove a path in uri I need to remove a part path in a request uri. I'm using an ingress on Goocle Cloud to access to the server and I want that if I go to localhost/symfony/ the symfony path is ignored in the uri request.
At moment It works if I go to localhost/symfony but If I go to localhost/symfony/something I receive 404 default backend.
I have tried also to add $1 to set request_url but it not works.
This is my configuration:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: symfony-nginx
  namespace: default
  labels:
    app: symfony-nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: symfony-nginx
  template:
    metadata:
      labels:
        app: symfony-nginx
    spec:
      volumes:
        - name: symfony-nginx
          configMap:
            name: symfony-nginx-configmap
      containers:
      - name: symfony-nginx
        image: nginx:stable
        ports:
        - containerPort: 80
        volumeMounts:
        - mountPath: /etc/nginx/conf.d
          name: symfony-nginx
        resources:
          requests:
            memory: 32Mi
            cpu: 10m
          limits:
            memory: 64Mi
            cpu: 30m
        readinessProbe:
          httpGet:
            path: /nginx-health
            port: 80
          initialDelaySeconds: 15
          timeoutSeconds: 1
          periodSeconds: 10
        livenessProbe:
          httpGet:
            path: /nginx-health
            port: 80
          initialDelaySeconds: 15
          timeoutSeconds: 1
          periodSeconds: 10
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: symfony-nginx-configmap
  namespace: default
data:
  default.conf: |
    server {
            server_name php-docker.local;
            error_log  /var/log/nginx/error.log;
            access_log /var/log/nginx/access.log;
            root /var/www/html/symfony/public;

            proxy_buffering off;

            location = /nginx-health {
                access_log off;
                return 200 "healthy\n";
            }

            location / {
                try_files $uri /index.php$is_args$args;
            }

            location ~ ^/index\.php(/|$) {

                set $request_url $request_uri;
                if ($request_uri ~ ^/symfony(.*)$ ) {
                    set $request_url /;
                }
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass symfony:9000;
                include fastcgi_params;
                fastcgi_param  REQUEST_URI $request_url;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $document_root;
                internal;
            }
            location ~ \.php$ {
                    return 404;
            }
        }
---
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: symfony-nginx-hpa
  namespace: default
  labels:
    app: symfony-nginx
spec:
  scaleTargetRef:
    kind: Deployment
    name: symfony-nginx
    apiVersion: apps/v1
  minReplicas: 1
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
---
apiVersion: v1
kind: Service
metadata:
  name: symfony-nginx-np
  namespace: default
  labels:
    app: symfony-nginx
spec:
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  selector:
    app: symfony-nginx
  type: NodePort
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: symfony-nginx-ingress
spec:
  rules:
  - http:
      paths:
      - path: /symfony
        backend:
          serviceName: symfony-nginx-np
          servicePort: 80

Any suggestion?
Thansk a lot
Pasquale

A: You need to use annotations in the Ingress object to rewrite URI. The nginx.ingress.kubernetes.io/rewrite-target annotation targets URI where the traffic must be redirected. Example:
    apiVersion: extensions/v1beta1
    kind: Ingress
    metadata:
      annotations:
        nginx.ingress.kubernetes.io/rewrite-target: /
      name: symfony-nginx-ingress
    spec:
      rules:
      - http:
          paths:
          - path: /symfony
            backend:
              serviceName: symfony-nginx-np
              servicePort: 80

In this case, it will rewrite URI from localhost/symfony/ to localhost/.
Please note that it works for all endpoints described in the Ingress object.


text:
Q: startEditingAtPath() throws exception when adding a node to a JTree
I'm learning to JTrees and Java.
Constructive suggestions and feedback are very welcome.
I think I am missing some understanding of JTrees and after 5 hours Googling, and testing I'm stuck. I've simplified the code as much as possible.
        public void actionPerformed(ActionEvent event) {
            MyNode selNode = (MyNode) m_tree.getLastSelectedPathComponent();
            if (selNode != null) {
                MyNode newNode = new MyNode("New Node");
                model.insertNodeInto(newNode, selNode,
                        selNode.getChildCount());
                MyNode[] nodes = model.getPathToRoot(newNode);
                TreePath path = new TreePath(nodes);
                m_tree.scrollPathToVisible(path);
                m_tree.setSelectionPath(path);
                // *******   The next line throws the exception shown below.  ****
                m_tree.startEditingAtPath(path);
            }

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.plaf.basic.BasicTreeUI.startEditing(BasicTreeUI.java:2059)
at javax.swing.plaf.basic.BasicTreeUI.startEditingAtPath(BasicTreeUI.java:601)
at javax.swing.JTree.startEditingAtPath(JTree.java:2349)
at ItemCreator.ItemCreator$1.actionPerformed(ItemCreator.java:74)

Code - My Simple Mutable JTree
1) When adding a new node into the JTree the code throws Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
2) Any general constructive feedback very welcome.
Kind regards

A: The problem is not the startEditingPath, but the incorrect model implementation. Basically its fails to notify its listeners on changes, consequently the ui has no chance to update its internals to include the added node.
The model fails in

*

*not accepting listeners (empty implementation of addTreeModelListener)

*not even trying to fire after changing (on inserts, updates ...)

*incorrect getPathToRoot implementation

It's not entirely trivial and the java doc slightly (to put it mildly) confusing - that's why SwingX has a well-tested utility class TreeModelSupport which takes over the burden. It can be used standalone, or as a blue-print of how-to do it.
In your custom model, some relevant changes (incomplete, the other modification methods must be fixed accordingly, as must the remove listener):
// prepare fix issue 1: instantiate the notification support
private TreeModelSupport support;

public ItemTreeModel(MyNode root) {
    this.root = root;
    support = new TreeModelSupport(this);
    // remove the following: a model never listens to itself
    // this.addTreeModelListener(new MyTreeModelListener());
}

// fix issue 1: accept listener
public void addTreeModelListener(TreeModelListener l) {
    support.addTreeModelListener(l);
}

// fix issue 2: notify the listeners on inserts
public void insertNodeInto(final MyNode newNode, final MyNode selNode,
        final int childCount) {
    selNode.add(childCount, newNode);
    newNode.setLocation(selNode);
    support.fireChildAdded(new TreePath(getPathToRoot(selNode)),
            childCount, newNode);
}

// fix issue 3: pathToRoot as needed in TreePath
public MyNode[] getPathToRoot(MyNode node) {
    ArrayList<MyNode> itemArrayList = new ArrayList<MyNode>();
    // TODO - Add root node ?
    // yes, certainly - please read the java doc for TreePath
    while ((node != null)) { // && (node != root)) {
        itemArrayList.add(0, node);
        node = node.getLocation();
    }
    return itemArrayList
            .toArray(new MyNode[itemArrayList.size()]);
}


text:
Q: Reading a csv as utf-8-sig from any encoding I'm writing a data processing scripts, that should handle files of any encodings.
When reading the files, I use:
 df = pd.read_excel(filepath, dtype=str) if '.xlsx' in \
                        filepath else pd.read_csv(filepath, dtype=str, low_memory=False,
                                               error_bad_lines=True, sep=CSV_delimiter)

(CSV_delimiter and filepath are defined variables)
While xlsx files work great, the handling of csvs is less straightforward. For many files, I keep receiving encoding errors that resolve only when I open the csvs manually, save with utf-8-bom encoding, and run the script again. I tried adding encoding="utf_8_sig", but now receiving errors like this:
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Any recommendations?


text:
Q: getting a syntax error when parsing assignment statement in yacc [Caution Homework]
I need a hint as to why the following code is failing when I try to run the test case: int a = 3; All the code compiles with no warnings or errors, and as far as I can tell the structure is correct.I feel there must be a problem in the rules for assignment.
The error message says: ERROR: syntax error at symbol "a" on line 1
This is the .lex file:
%{

#include "calc.h"
#include "symbol-table.h"
#include "tok.h"
int yyerror(char *s);
int yylinenum = 1;
%}

digit        [0-9]
int_const    {digit}+
float_const  {digit}+[.]{digit}+
id           [a-zA-Z]+[a-zA-Z0-9]*

%%

{int_const}    { yylval.int_val = atoi(yytext); return INTEGER_LITERAL; }
{float_const}  { yylval.float_val = atof(yytext); return FLOAT_LITERAL; }
"="            { yylval.str_val = strdupclean(yylval.str_val, yytext); return EQUALS; }
"+"            { yylval.str_val = strdupclean(yylval.str_val, yytext); return PLUS; }
"*"            { yylval.str_val = strdupclean(yylval.str_val, yytext); return MULT; }
"-"            { yylval.str_val = strdupclean(yylval.str_val, yytext); return MINUS; }
"/"            { yylval.str_val = strdupclean(yylval.str_val, yytext); return DIV; }
"("            { yylval.str_val = strdupclean(yylval.str_val, yytext); return OPAREN; }
")"            { yylval.str_val = strdupclean(yylval.str_val, yytext); return CPAREN; }
";"            { yylval.str_val = strdupclean(yylval.str_val, yytext); return SEMIC; }
"sqrt"         { yylval.str_val = strdupclean(yylval.str_val, yytext); return SQRT; }
{id}           { yylval.str_val = strdupclean(yylval.str_val, yytext);
                 /*HINT: One way to simplify parsing is to have lex return what
                  * type of variable we have.  IVAR = int, FVAR = float
                  * UVAR = unknown var.
                  * Naturally, you may use your own solution.
                  */
              if (strcmp(yylval.str_val, "int")) {return IVAR;}
              else if (strcmp(yylval.str_val, "float")) {return FVAR;}
                  else {return UVAR;}
               }

[ \t]*         {}
[\n]           { yylinenum++;    }

.              { yyerror("Unknown Symbol"); exit(1); }
%%

and this is the yacc file:
%{
#include "calc.h"
#include "symbol-table.h"
int yyerror(char *s);
int yylex(void);
%}

%union{
int         int_val;
float       float_val;
char*       str_val;
}

%start input

%token <int_val>   INTEGER_LITERAL
%token <float_val> FLOAT_LITERAL
%token <float_val> SQRT
%token OPAREN CPAREN SEMIC IVAR FVAR UVAR
%type  <int_val>   int_exp
%type  <float_val> float_exp
%type  <str_val>  IVAR FVAR UVAR
%right EQUALS /*right associative, everything on the right side of the = should be evaluated and stored*/
%left  PLUS MINUS/*The order matters, by listing PLUS/MIUS first and then MULT/DIV we are */
%left  MULT DIV /*telling yacc to evaluate MULTs & DIVs before PLUSes and MINUSes*/

%%

input:           /*empty*/
            | int_exp                   { printf("Result %d\n", $1); }
            | float_exp                 { printf("Result %f\n", $1); }
            | assignment                { printf("Result \n"); }
            ;

int_exp:          INTEGER_LITERAL           { $$ = $1; }
            | int_exp PLUS int_exp      { $$ = $1 + $3; }
            | int_exp MULT int_exp      { $$ = $1 * $3; }
            | int_exp MINUS int_exp     { $$ = $1 - $3; }
            | int_exp DIV int_exp       { $$ = $1 / $3; }
            | OPAREN int_exp CPAREN     { $$ = $2; }
            ;

float_exp:        FLOAT_LITERAL             { $$ = $1; }
            | float_exp PLUS float_exp  { $$ = $1 + $3; }
            | float_exp MULT float_exp  { $$ = $1 * $3; }
            | float_exp MINUS float_exp { $$ = $1 - $3; }
            | float_exp DIV float_exp   { $$ = $1 / $3; }
            | int_exp PLUS float_exp    { $$ = (float)$1 + $3; }
            | int_exp MULT float_exp    { $$ = (float)$1 * $3; }
            | int_exp MINUS float_exp   { $$ = (float)$1 - $3; }
            | int_exp DIV float_exp     { $$ = (float)$1 / $3; }
            | float_exp PLUS int_exp    { $$ = (float)$1 + $3; }
            | float_exp MULT int_exp    { $$ = (float)$1 * $3; }
            | float_exp MINUS int_exp   { $$ = (float)$1 - $3; }
            | float_exp DIV int_exp     { $$ = (float)$1 / $3; }
            | OPAREN float_exp CPAREN   { $$ = $2; }
            | SQRT OPAREN float_exp CPAREN  { $$ = sqrt((double)$3); }
            | SQRT OPAREN int_exp CPAREN    { $$ = sqrt((double)$3); }
            ;

assignment:       UVAR EQUALS float_exp SEMIC           { //if UVAR exists and is float, update value
                                          //if UVAR doesn't exist, error: unknown type
                                          symbol_table_node *n1 = symbol_table_find( $1, *st);
                                          if(n1) {
                                            if(n1->type == FLOAT_TYPE) {
                                                n1->val.float_val = $3;
                                            } else {
                                                //error
                                            }
                                            //error, variable not defined
                                          //if UVAR is not float, error: illegal assignment
                                          }
                                        }
            | UVAR EQUALS int_exp SEMIC         {
                                          symbol_table_node *n1 = symbol_table_find( $1, *st);
                                          if(n1) {
                                            if(n1->type == INT_TYPE) {
                                                n1->val.int_val = $3;
                                            } else {
                                                //error
                                            }
                                          }
                                        }
            | IVAR UVAR EQUALS int_exp SEMIC { //UVAR should not be in symbol table
                                          if(symbol_table_find($2, *st)) {
                                            //error
                                          } else {
                                            //how to handle errors?
                                            symbol_table_add_i($2, $4, *st);
                                          }
                                        }
            | FVAR UVAR EQUALS float_exp SEMIC {
                                          if(symbol_table_find($2, *st)) {

                                          } else {
                                            symbol_table_add_f($2, $4, *st);
                                          }
                                        }
            ;

%%

int yyerror(char *s){
extern int yylinenum; /* defined and maintained in lex.c*/
extern char *yytext;  /* defined and maintained in lex.c*/

printf("ERROR: %s at symbol \"%s\" on line %d\n", s, yytext, yylinenum);
return -1;
}

A: The bug is simple enough:
if (strcmp(yylval.str_val, "int"))

does not do what you think it does. strcmp returns 0 if the two strings are equal, a negative value if the first one is lexicographically earlier, and a positive value if the first one is lexicographically later. Used as a boolean, that means that strcmp is false if the string compare equal, and true otherwise. So the token int will not generate the token value IVAL.
But I don't think that's really what you wanted to do, anyway. Your instructor's hint about having the lexer return a token type corresponding to the known datatype of the token is referring to looking the variable up in the symbol table and returning a token type corresponding to the declaration of the variable. It's not referring to recognizing the reserved words int and float, which should be done with simple lexer rules, much like your rule for the reserved word sqrt.
As written, your grammar does not allow expressions to use variables, so (even after you fix the bug I referred to), the following will fail:
int b = 0;
int a = b + 3;

because b won't be recognized as an int_exp. It's in this context that the instructor's hint applies. (Although personally, I would suggest doing it differently.)
Finally, I don't know what strdupclean does, but I presume it involves making a copy of yytext. That's almost certainly unnecessary in the case of operator tokens (+, -, and so on) or reserved words, since you will never refer to the "semantic value" of those tokens. (As evidence, you don't declare any of these tokens to even have a semantic type.) Unnecessary copying does have a cost, particularly if you need to clean up the memory allocated for the copy.
Good luck.


text:
Q: What combination of string functions I should use to get this right in impala? I want to separate this data
"trial: 1.28  :sprout: 1.28  :blossom: 1.088  :garden: 0.896  :standard: 1.088  :advance: 1.088"

in columns like column a 'trial' column b '1.28', column c 'sprout' column d '1.28' and so on....
can somebody help me with this?

A: You can use below function for this purpose. Main issue is you need to know how many possible split can be.
First remove all unwanted characters like : or double space. Then use below function to separate.
select split_part('trial: 1.28  :sprout: 1.28  :blossom:',' ',1)


text:
Q: I want to open the first link that appear when i do a search on google I want to get the first link from the html parser, but I'm getting anything(tried to print).
Also when i inspect the page on browser, the links are under class='r'
But when i print the soup.prettify(), and closely analyse then i find there is no class='r', instead class="BNeawe UPmit AP7Wnd".
Please help, thanks in advance!
import requests
import sys
import bs4
import webbrowser

def open_web(query):
    res = requests.get('https://google.com/search?q=' + query)
    res.raise_for_status()

    soup = bs4.BeautifulSoup(res.text, "html.parser")
    link_elements = soup.select('.r a')
    link_to_open = min(1, len(link_elements))
    for i in range(link_to_open):
        webbrowser.open('https://google.com' + link_elements[i].get('href'))

open_web('youtube')

A: The problem is that google serves different HTML when you don't specify User-Agent in headers. To add User-Agent to your request, put it in the headers= attribute:
import requests
import bs4

def open_web(query):
    headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0'}

    res = requests.get('https://google.com/search?q=' + query, headers=headers)
    res.raise_for_status()

    soup = bs4.BeautifulSoup(res.text, "html.parser")
    link_elements = soup.select('.r a')
    print(link_elements)

open_web('youtube')

Prints:
[

... and so on.

A: You received a completely different HTML with different elements and selectors thus the output is empty. The reason why Google blocks your request is because default requests user-agent is python-requests and Google understands it and blocks it. Check what's your user-agent.
User-agent let identifies the browser, its version number, and its host operating system that representing a person (browser) in a Web context that lets servers and network peers identify if it's a bot or not.
Sometimes you can receive a different HTML, with different selectors.

You can pass URL params as a dict() which is more readable and requests do everything for you automatically (same goes for adding user-agent into headers):
params = {
  "q": "My query goes here"
}

requests.get("YOUR_URL", params=params)

If you want to get the very first link then use select_one() instead.

Code and full example in the online IDE:
from bs4 import BeautifulSoup
import requests

headers = {
    'User-agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}

params = {
  "q": "My query goes here"
}

html = requests.get('https://www.google.com/search', headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')

link = soup.select_one('.yuRUbf a')['href']
    print(link)

# https://dev.mysql.com/doc/refman/8.0/en/entering-queries.html

Alternatively, you can do the same thing by using Google Organic Results API from SerpApi. It's a paid API with a free plan.
The difference in your case is that you only need to extract the data you want from JSON string rather than figuring out how to extract, maintain or bypass blocks from Google.
Code to integrate:
import os
from serpapi import GoogleSearch

params = {
    "engine": "google",
    "q": "My query goes here",
    "hl": "en",
    "api_key": os.getenv("API_KEY"),
}

search = GoogleSearch(params)
results = search.get_dict()

# [0] means first index of search results
link = results['organic_results'][0]['link']

# https://dev.mysql.com/doc/refman/8.0/en/entering-queries.html

Disclaimer, I work for SerpApi.


text:
Q: Record number constraint in mongodb Suppose we have a collection with this schema:
{
  "sub": 1234,
  "appId": 5678
}

The sub field is the user account id, and appId application id.
Now we need to limit the number of applications per user account to some value (let's say, 5). What is the easiest way?
Of course we could introduce transaction in mongodb as we do in SQL. Since we choose a document database, is there any more advanced way to this requirement?


text:
Q: how to make a property is only readable from abstract class in Dart? abstract class ListController {

   int numberOfDocumentPerPage = 7;

}

then use the abstract class
class EventListController extends ListController {

}

but when I make an instance, I can change/assign the new value to the property
final controller = EventListController();
controller.numberOfDocumentPerPage = 1000; // should be error in here

so how to make a property is only readable from abstract class ?
UPDATE:
I also need to modify the property inside EventListController class

A: Basically you want the base class to declare a public getter.  I think the simplest way would be:
abstract class ListController {
  static const defaultNumberOfDocumentPerPage = 7;

  int get numberOfDocumentPerPage => defaultNumberOfDocumentPerPage;
}

class EventListController extends ListController {
  int _numberOfDocumentPerPage = ListController.defaultNumberOfDocumentPerPage;

  @override
  int get numberOfDocumentPerPage => _numberOfDocumentPerPage;
}

If you don't want the separate named constant, you could explicitly initialize your internal value with the result of calling the original getter:
abstract class ListController {
  final int numberOfDocumentPerPage = 7;
}

class EventListController extends ListController {
  EventListController() {
    _numberOfDocumentPerPage = super.numberOfDocumentPerPage;
  }

  // ignore: super_in_invalid_context, https://github.com/dart-lang/sdk/issues/46850
  late int _numberOfDocumentPerPage = super.numberOfDocumentPerPage;

  @override
  int get numberOfDocumentPerPage => _numberOfDocumentPerPage;
}

Another approach would be to provide a protected setter in the base class:
import 'package:meta/meta.dart';

abstract class ListController {
  int _numberOfDocumentPerPage = 7;

  int get numberOfDocumentPerPage => _numberOfDocumentPerPage;

  @protected
  set numberOfDocumentPerPage(int value) => _numberOfDocumentPerPage = value;
}

But note that the @protected annotation just provides a hint to the analyzer so that it can warn about violations; it is not enforced at compilation-time nor at runtime.


text:
Q: Save changes in file in Windows Store app in required directory using c#, VS2013, windows store app
In simple program have a file with some data saved in JSON format. I'll try to add new data to this file and then store it.

Try to save file in JSON with next code:
string result = await JsonConvert.SerializeObjectAsync(groups);
//get file path
string pathOfFile = Path.GetDirectoryName(file.Path); //get path
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(pathOfFile); //create dir by path

StringBuilder builder = new StringBuilder();
builder.Append(folder.Path);
builder.Append("\\EventsData.json");

Uri uriToSave = new Uri(builder.ToString());
//create file
StorageFile fileToWrite =
    await StorageFile.GetFileFromApplicationUriAsync(uriToSave);
using (IRandomAccessStream stream =
    await file.OpenAsync(FileAccessMode.ReadWrite))
{
    // write the JSON file
     using (DataWriter textWriter = new DataWriter(stream))
    {
        textWriter.WriteString(result);
          await textWriter.StoreAsync();
    }
}

But during executing code StorageFile fileToWrite = await StorageFile.GetFileFromApplicationUriAsync(uriToSave); got exception System.ArgumentException
During debagging got next Uri

Question - why i got such exception and if I'm wrong - how to save file in windows store app in required directory?
Also look MSDN sample for writing data to file, and use code like in tutorial but got System.UnauthorizedAccessException:
StorageFile sampleFile = await folder.CreateFileAsync("EventsData.json", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, result);

Why Access denied or I missing something?

A: You cannot write to the install directory without explicit permission from the user.
Here is the protocol instead:

*

*At first startup, check to see if there is a file in the local data folder (ApplicationDataContainer), if not, read in the file from the install directory.

*Write out a copy of the file to the local app data folder (Check out guides on ApplicationDataContainer for more info there)

*Edit this file freely.


text:
Q: N1QL slow join despite of indexes I am experimenting with CB for a uni project. I've loaded a bucket called tweets with 5000000 docs  and a bucket called users with 2000000 docs.
Each Tweet-doc has the same schema, with some attributes like "is_retweet" ("true" or "false"), "text" (text of the tweet), "timestamp" and "user_id" which is the id of the user who tweeted it.
Each User has and id and may have a list of followers (id of other users).
I would like to create a query that retrieve the 20 most seen tweets. This means that I look for those tweets which have the field "is_retweet" = "true" and a user with a lot of followers.
I have created indexes on the ARRAY_LENGTH of followers, on the attribute "is_retweet" and on "user_id" field:
CREATE INDEX `idx_followers_length` ON `users`(array_length(`followers`)) WHERE (100 < array_length(`followers`))

CREATE INDEX `idx_retweet` ON `tweets`(`is_retweet`) WHERE (`is_retweet` = "true")

CREATE INDEX `idx_users_on_tweets` ON `tweets`(`user_id`)

Thanks to those indexes, the execution of partial queries is quite fast. "Partial Queries" are:

*

*Get the 20 most followed users, based on the length of "followers" array
SELECT id, ARRAY_LENGTH(followers) AS followers_num
FROM users
WHERE ARRAY_LENGTH(followers) > 100
ORDER BY ARRAY_LENGTH(followers) DESC
LIMIT 20

*Select the text and the timestamp (month/day) of tweets that have been retweeted
SELECT DATE_PART_STR(MILLIS_TO_STR(TONUMBER(timestamp)), 'month') AS month,
       DATE_PART_STR(MILLIS_TO_STR(TONUMBER(timestamp)), 'day') AS day,
       text
FROM tweets
WHERE is_retweet = "true"

The problem is that when I try the join, the query just runs forever (more than 30 mins). Here is the query (maybe it is wrong) and the explain (the query uses all the indexes mentioned above):
SELECT u.id,
       u.followers_num,
       DATE_PART_STR(MILLIS_TO_STR(TONUMBER(t.timestamp)), 'month') AS month,
       DATE_PART_STR(MILLIS_TO_STR(TONUMBER(t.timestamp)), 'day') AS day,
       t.text
FROM tweets AS t
JOIN (SELECT id, ARRAY_LENGTH(followers) AS followers_num
      FROM users
      WHERE ARRAY_LENGTH(followers) > 100)
      AS u ON t.user_id = META(u).id
WHERE t.is_retweet = "true"
ORDER BY u.followers_num DESC
LIMIT 20

{
    "#operator": "Sequence",
    "~children": [
        {
            "#operator": "Sequence",
            "~children": [
                {
                    "#operator": "IntersectScan",
                    "scans": [
                        {
                            "#operator": "IndexScan3",
                            "as": "t",
                            "index": "idx_retweet",
                            "index_id": "437d590a2e220ed4",
                            "index_projection": {
                                "primary_key": true
                            },
                            "keyspace": "tweets",
                            "namespace": "default",
                            "spans": [
                                {
                                    "exact": true,
                                    "range": [
                                        {
                                            "high": "\"true\"",
                                            "inclusion": 3,
                                            "low": "\"true\""
                                        }
                                    ]
                                }
                            ],
                            "using": "gsi"
                        },
                        {
                            "#operator": "IndexScan3",
                            "as": "t",
                            "index": "idx_users_on_tweets",
                            "index_id": "c93f6f0be887553",
                            "index_projection": {
                                "primary_key": true
                            },
                            "keyspace": "tweets",
                            "namespace": "default",
                            "spans": [
                                {
                                    "exact": true,
                                    "range": [
                                        {
                                            "inclusion": 0,
                                            "low": "null"
                                        }
                                    ]
                                }
                            ],
                            "using": "gsi"
                        }
                    ]
                },
                {
                    "#operator": "Fetch",
                    "as": "t",
                    "keyspace": "tweets",
                    "namespace": "default"
                },
                {
                    "#operator": "Parallel",
                    "~child": {
                        "#operator": "Sequence",
                        "~children": [
                            {
                                "#operator": "NestedLoopJoin",
                                "alias": "u",
                                "on_clause": "((`t`.`user_id`) = (meta(`u`).`id`))",
                                "~child": {
                                    "#operator": "Sequence",
                                    "~children": [
                                        {
                                            "#operator": "Sequence",
                                            "~children": [
                                                {
                                                    "#operator": "IndexScan3",
                                                    "index": "idx_followers_length_2",
                                                    "index_id": "b5cc45b51847b40f",
                                                    "index_projection": {
                                                        "primary_key": true
                                                    },
                                                    "keyspace": "users",
                                                    "namespace": "default",
                                                    "spans": [
                                                        {
                                                            "exact": true,
                                                            "range": [
                                                                {
                                                                    "inclusion": 0,
                                                                    "low": "100"
                                                                }
                                                            ]
                                                        }
                                                    ],
                                                    "using": "gsi"
                                                },
                                                {
                                                    "#operator": "Fetch",
                                                    "keyspace": "users",
                                                    "namespace": "default"
                                                },
                                                {
                                                    "#operator": "Parallel",
                                                    "~child": {
                                                        "#operator": "Sequence",
                                                        "~children": [
                                                            {
                                                                "#operator": "Filter",
                                                                "condition": "(100 < array_length((`users`.`followers`)))"
                                                            },
                                                            {
                                                                "#operator": "InitialProject",
                                                                "result_terms": [
                                                                    {
                                                                        "expr": "(`users`.`id`)"
                                                                    },
                                                                    {
                                                                        "as": "followers_num",
                                                                        "expr": "array_length((`users`.`followers`))"
                                                                    }
                                                                ]
                                                            },
                                                            {
                                                                "#operator": "FinalProject"
                                                            }
                                                        ]
                                                    }
                                                }
                                            ]
                                        },
                                        {
                                            "#operator": "Alias",
                                            "as": "u"
                                        }
                                    ]
                                }
                            },
                            {
                                "#operator": "Filter",
                                "condition": "((`t`.`is_retweet`) = \"true\")"
                            },
                            {
                                "#operator": "InitialProject",
                                "result_terms": [
                                    {
                                        "expr": "(`u`.`id`)"
                                    },
                                    {
                                        "expr": "(`u`.`followers_num`)"
                                    },
                                    {
                                        "as": "month",
                                        "expr": "date_part_str(millis_to_str(to_number((`t`.`timestamp`))), \"month\")"
                                    },
                                    {
                                        "as": "day",
                                        "expr": "date_part_str(millis_to_str(to_number((`t`.`timestamp`))), \"day\")"
                                    },
                                    {
                                        "expr": "(`t`.`text`)"
                                    }
                                ]
                            }
                        ]
                    }
                }
            ]
        },
        {
            "#operator": "Order",
            "limit": "20",
            "sort_terms": [
                {
                    "desc": true,
                    "expr": "(`u`.`followers_num`)"
                }
            ]
        },
        {
            "#operator": "Limit",
            "expr": "20"
        },
        {
            "#operator": "FinalProject"
        }
    ]
}

A: N1QL Joins are LEFT to RIGHT. And you have Pagination query with ORDER BY, which must produce all possible values even though you need 20 items.
CREATE INDEX `ix1` ON `users`(array_length(`followers`) DESC) WHERE (100 < array_length(`followers`));
CREATE INDEX `ix2` ON `tweets`(user_id, timestamp, text) WHERE (`is_retweet` = "true");
SELECT u.id,
       u.followers_num,
       DATE_PART_STR(MILLIS_TO_STR(TONUMBER(t.timestamp)), 'month') AS month,
       DATE_PART_STR(MILLIS_TO_STR(TONUMBER(t.timestamp)), 'day') AS day,
       t.text
FROM (SELECT META().id, ARRAY_LENGTH(followers) AS followers_num
      FROM users
      WHERE ARRAY_LENGTH(followers) > 100
      ORDER BY ARRAY_LENGTH(followers) DESC) AS u
JOIN tweets AS t ON u.id = t.user_id
WHERE t.is_retweet = "true"
LIMIT 20;

Subquery uses covering index with index order (avoids sort) and produces the the highest followers in reverse order. Then it JOINS the tweet produces 20 tweets.
NOTE: This produces 20 retweets. JOIN can produce 1 to many. It can't be top 20 followers. If you need that, based on your needs you might need GROUP BY or use NEST (Example 17 https://blog.couchbase.com/ansi-join-support-n1ql/). In CB 7.0 you can use generic correlated subquery.

A: I tried the index advisor in my local instance of Couchbase Server 7, with the indexes you already created. It recommended another index:
CREATE INDEX adv_is_retweet_user_id ON `tweets`(`is_retweet`,`user_id`)

So, you might want to give that a try. (I don't have your dataset, so I don't know if it will help, or how much it will help).
But, if you plan to create more complex queries on this same dataset, especially adhoc queries, you may want to consider using the Analytics service. It supports N1QL and indexing as well, but it will usually give you pretty good performance without having to create indexes up front.


text:
Q: how to check if an if statement inside of a for loop is never used? i created a Method to check if users location are close to a building.
Therefore i created the following method
private void whereAreYou(final List<location> locations) {
    loadingprogress.setVisibility(View.INVISIBLE);

    for (int i = 0; i < this.cities.size(); i++) {
        final location loc= locations.get(i);
        Location loc1 = mLastLocation;
        Location loc2 = new Location("");
        loc2.setLatitude(loc.getLat());
        loc2.setLongitude(loc.getLng());

        float distanceInMeters = loc1.distanceTo(loc2);
        int distanceInKm = (int) (distanceInMeters / 1000);

        if (distanceInKm <= Integer.parseInt(currentclub.getRadius())) {
            uploadInformationToUserProfile(loc.getName());
        }
    }
}

Now I have to check if a value was within the if statements or not, because then another method must be called, but only if all values do not fit

A: You could add a flag that is set to false initially, and within the if statement action code set the flag to true.  Following that section of code print it to the console.
Then iterate through the appropriate test cases and check if it ever appears as true.

A: Add a boolean flag.
private void whereAreYou(final List<location> locations) {
    loadingprogress.setVisibility(View.INVISIBLE);

    boolean locationMatchFound = false; //boolean flag

    for (int i = 0; i < this.cities.size(); i++) {
        final location loc= locations.get(i);
        Location loc1 = mLastLocation;
        Location loc2 = new Location("");
        loc2.setLatitude(loc.getLat());
        loc2.setLongitude(loc.getLng());

        float distanceInMeters = loc1.distanceTo(loc2);
        int distanceInKm = (int) (distanceInMeters / 1000);
        if (distanceInKm <= Integer.parseInt(currentclub.getRadius())) {
            locationMatchFound = true; //boolean flag set to true if location found

            uploadInformationToUserProfile(loc.getName());
        }
    }
    if (!locationMatchFound){
        //Call your other method.
    }
}


text:
Q: How to sort multiple wordpress custom field values? Display posts with 'Product' type ordered by 'Price' custom field:
$query = new WP_Query(
                      array ( 'post_type' => 'product',
                              'orderby' => 'meta_value',
                              'meta_key' => 'price' )
                     );

Which code should I use if also want to order by 'Size'?
Another example on which I need multiple sort on custom fields:
Display posts with 'Event' type ordered by 'Start_Hour' and then by 'Start_Minute'.

A: Thanks to Bainternet I found the solution:
function orderbyreplace($orderby) {
    return str_replace('menu_order', 'mt1.meta_value, mt2.meta_value', $orderby);
}

and...
$args = array(
  'post_type'=>'Events',
  'orderby' => 'menu_order',
  'order' => 'ASC',
  'meta_query' => array(
        array(
            'key' => 'Start_Hour',
            'value' => '',
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'Start_Minute',
            'value' => '',
            'compare' => 'LIKE'
        )
    )
);

add_filter('posts_orderby','orderbyreplace');
$loop = new WP_Query( $args );
remove_filter('posts_orderby','orderbyreplace');

A: I think this changed slightly in Wordpress 3.7.
I had to change
return str_replace('menu_order', 'mt2.meta_value, mt1.meta_value', $orderby);

into
return str_replace('wp_posts.menu_order', 'mt2.meta_value, mt1.meta_value', $orderby);

Thanks for the initial solution!  [Edited]

A: Here's an example of using more than one meta_key and orderby that I believe should work:
$params = array(
'post_type' => 'product',
'meta_query' => array(
    array(
            'key' => 'price',
            'value' => '',
            'compare' => 'LIKE'
    ),
    array(
            'key' => 'size',
            'value' => '',
            'compare' => 'LIKE'
    )
),
'orderby' => 'price size',
'order' => 'ASC'
);
$query = new WP_Query;
$resulting_obj = $query->query($params);

You'll need to play with the meta_query items a bit more, especially the 'value' parameter. Please have a good look at http://codex.wordpress.org/Class_Reference/WP_Query in the 'Custom Field Parameters' section.

A: You don't need any filter or hooks to sort multiple custom fields, if your one of custom field is meta_key and other one is normal column of table, than use these parameters/arguments in your query.
'meta_key' => 'KEY_NAME',
'orderby' => 'meta_value_num SECOND_COLUMN_NAME',
'order' => 'ASC' or 'order' => 'DESC'

Here the order of meta_value_num and SECOND_COLUMN_NAME matter, you may see different-2 result based on the order.


text:
Q: Como criar um relatório no JasperReports (Jasper Studio) que possua colunas dinamicas? Segue a tabela:

Como voces podem ver, as vezes eu posso ter 1 test, 2 test, 3 tests ou as vezes nenhum. Tudo isso ia depender do que eu pudesse trazer do banco. Como eu posso fazer isso no JasperReports?

A: Olá, hoje mesmo fiz um relatório com colunas dinâmicas.
Só que elas não são tão dinâmicas assim, você vai criar seu relatório, se for nele onde você vai exibir os dados trazidos do banco, você vai nas "properties>advanced>column count" que vai estar marcado com valor 1, e seta o numero de colunas que desejar, marca "print order" de vertical para horizontal, neste caso de tabelas, você pode mandar exibir em uma lista, ai suas colunas ficarão certinhas de acordo com o numero de linhas de cada coluna, caso for usar sub-relatório, o processo é o mesmo. Espero ter ajudado! Dúvidas pergunte! Abraço!


text:
Q: How to avoid temporary file creation during FTP using spring integration I am using spring-integration version 2.0.3  to  send files to remote system via FTP with spring-integration-ftp outbound-channel-adapter.  By default, during FTP the file will be created with an extenstion ".writing"  and once the copying finished, it will be renamed by removing the ".writing" suffix.
But there is no permission to rename the file, once it is copied to remote location.  in the latest Spring integration reference I fond that the peroperty use-temporary-file-name can be set to false to avoid using temporary file naming during FTP.
Is there any way to achieve the functionality with Spring integration ver 2.0.x ?

A: No; this was added in 2.1.x; I would recommend upgrading to 2.2.6.
Be aware that if you transfer a file without a suffix, there is a danger that the receiving application might see the file before it is completely written (that is why the default is the way it is).


text:
Q: Errors in AlertDialog I am follow https://codingwithjoe.com/flutter-navigation-how-to-prevent-navigation/ for show AlertDialog but have two error:

*

*When tap away from dialog box (dismiss barrier without tap any button) get runtime error:

  Dart Error: Unhandled exception:Failed assertion: boolean expression must not be null

2. child: new AlertDialog( 'child is deprecated and shouldn't be used'.
Code:
Future<bool> _exitApp(BuildContext context) {
  return showDialog(
        context: context,
        child: new AlertDialog(
          title: new Text('Do you want to exit this application?'),
          content: new Text('We hate to see you leave...'),
          actions: <Widget>[
            new FlatButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: new Text('No'),
            ),
            new FlatButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: new Text('Yes'),
            ),
          ],
        ),
      ) ??
      false;
}

Stacktrace:
#0      ModalRoute.willPop (package:flutter/src/widgets/routes.dart)
<asynchronous suspension>
#1      NavigatorState.maybePop (package:flutter/src/widgets/navigator.dart:1783:57)
<asynchronous suspension>
#2      Navigator.maybePop (package:flutter/src/widgets/navigator.dart:1133:34)
#3      BackButton.build.<anonymous closure> (package:flutter/src/material/back_button.dart:91:19)
#4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
#5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
#6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
#7      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
#8      TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:204:7)
#9      GestureArenaManager.sweep (package:flutter/src/g<…>

Thanks!

A: Make your method async and use the await keyword :
Future<bool> _exitApp(BuildContext context) async {
  return await showDialog(  ...

If you don't want to dismiss your Dialog when you tap outside of the container, set barrierDismissible to false.
showDialog(barrierDismissible: false, ...


text:
Q: Finding the Least Common Multiple(LCM) of two integer in C I am trying to use the following code to find the LCM of two integers in C. I have no idea why the code will show me the maximum number of the two integers instead of the LCM of them. Have I do something wrong?
#include<stdio.h>
int main(){
    int num1, num2;
    printf("Input your number 1:");
    scanf("%d", &num1);
    printf("Input your number 2:");
    scanf("%d", &num2);
    //find max and main
    int max = num1, min = num2;
    if(num1 < num2){
        max = num2;
        min = num1;
    }
    int k = 1, LCM;
    do{
        LCM = max*k;
        k++;
    }while(LCM%min == 0);
    printf("LCM of %d and %d is %d", num1 ,num2, LCM);
}

Here is the output of the program:
Input your number 1:5
Input your number 2:3
LCM of 5 and 3 is 5
Process returned 0 (0x0)   execution time : 1.735 s
Press any key to continue.

A: while(LCM%min == 0) is checking if LCM is divisible by min and if so the loop continues.
You should use while(LCM%min != 0) instead to find the first multiple of max that is divisible by min and exit the loop when one is found.


text:
Q: Parse error dado ao verificar variáveis com a função empty() Estou com um probleminha no meu PHP quando passo mais de uma variável para ele verificar separado por virgula ele gera um parse error.
Olhem meu código abaixo:
if (isset($_POST['btnCriaTempo'])){

  $ordem         = trim($_POST['ordem']);
  $timeHours     = trim($_POST['tempoHora']);
  $timeMinutes   = trim($_POST['tempoMinuto']);
  $timeSeconds   = trim($_POST['tempoSegundo']);
  $visao         = trim($_POST['visibilidade']);
  $momentHours   = trim($_POST['momentoHora']);
  $momentMinutes = trim($_POST['momentoMinuto']);
  $momentSeconds = trim($_POST['momentoSegundo']);

  if (!empty($ordem, $visao)){ /*Esta é a linha 41*/

    $sqlCriaTempo = "INSERT INTO sv_tempo (tempoTotal, tempoVisao, tempoMomento, tempoOrdem)"
                    ." values (:tempoTotal, :tempoVisao, :tempoMomento, :tempoOrdem)";

    $queryCriaTempo = $conecta->prepare();
  }
}

Dá esse erro:
Parse error: syntax error, unexpected ',', expecting ')'
in C:\xampp\htdocs\newcemp\admin\create\tempo.php on line 41

Sou eu que estou errando a sintaxe mesmo? Quando coloco só um roda normal.

A: Sim, a função empty só aceita um parâmetro. Veja o manual da função empty() no site oficial.
bool empty ( mixed $var )

Este mixed significa que aceita vários tipos de dados para o parâmetro $var.
Lá tem alguns exemplos de como fazer funções derivadas para verificar vários itens ao mesmo tempo. Talvez não tenha exatamente para o que você quer, mas é bem fácil fazer uma função que aceite vários parâmetros e verifique se todos estão vazios. Mas já é outro problema.
Você deve mudar o if para:
if (!empty($ordem) && !empty($visao)) {

Coloquei no Github para futura referência.

A: O teu problema é que a função empty() só aceita um argumento, ou seja, só podes verificar uma variável de cada vez.
Uma ideia é criar uma função que receba múltiplos argumentos que por cada argumento recebido vai chamar a função empty() e realizar a verificação:
function mempty() {

  foreach (func_get_args() as $arg) {

    if (empty($arg)) {
      continue;
    } else {
      return false;
    }
  }
  return true;
}

Créditos para a solução dados ao utilizador imkingdavid do StackOverflow nesta resposta.

A alternativa é validar variável a variável:
if (!empty($ordem) && !empty($visao)) {
 ...
}


text:
Q: PyQGIS Dialog Plugin not resetting I have written a PostGIS search plugin that works pretty well, except two things that I just cannot figure out a solution
1) When the dialog closes and then is reopened the previous query is still in the lineEdit and tableView. A tableView only seems to have clearSpans() however this is not clearing out the contents. I have tried .close(), .clear(), clearContents() none of which work or none are valid for a tableView.
I think the issue is I am loading the data from the database into a model via QSQLQueryModel.
2) When the user queries the database, selects a point the map moves to the location. If the user then opens the plugin again and queries the database again and selects a record from the tableView a point is added as a new memory layer, however it has the same XY coordinate as the first query.
I think the two problems are linked. Because number 1, the dialog isn't resetting properly, then the selected row from the table view gets confused.
I am so close and I think it will be a very useful plugin for the QGIS, so I hope someone can help. This might not be the best method to achieve this but having read the cookbook and the PyQGIS Programmers Guide it is the only way that may work
Thanks in advance
Full code can be seen on the github page here - https://github.com/tjmgis/PostGISSearch
This is the important code from the main python script
def cellClicked(self):
    iface.mapCanvas().refresh()

    index = self.dlg.tableView.currentIndex()

    rownumber = index.row()

    hmodel = self.dlg.tableView.horizontalHeader().model()
    for column in range(hmodel.columnCount()):
        if hmodel.headerData(column, Qt.Horizontal) == "x":
            xcolumn = column

        elif hmodel.headerData(column, Qt.Horizontal) == "y":
            ycolumn = column

        elif hmodel.headerData(column, Qt.Horizontal) == self.postgisdisplaycolumn:
            descriptioncolumn = column

    self.x = self.projectModel.index(rownumber, xcolumn).data()
    self.y = self.projectModel.index(rownumber, ycolumn).data()
    self.description = self.projectModel.index(rownumber, descriptioncolumn).data()

    self.pinLayer =  QgsVectorLayer(
          "Point?field=Description:string(120)&field=X_Coordinate:double&field=Y_Coordinate:double&index=yes",
          self.description,
          "memory")
    self.provider = self.pinLayer.dataProvider()
    QgsMapLayerRegistry.instance().addMapLayer(self.pinLayer)

    feature = QgsFeature()
    feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(self.x,self.y)))
    if QGis.QGIS_VERSION_INT > 10800:
        feature.setAttributes([self.description, self.x, self.y])
        self.pinLayer.startEditing()
        self.pinLayer.addFeature(feature, True)
        self.pinLayer.commitChanges()
    else:
        feature.setAttributeMap( {0 : QVariant(self.description),
            1 : QVariant(self.x),
            2 : QVariant(self.y)})
        self.provider.addFeatures([feature])
        self.pinLayer.updateExtents()
    #QMessageBox.information(self.iface.mainWindow(), "Feature/field count", "%s / %s" % (str(self.provider.featureCount()), str(self.provider.fieldCount())))
    #self.pinLayer.reload()
    #self.pinLayer.setCacheImage(None)
    self.pinLayer.triggerRepaint()

    iface.mapCanvas().setExtent(QgsRectangle(self.x,self.y,self.x,self.y))
    iface.mapCanvas().zoomScale(10000)
    iface.mapCanvas().refresh()

    self.db.close()
    self.db.removeDatabase('QPSQL')

    self.dlg.close()

def addPostGISLayer(self, string):

    if len(string) > 4:
        uri = QgsDataSourceURI()
        # set host name, port, database name, username and password
        uri.setConnection(self.postgishost, self.postgisport, self.postgisdatabase, self.postgisusername, self.postgispassword)
        # set database schema, table name, geometry column and optionaly
        # subset (WHERE clause)
        if self.searchmethod == 'SQL':
            querystring = ("%" + string + "%")
            sql = "select %s.*, ST_X(%s) as x, ST_Y(%s) as y from %s.%s WHERE LOWER(%s) LIKE LOWER('%s') LIMIT 1000"%(self.postgistable, self.postgisgeomname, self.postgisgeomname, self.postgisschema, self.postgistable, self.postgissearchcolumn, querystring)

        elif self.searchmethod == 'FTS':
            sql = """SELECT %s.*, ST_X(%s) as x, ST_Y(%s) as y FROM %s.%s WHERE %s @@ plainto_tsquery('english', '%s') LIMIT 100"""%(self.postgistable, self.postgisgeomname, self.postgisgeomname, self.postgisschema, self.postgistable, self.postgissearchcolumn, string)

        else:
            iface.messageBar().pushMessage("Error", "Wrong search method declared in config file", level=QgsMessageBar.CRITICAL, duration=5)

        self.db = QSqlDatabase.addDatabase('QPSQL')
        # check to see if it is valid
        if self.db.isValid():
            #iface.messageBar().pushMessage("Info", "Successfully connected to database", level=QgsMessageBar.INFO, duration=3)
            self.db.setHostName(uri.host())
            self.db.setDatabaseName(uri.database())
            self.db.setPort(int(uri.port()))
            self.db.setUserName(uri.username())
            self.db.setPassword(uri.password())
            # open (create) the connection
            if self.db.open():
                self.projectModel = QSqlQueryModel()
                self.projectModel.setQuery(sql,self.db)
                self.dlg.tableView.setModel(self.projectModel)
                self.dlg.tableView.resizeColumnsToContents()
                self.dlg.tableView.selectionModel().currentChanged.connect(self.cellClicked)
            else:
                iface.messageBar().pushMessage("Error", "Cannot open search on the database", level=QgsMessageBar.CRITICAL, duration=5)

        else:
            iface.messageBar().pushMessage("Error", "DB not valid", level=QgsMessageBar.CRITICAL, duration=5)

# run method that performs all the real work
def run(self):
    # show the dialog
    self.dlg.show()
    # Run the dialog event loop
    result = self.dlg.exec_()
    # See if OK was pressed
    if result == 1:
        # do something useful (delete the line containing pass and
        # substitute with your code)
        pass