text:
Q: Image appears on the wrong window on Tkinter I'm creating a mysql/tkinter project and im trying to use a picture as bg for one of the windows. but instead of appearing on the new window it opens in the main window instead. I want the image to open on the new window that im currently on. the menu() by itself works how I intend it to but with the whole program it doesn't . any ideas on how I can fix this?
def menu():
    root = tk.Tk()
    root.title("DBMS Menu Page")
    bgimage= ImageTk.PhotoImage(Image.open('960x0.jpg'))
    imglabel= Label(image=bgimage)
    imglabel.img=bgimage
    imglabel.pack()

    lblmenu = tk.Label(root,text ="MENU", font=('Times New Roman',28,'bold'))
    lblmenu.place(x = 220, y = 60)
    btninsert = tk.Button(root, text ="Insert",
                    fg ='blue',font=("Times New Roman Bold", 10))
    btninsert.place(x = 100, y = 135, width = 60)
    btnupdate = tk.Button(root, text ="Update",
                    fg ='blue',font=("Times New Roman Bold", 10))
    btnupdate.place(x = 170, y = 135, width = 60)
    btndelete = tk.Button(root, text ="Delete",
                    fg ='blue',font=("Times New Roman Bold", 10))
    btndelete.place(x = 240, y = 135, width = 60)
    btndisplay = tk.Button(root, text ="Display",
                    fg ='blue',font=("Times New Roman Bold", 10))
    btndisplay.place(x = 310, y = 135, width = 60)

def clearlogin():
    txtUser.delete(0,END)
    txtpass.delete(0,END)

def submitact():

    user = txtUser.get()
    passw = txtpass.get()
    print(f"The ID-pw entered by you is {user} {passw}")
    logintodb(user, passw)
def logintodb(user, passw):
    if passw:
        db = mys.connect(host ="localhost",
                                    user = user,
                                    password = passw,
                                    db ="1234")
        cursor = db.cursor()
    else:
        db = mys.connect(host ="localhost",
                                    user = root,
                                    database ="1234")
        cursor = db.cursor()

    # A Table in the database
    savequery = "show tables"

    try:
        cursor.execute(savequery)
        myresult = cursor.fetchall()
        print("Query Excecuted succesfully")
        messagebox.showinfo("Login ", "Login Successful")

    except:
        db.rollback()
        print("Error occured")
    menu()

root = tk.Tk()
root.geometry("250x150")
root.title("DBMS Login Page")
lbluser = tk.Label(root, text ="Username -",fg="red",font=("Times New Roman Bold", 13) )
lbluser.place(x = 10, y = 20)
txtUser = tk.Entry(root, width = 35,fg="green",font=("Times New Roman Bold", 10))
txtUser.place(x = 100, y = 20, width = 100)
lblpass = tk.Label(root, text ="Password -",fg="red",font=("Times New Roman Bold", 13))
lblpass.place(x = 10, y = 50)
txtpass = tk.Entry(root,show="*", width = 35,fg="green",font=("Times New Roman Bold", 10))
txtpass.place(x = 100, y = 50, width = 100)

submitbtn = tk.Button(root, text ="Login",
                    fg ='blue', font=("Times New Roman Bold", 15),command = submitact)
submitbtn.place(x = 30, y = 100, width = 55)
clearbtn = tk.Button(root, text ="Clear",
                    fg ='blue', font=("Times New Roman Bold", 15),command = clearlogin)
clearbtn.place(x = 130, y = 100, width = 55)
root.mainloop()

A: The first part of your function menu is the where the mistake is:
def menu():
    root = Toplevel()
    root.title("DBMS Menu Page")
    bgimage= ImageTk.PhotoImage(Image.open('960x0.jpg'))
    imglabel= Label(root,image=bgimage)
    imglabel.img=bgimage
    imglabel.pack()

You dint specify which window the image should appear at and adding it as an argument, solves the issue and saying root as Toplevel() is a better practice rather than calling Tk() which is usually just used for the main parent window only


text:
Q: Python declaration order: classes or functions first? Is there any preferred order when declaring multiple functions and classes in the same python file? Should functions or classes be declared first? What are the best practices?
PEP8 does not seems to give any recommendation

A: Generally, there is no preferred order. Depending on the program, a order can be needed:

*

*You can decorate classes with functions. Then the decorator function must be defined before the class.

*OTOH, you can decorate functions with classes. Then the decorator class must be defined before the function.

*You can have classes be assigned class attributes which are determined by calling a function. Again, this function must be defined before the class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: syntax error near unexpected token `newline' in .bashrc I'm trying to add script
function proxyset() {
        proxy_enabled=true

        NO_PROXY_DOMAINS=".abc.com,"
        LOCAL_ADDRESSES="localhost"

        USER=<USER_ID>
        PASSWORD=<URL_ENCODED_PASSWORD>
        SERVER=httppxgot.abc.com
        PORT=8080

# Disable HTTP proxy
function proxyunset() {
        unset NO_PROXY
        echo 'Im unset!'
}

but when I'm opening cygwin terminal its showing
syntax error near unexpected token `newline'
-bash: /cygdrive/c/Users/XXX/.bashrc: line 214: `        USER=<USER_ID>'

whats is wrong with script

A: As it says, bash can not handle the line 214 in which the USER variable is set to
I don't know what you want to fill in there but the signs '<' and '>' are used in bash for redirecting output therefore the variable cannot be set.
Example:
bash-4.4$ USER=<USER_ID>
bash: syntax error near unexpected token `newline'

bash-4.4$ USER=test<
bash: syntax error near unexpected token `newline'

bash-4.4$ USER=test
bash-4.4$ echo $USER
test

If you want to get your actual username or id either use the command id or look with export for Environment Variables which already exists.
For more information about I/O redirection have a look at the docs: https://www.tldp.org/LDP/abs/html/io-redirection.html


text:
Q: Imagick Resize, Center, and Sparse Fill problems My end goal here is to resize the input image to 100px width, 125px height. Some of the input images are a different Aspect Ratio, so I wish for them to be in a 100x125 container with the background sparse filled from their edge color.
Ok, so this works for the basic resize:
$image = new Imagick($imgFile);
$image->resizeImage(100,0, Imagick::FILTER_LANCZOS, 1, false);
$image->writeImage("$Dir/$game.png");
header("Content-type: ".$image->getImageFormat());
echo $image;
$image->clear();
$image->destroy();

However I've been searching for hours, and I cannot find a simple "This is how you center an image in a canvas" bit for PHP's Imagick library. Everything is for the actual ImageMagick convert application, which is not really what I'm after. I've tried compositing the resized image into an empty newImage with the set width and height, but it just seems to overwrite the dimensions regardless of the composite type, setting the Gravity to center and then the extent to 100x125 has no effect ( It always sits at 0,0, and trying to set the y offset to ((125-imageheight)/2) resulted in an offset that was way more than it should have been )
Edit:
    $imageOutput = new Imagick();
    $image = new Imagick($imgFile);
    $image->resizeImage(100,0, Imagick::FILTER_LANCZOS, 1, false);
    $imageOutput->newImage(100, 125, new ImagickPixel('black'));
    $imageOutput->compositeImage($image, Imagick::COMPOSITE_ADD, 0, ((125 - $image->getImageHeight()))/2 );
    $imageOutput->setImageFormat('png');
    $imageOutput->writeImage("$Dir/$game.png");
    header("Content-type: ".$imageOutput->getImageFormat());
    echo $imageOutput;
    $image->clear();
    $image->destroy();

So I got my centering working, gravity apparently has no effect on actual images.
I have absolutely no idea where I would even begin to try and recreate a command line edge-in sparse fill in PHP with the library.

A: I ended up using a combination of Imagick and shell calls to convert itself, I'll eventually rewrite it to use entirely shell calls. I also changed my dimensions, here's the code:
    $imageOutput = new Imagick(); // This will hold the resized image
    $image = new Imagick($imgFile); // Open image file
    $image->resizeImage(120,0, Imagick::FILTER_LANCZOS, 1, false); // Resize it width-wise
    $imageOutput->newImage(120, 150, "none"); // Make the container with transparency
    $imageOutput->compositeImage($image, Imagick::COMPOSITE_ADD, 0, ((150 - $image->getImageHeight())/2) ); // Center the resized image inside of the container
    $imageOutput->setImageFormat('png'); // Set the format to maintain transparency
    $imageOutput->writeImage("$Dir/$game.temp.png"); // Write it to disk
    $image->clear(); //cleanup -v
    $image->destroy();
    $imageOutput->clear();
    $imageOutput->destroy();
    //Now the real fun
    $edge = shell_exec("convert $Dir/$game.temp.png -channel A -morphology EdgeIn Diamond $Dir/$game.temp.edge.png"); // Get the edges of the box, create an image from just that
    $shepards = shell_exec("convert $Dir/$game.temp.edge.png txt:- | sed '1d; / 0) /d; s/:.* /,/;'"); // get the pixel coordinates
    $final = shell_exec("convert $Dir/$game.temp.edge.png -alpha off -sparse-color shepards '$shepards' png:- | convert png:- $Dir/$game.temp.png -quality 90 -composite $Dir/$game.jpg"); // Sparse fill the entire container using the edge of the other image as shepards , then composite that on top of this new image
    unlink("$Dir/$game.temp.png"); // cleanup temp files
    unlink("$Dir/$game.temp.edge.png");
    set_header_and_serve("$Dir/$game.jpg"); // serve the newly created file


text:
Q: How pip install pylzma on windows 7 x64 , python 2.7 I assumed this should be working out of the box, but ...
i've pasted pip.log on pastbin
the last few lines of error message is
e:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -DWITH_COMPAT=1 -DCOMPRESS_MF_MT=1 -Isrc/sdk -IC:\Python27\include -IC:\Python27\PC /Tcsrc\7zip\C\AesOpt.c /Fobuild\temp.win-amd64-2.7\Release\src\7zip\C\AesOpt.obj /MT

cl : Command line warning D9025 : overriding '/MD' with '/MT'

AesOpt.c

src\7zip\C\AesOpt.c(14) : fatal error C1083: Cannot open include file: 'wmmintrin.h': No such file or directory

error: command '"e:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\cl.exe"' failed with exit status 2

via google search i found that wmmintrin.h is one of the headers comes with vc 10.0, i've installed visual studio 2010 ( contains vc 10.0 ), what i need to do is copy this file over ?
isn't pip install something supposed to be simple and painless ?
edit: i tried to copy this file into vc9's include path, but came across several different errors
i have read this Installing/compiling pylzma (lzma python binding)
it seems author has fix what in the setup.py and .c file already. i saw the /MANIFEST flag and  Py_BEGIN_ALLOW_THREADS and Sha256_Init(&sha) have been moved after variable declarations:
edit2: it seems vs2008(vc9) doesn't support the compiler intrinsics as seen in the error log, after i installed vs2008 sp1, it compiles without any error ... see log

A: I would strongly recommend installing via a windows binary. It can be found at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pylzma. This way, you don't have to worry about the stupid make errors. Trust me, you'ld waste time & energy & yet you wouldn't reap any benefits by trying to make the Visual Studio errors go away. But, if you do get success that way, please post the relevant answer here!


text:
Q: Is there any way to write tray switch and Duplex command in Postscript file converted using Ghostscript I have converted PDF to Postscript using ghostscript. The output generated is in encrypted format. I want to add Tray Switch and Duplex Printing command inside the Postscript so that printer is able to follow those. Is there any way to achieve?
Following is the command i am using to convert PS
C:\Program Files\gs\gs9.22\bin\gswin64 -sDEVICE=pdfwrite -dCompressFonts=true -o D:\output\OutputFile.ps D:\output\InputFile.pdf

A: First thing you shoudl do is use current code; the current version is 9.50. IIRC this version, by default, doesn't write compressed (not encrypted) output.
In addition that version has 2 controls, PSDocOptions and PSPageOptions, documented here which already allow you to do what you want. You will have to understand the PostScript syntax in order to use these.


text:
Q: How to use ng-repeat in HTML page using AngularJS? I need five independent fields based on the actual price and offer i need to find final price
This is my sample html code
addproduct.html

         {{a}}
         <input type="text" class="form-control" placeholder="0" style="width:70%; line-height:1.5" ng-model="product.pModel">
         <input type="text" class="form-control" placeholder="0" style="width:70%; line-height:1.5" ng-model="product.actualPrice" max="2" limit-decimal>
         <input type="text" class="form-control" placeholder="0" style="width:50%; line-height:1.5" ng-model="product.offer" numbers-only>

                  <input type="checkbox" id="inlineCheckbox" value="option" ng-change="product.availablity = data.check ? '' : 0" ng-model="data.check"> Unlimited

        <input class="form-control" type="text" id="availablity" name="availablity" ng-disabled="data.check0" ng-model="product.availablity" >

How can i save data in json format using angularjs
When I save the submit button I need the output as
script.json
    product : [
            {
                "pModel" : "50gm",
                "actualPrice" : "250",
                "offer" : 0,
                "availablity" : "0"
            },
            {
                "pModel" : "50gm",
                "actualPrice" : "250",
                "offer" : 0,
                "availablity" : "0"
            }
                .....upto 5 fields
            ]

In here when I am entering any one of the field it will affect entire field

A: This should help you to figure it out.
Your product variable is an array, so you should access it like it's array, not as object - product[$index].fieldName


text:
Q: Can't receive CONNACK by using MQTT protocol to connect to IBM Iot foundation I have used my device to connect to IBM Iot Foundation, as I know, there are two ways to establish the connection: quickstart and the registered device. firstly, I tried to connect to the quickstart. (quickstart.messaging.internetofthings.ibmcloud.com)  I downloaded the C/C++ MQTT Embedded client library from paho.(http://www.eclipse.org/paho/) the socket has successfully established and there is no wrong in the code, buf after I established the mqttconnect, I can't receive the response CONNACK and it directly goto exit. what may cause this problem?
len = MQTTSerialize_connect((unsigned char*)buf, buflen, &data);
rc=transport_sendPacketBuffer(mysock,buf,len);
/****wait for connack***/
if (MQTTPacket_read(buf, buflen, transport_getdata) == CONNACK)
{
    unsigned char sessionPresent, connack_rc;
    printf("receive connack\n");// can't print this setence.
    if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, buf, buflen) != 1 || connack_rc != 0)
    {
        printf("Unable to connect, return code %d\n", connack_rc);
        goto exit;
    }
}
else
    goto exit;

topicString.cstring = "iot-2/evt/status/fmt/json";
len += MQTTSerialize_publish((unsigned char *)(buf + len), buflen - len, 0, 0, 0, 0, topicString, (unsigned char *)payload, payloadlen);
    len += MQTTSerialize_disconnect((unsigned char *)(buf + len), buflen - len);
rc=transport_sendPacketBuffer(mysock,buf,len);

if (rc == len)
    printf("Successfully published\n");
else
    printf("Publish failed\n");
exit:
   printf("close socket.\n");
   transport_close(mysock);


text:
Q: Bytecopy of Float array into Byte buffer creates hard fault (C - STM32F4xx/F103) Abstract:
I need to copy all elements of a struct containing a float array into a byte buffer, in order to send it out via UART. The next call of malloc after the copy operation leads (allways) to a hard fault, which is a good indicator that somewhere the memory gets corrupted, but I have no clue where this could happen (after 2 days debugging ...)
Description:
I have a nested Typtedef, that contains a float array:
#define DRV_SCALE_MAXSZ 32
#define DRV_CHANNELS 2

typedef struct {
    float x1;
    float step;
    uint8_t aSz;
    float Y[DRV_SCALE_MAXSZ];
} DRV_linscale_TDS;

typedef struct {
    DRV_linscale_TDS scale;
    uint32_t active;
} DRV_ChScale_TDS;

DRV_ChScale_TDS DRV_scale[DRV_CHANNELS] = {0,};     // Channel Scales

And I need to copy the whole content of either DRV_scale[0] or [1] into a byte buffer, in order to send it out via UART.
As a little extra complication I copy it element by element, with a copy function, that reverts the bytes of the value if necessary:
#define TXBUFSZ 255

volatile uint8_t TxBuf[TXBUFSZ] = {0,};

void FillTxBuf(uint8_t idx, uint8_t *pBo) {
    if(idx < DRV_CHANNELS) {
        volatile uint8_t *pDst = TxBuf;
        *pDst++ = DRV_SCALE_MAXSZ;
        *pDst++ = DRV_scale[idx].active;
        pDst += COM_ElementCopyU32((uint8_t*)&DRV_scale[idx].scale.x1, pDst, pBo);
        pDst += COM_ElementCopyU32((uint8_t*)&DRV_scale[idx].scale.step, pDst, pBo);
        *pDst++ = DRV_scale[idx].scale.aSz;

        uint8_t i = *pDst;
        float *pSrc = DRV_scale[idx].scale.Y;

        while(i--) {
            pDst += COM_ElementCopyU32((uint8_t*)pSrc, pDst, pBo);
            pSrc++;
        }
    }
}

Note: the code above is a shrinked version just for explanation. In reality TxBuf[TXBUFSZ] is a static preallocated byte buffer (declared extern in the header file, and defined in the c file)
The function COM_ElementCopyU32 looks like this:
uint8_t COM_ElementCopyU32(volatile uint8_t* pSrc, volatile uint8_t* pDst, uint8_t* ByteOrder) {
    // @brief   copy data from Source to Destination and revert bytes if necessary
    // @param   U8* pSrc: Pointer to data Source Buffer
    // @param   U8* pDst: Pointer to Destination Buffer
    // @param   U8 ByteOder: 0 = little endian, 1=big endian
    // @return  u16 number of copied bytes

    if(pSrc && pDst) {
        if(*ByteOrder != isBigEndian) {
            pDst[0] = pSrc[3];
            pDst[1] = pSrc[2];
            pDst[2] = pSrc[1];
            pDst[3] = pSrc[0];
        } else {
            pDst[0] = pSrc[0];
            pDst[1] = pSrc[1];
            pDst[2] = pSrc[2];
            pDst[3] = pSrc[3];
        }
    }

    return(sizeof(uint32_t));
}

The issue:
as soon as the line
pDst += COM_ElementCopyU32((uint8_t*)pSrc, pDst, pBo);

is involved, the call of FillTxBuf() leads to an hard fault with the next call of malloc(). The next malloc() comes immediately after FillTxBuf() when the CRC32 is appended to the byte stream. The general workflow is: check the incoming request, fill the Tx Buffer, append the CRC32 and send it out.
What have i tried to solve this so far?
Well, i tried a lot:

*

*I removed the line mentioned above. As long i do not copy any bytes
from DRV_scale[idx].scale.Y to TxBuf[] in the while loop is
disabled, anything works fine.

*I replaced float pSrc = DRV_scale[idx].scale.Y; with * float pSrc =
DebugArray; where DebugArray is a "stand alone" static pre-allocated
float array of the same size as DRV_scale[idx].scale.Y (32
Elements) and anything works fine

*I tried to copy the Elements from DRV_scale[idx].scale.Y to
another float array (lets call it "DupArray"), which worked fine but
when I tried to copy "DupArray" bytewise into TxBuf[] it crashes.

*and I tried to copy the Elements from DRV_scale[idx].scale.Y to
TxBuf[] in another function, right after Hardware initialisation, using the same code (copy & paste), it worked fine

*I tried several versions of the DRV_linscale_TDS Typdef, with the
Byte variable at the end and at the beginning, with no effect

*I checked if there would be a buffer overflow in the while loop, but
as expected there is none, as the total number of copied bytes is
~100, so there are 155 bytes "free" (note: the overrun prevention
code is still in the original code but left out here for better
readability)

I have no clue what's going on here. Each part of the code - when I debug it separatey - works fine. Copying the original Array to another float preallocated float array works fine, copying the float array to a byte array and writing it back works fine. Just if I do exactly that, whats working fine verywhere else, in that particular function, it generates a hard fault.
Through all the testing and debugging it points out clearly: the hard fault only happens, when I try to copy DRV_scale[idx].scale.Y into TxBuf[], anything else works without problems.
One might say: well, then somewhere before FillTxBuf() TxBuf[] gets corrupted, but why works anything flawless in FillTxBuf() when I use a different float array than DRV_scale[idx].scale.Y?
Remarks:
One possible workaround would most probably be to split up the struct and use separate preallocated "stand alone" float arrays. The reason why I glued it together in one variable is, that this variable is written to flash and I'd really like the approach FlashWrite(VariablePointer, SizeInBytes) ...
If there is no other option, i will have to separate it, but I'd really like to understand in which pitfall I stumbled in ...
The Question:
Where could I search?

A: I have no idea about the problem but you can use union to send struct data within a array. Here is an example;
typedef union
{
  your struct object; (should be packed
  struct)
  uint8_t uartBuff[your struct size];
}unExample;

Variables in union use same memory address via this you can easily send your data.

A: hardfault errors always because of pointer-alingment
i usually use my own library for binary serialize in c
this library can help you
it's have examples in c and for STM32F4 already
it's support endiness and have configuration part for customization


text:
Q: pdf-creator-node can not generate ul li with 2 column i've problem when convert html to pdf with pdf-creator-node. when i uses ul li with column=2, in preview html is look good. but when i generated to pdf always preview in one column. may i help me ? this is my css
.itenerary ul{
    display: block;
    list-style-type: disc;
    margin-left: 0;
    margin-right: 0;
    padding-left: 40px;
    line-height:1.6 ;

    columns: 2;

  -webkit-columns: 2;
  -moz-columns: 2;
}

i want to get tips and trick to solve my problems


text:
Q: split up data with java split() make empty data of first array DB has like this data for hashtag in string type
#a#b#c#d#e
with this data, I want split each tag
so I code this
 String tagToArray[] = output.getText("TAG", i).split("#");

but the result is
tagToArray[, a, b, c, d, e]

I want to remove first empty data
what is the right way to splay data of hashtag?

A: This extra empty string produce for first #.
So, you can replace the first character if it is # then split.
 String tagToArray[] = output.getText("TAG", i).replaceFirst("^#", "").split("#");

A: Remove the first # before splitting
 String[] array = str.replaceFirst("#", "").split("#");

A: The issue can be solved with the regex (?<=\#)(.)
Code:
output.getText("TAG", i).split("(?<=\#)(.)");


text:
Q: Using rkt with kubernetes causes "unsupported CRI runtime" I am currently trying to set up a bare metal kubernetes cluster and I am using CoreOS Container Linux and facing the following issue when trying to start the kubelet service:

server.go:266] failed to run Kubelet: failed to create kubelet: unsupported CRI runtime: "rkt"

My ignition file Source:
# NOTE: This configuration is meant to work with Config Transpiler v0.8.0
# The spec is available at (https://github.com/coreos/container-linux-config-transpiler/blob/v0.8.0/doc/configuration.md)

passwd:
  users:
    - name: core
      ssh_authorized_keys:
        - ssh-rsa ...
systemd:
  units:
    # Docker will be configured initially but we'll be using rkt exclusively and will disable it after containerd setup
    - name: docker.service
      enabled: true

    ####################
    # services for rkt #
    ####################
    - name: rkt-api.service
      enabled: true
      contents: |
        [Unit]
        Description=rkt api service
        Documentation=http://github.com/rkt/rkt
        After=network.target rkt-api-tcp.socket
        Requires=rkt-api-tcp.socket

        [Service]
        ExecStart=/usr/bin/rkt api-service

        [Install]
        WantedBy=multi-user.target

    - name: rkt-api-tcp.socket
      enabled: true
      contents: |
        [Unit]
        Description=rkt api service socket
        PartOf=rkt-api.service

        [Socket]
        ListenStream=127.0.0.1:15441
        ListenStream=[::1]:15441
        Service=rkt-api.service
        BindIPv6Only=both

        [Install]
        WantedBy=sockets.target

    - name: rkt-gc.service
      enabled: true
      contents: |
        [Unit]
        Description=Garbage Collection for rkt

        [Service]
        Environment=GRACE_PERIOD=24h
        Type=oneshot
        ExecStart=/usr/bin/rkt gc --grace-period=${GRACE_PERIOD}

        [Install]
        WantedBy=multi-user.target

    - name: rkt-gc.timer
      enabled: true
      contents: |
        [Unit]
        Description=Periodic Garbage Collection for rkt

        [Timer]
        OnActiveSec=0s
        OnUnitActiveSec=12h

        [Install]
        WantedBy=multi-user.target

    - name: rkt-metadata.service
      enabled: true
      contents: |
        [Unit]
        Description=rkt metadata service
        Documentation=http://github.com/rkt/rkt
        After=network.target rkt-metadata.socket
        Requires=rkt-metadata.socket

        [Service]
        ExecStart=/usr/bin/rkt metadata-service

        [Install]
        WantedBy=multi-user.target

    - name: rkt-metadata.socket
      enabled: true
      contents: |
        [Unit]
        Description=rkt metadata service socket
        PartOf=rkt-metadata.service

        [Socket]
        ListenStream=/run/rkt/metadata-svc.sock
        SocketMode=0660
        SocketUser=root
        SocketGroup=root
        RemoveOnStop=true

        [Install]
        WantedBy=sockets.target

    ################################
    # services for install scripts #
    ################################
    - name: k8s-install.service
      enabled: true
      contents: |
        [Install]
        WantedBy=multi-user.target

        [Unit]
        Description=k8s installation script
        Wants=network-online.target
        After=network.target network-online.target

        [Service]
        Type=oneshot
        ExecStart=/ignition/init/k8s/install.sh

    - name: cni-install.service
      enabled: true
      contents: |
        [Install]
        WantedBy=multi-user.target

        [Unit]
        Description=cni plugin installation script
        Requires=k8s-install.service
        After=k8s-install.service

        [Service]
        Type=oneshot
        ExecStart=/ignition/init/cni/install.sh

    - name: rkt-setup.service
      enabled: true
      contents: |
        [Install]
        WantedBy=multi-user.target

        [Unit]
        Description=rkt installation script
        Requires=cni-install.service
        After=cni-install.service

        [Service]
        Type=oneshot
        ExecStart=/ignition/init/rkt/setup.sh

    - name: kubeadm-install.service
      enabled: true
      contents: |
        [Install]
        WantedBy=multi-user.target

        [Unit]
        Description=kubeadm installation script
        Requires=rkt-setup.service
        After=rkt-setup.service

        [Service]
        Type=oneshot
        Environment="PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/opt/bin"
        ExecStart=/ignition/init/kubeadm/kubeadm-install.sh

    - name: k8s-setup.service
      enabled: true
      contents: |
        [Install]
        WantedBy=multi-user.target

        [Unit]
        Description=kubernetes setup script
        Requires=kubeadm-install.service
        After=kubeadm-install.service

        [Service]
        Type=oneshot
        User=core
        Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/opt/bin"
        ExecStart=/ignition/init/k8s/setup.sh

storage:
  filesystems:
    - mount:
        device: /dev/disk/by-label/ROOT
        format: xfs
        wipe_filesystem: true
        label: ROOT

  files:
    - path: /opt/bin/kubeadm
      filesystem: root
      mode: 493 # 0755
      contents:
        remote:
          url: https://storage.googleapis.com/kubernetes-release/release/v1.14.3/bin/linux/amd64/kubeadm

    - path: /opt/bin/kubelet
      filesystem: root
      mode: 493 # 0755
      contents:
        remote:
          url: https://storage.googleapis.com/kubernetes-release/release/v1.14.3/bin/linux/amd64/kubelet

    - path: /opt/bin/kubectl
      filesystem: root
      mode: 511 # 0777
      contents:
        remote:
          url: https://storage.googleapis.com/kubernetes-release/release/v1.14.3/bin/linux/amd64/kubectl

    - path: /etc/systemd/system/kubelet.service
      filesystem: root
      mode: 420 # 0644
      contents:
        remote:
          url: https://raw.githubusercontent.com/kubernetes/kubernetes/v1.14.3/build/debs/kubelet.service

    - path: /etc/systemd/system/kubelet.service.d/10-kubeadm.conf
      filesystem: root
      mode: 420 # 0644
      contents:
        remote:
          url: https://raw.githubusercontent.com/kubernetes/kubernetes/v1.14.3/build/debs/10-kubeadm.conf

    - path: /ignition/init/cni/cni-plugins-v0.8.1.tgz
      filesystem: root
      mode: 420 # 0644
      contents:
        remote:
          url: https://github.com/containernetworking/plugins/releases/download/v0.8.1/cni-plugins-linux-amd64-v0.8.1.tgz

    - path: /ignition/init/canal/canal.yaml
      filesystem: root
      mode: 493 # 0755
      contents:
        remote:
          url: https://docs.projectcalico.org/v3.7/manifests/canal.yaml

    - path: /ignition/init/kube-router/kube-router.yaml
      filesystem: root
      mode: 493 # 0755
      contents:
        remote:
          url: https://raw.githubusercontent.com/cloudnativelabs/kube-router/v0.3.1/daemonset/kubeadm-kuberouter.yaml

    - path: /ignition/init/k8s/install.sh
      filesystem: root
      mode: 480 # 740
      contents:
        inline: |
          #!/bin/bash

          # Unzip the kubernetes binaries if not already present
          test -d /opt/bin/kubeadm && echo "k8s binaries (kubeadm) already installed" && exit 0

          # NOTE: If RELEASE is updated, the SHA512 SUMs will need to be as well
          echo -e "=> Installing k8s v1.14.3"

          echo "=> Cusomizing kubelet.service..."
          sed -i "s:/usr/bin:/opt/bin:g" /etc/systemd/system/kubelet.service
          sed -i "s:/usr/bin:/opt/bin:g" /etc/systemd/system/kubelet.service.d/10-kubeadm.conf

          systemctl daemon-reload
          systemctl enable kubelet
          systemctl start kubelet

    - filesystem: root
      path: /ignition/init/rkt/setup.sh
      mode: 480 # 740
      contents:
        inline: |
          #!/bin/bash

          # Unzip the kubernetes binaries if not already present
          test -d /etc/systemd/system/kubelet.service.d/0-kubelet-extra-args.conf && echo "rkt systemd drop-ins already installed" && exit 0

          echo "=> Adding dropins for rkt...."
          cat > /etc/systemd/system/kubelet.service.d/0-kubelet-extra-args.conf <<EOF
          [Service]
          Environment="KUBELET_EXTRA_ARGS=--container-runtime=rkt --volume-plugin-dir=/var/lib/kubelet/volumeplugins"
          EOF

          echo "=> Triggering systemctl daemon-reload...."
          systemctl daemon-reload
          systemctl enable rkt-api
          systemctl enable rkt-metadata
          systemctl start rkt-api
          systemctl start rkt-metadata
          systemctl start rkt-gc

    - filesystem: root
      path: /ignition/init/cni/install.sh
      mode: 480 # 740
      contents:
        inline: |
          #!/bin/bash

          # Unzip the kubernetes binaries if not already present
          test -d /opt/cni/bin && echo "CNI binaries already installed" && exit 0

          VERSION=0.8.1
          echo -e "=> Installing CNI (v${VERSION}) binaries to /opt/cni/bin"
          cd /ignition/init/cni
          mkdir -p /opt/cni/bin
          tar -C /opt/cni/bin -k -xzf cni-plugins-v${VERSION}.tgz

    - filesystem: root
      path: /ignition/init/kubeadm/kubeadm-install.sh
      mode: 480 # 740
      contents:
        inline: |
          #!/bin/bash

          # Ensure kubeadm binary is present
          test -f /opt/bin/kubeadm || (echo "Failed to find kubeadm binary" && exit 1)

          # Exit if kubeadm has already been run (/etc/kubernetes folder would have been created)
          test -d /etc/kubernetes && echo "/etc/kubernetes is present, kubeadm should have already been run once" && exit 0

          echo "=> Running kubeadm init..."
          /opt/bin/kubeadm init --pod-network-cidr "10.244.0.0/16"

          echo "=> Running kubeadm post-install set up for user 'core'"
          mkdir -p /home/core/.kube
          cp -i /etc/kubernetes/admin.conf /home/core/.kube/config
          chown $(id -u core):$(id -g core) /home/core/.kube/config

    - filesystem: root
      path: /ignition/init/k8s/setup.sh
      mode: 493 # 0755
      contents:
        inline: |
          #!/bin/bash

          # Ensure /etc/kubernetes is present (created by kubeadm)
          test -d /etc/kubernetes || (echo "/etc/kubernetes not present, ensure kubeadm has run properly" && exit 1)

          test -f /home/core/.kubernetes-setup-finished && echo "kubeadm already run, k8s should be set up" && exit 0

          echo "=> Enabling workload running on the master node"
          kubectl taint nodes --all node-role.kubernetes.io/master-

          echo "=> Installing kube-router"
          kubectl apply -f /ignition/init/kube-router/kube-router.yaml

          echo "=> Removing kube-proxy (kube-router will perform routing for the node)"
          kubectl delete daemonset kube-proxy -n kube-system
          docker run --privileged --net=host k8s.gcr.io/kube-proxy-amd64:v1.14.3 kube-proxy --cleanup

          # Disable docker (it won't be used by anything after now)
          sudo systemctl stop docker
          sudo systemctl disable docker

          echo "=> Leaving post-setup lock file @ [/home/core/.kubernetes-setup-finished]"
          touch /home/core/.kubernetes-setup-finished

    - filesystem: root
      path: /etc/cni/net.d/10-kuberouter.conf
      mode: 493 # 0755
      contents:
        inline: |
          {
            "name":"kubernetes",
            "type":"bridge",
            "bridge":"kube-bridge",
            "isDefaultGateway":true,
            "ipam": {
              "type":"host-local"
            }
          }

Why is it not working? Does kubelet not support rkt anymore?

A: I found the solution myself:
kubelet --help

--container-runtime string
  The container runtime to use. Possible values: 'docker', 'remote', 'rkt (deprecated)'. (default "docker")


text:
Q: Could we get an option for pinging the first downvoter in a comment? In short, what I'm asking for is something like this:
Assume you've got an answer to a question. Now, someone downvotes that, and doesn't leave a comment. You're scratching your head at why, as your answer (you think) was good, answers the question, and works. However, you can't ask the downvoter, as (s)he is anonymous.
My suggestion is that for the first downvoter (and only if there is ONE downvote, as when you have two downvotes it usually means that it's either a bad answer, or it's quite a popular answer and it's just getting voted down for the sake of it) that you can mention him/her in a comment, as @Downvoter. This would be completely anonymous, and the person would get a notification, but you wouldn't know who it was. So they can choose whether or not to comment (for example, if it was a terribly bad answer, (s)he shouldn't be forced to explain why). However, they would get a notification, so maybe if they forgot to explain why they could be reminded.
Also, I'd say there should be a rep limit for this, as it means that new users can't abuse this if they got downvoted because they posted a bad answer. Not that high, though. Maybe around 250?

A: Usually when I downvote without a comment, it is because the question lacks evidence of research. In other words, I don't have anything to say beyond what is already in the standard ask question interface.
See https://meta.stackexchange.com/a/172760/192138

A: I guess most of the people downvote because of poor information in the question and few of them are just to get the reputation badge for downvoting. But I think its better to  ask for more details abuot the question in the comment even after downvoting so that we can improve our question.


text:
Q: get_row function ignored in python I wrote a function to get row data from a csv file,which failed .so I insert so many "print"s to see  what is wrong.but to my surprise,the console just keeps empty,that's quit strange.I have reindent my code for so many times
my code is blew:
# -*- coding: utf-8 -*-
import csv

def get_rows(csv_file):
    print '0'
    reader=csv.reader(open(csv_file))
    print '1'
    #get the colnum names,lowercased
    col_names=tuple(k.lower() for k in reader.next())
    print '2'
    for row in reader:
        yield dict(zip(col_names,row))
    print col_names

def main():
    file_name='companylist.csv'

    try:
        get_rows(file_name)
    except:
        print 'OK'
if __name__=='__main__':
    main()

while code:
# -*- coding: utf-8 -*-
import csv

reader=csv.reader(open('companylist.csv'))
col_names=tuple(k.lower() for k in reader.next())
for row in reader:
    dict(zip(col_names,row))
print col_names

work s perfectly,resulted in:
('symbol', 'name', 'lastsale', 'marketcap', 'adr tso', 'ipoyear', 'sector', 'industry', 'summary quote', '')

while code:
# -*- coding: utf-8 -*-
import csv

def main():
    reader=csv.reader(open('companylist.csv'))
    col_names=tuple(k.lower() for k in reader.next())
    print '1'
    print col_names
    for row in reader:
        yield dict(zip(col_names,row))
    print col_names

if __name__=='__main__':
    main()

resulted in nothing
and code:
# -*- coding: utf-8 -*-
import csv
def get_rows(csv_file):
    print '0'
    reader=csv.reader(open(csv_file))
    print '1'
    #get the colnum names,lowercased
    col_names=tuple(k.lower() for k in reader.next())
    print '2'
    for row in reader:
        yield dict(zip(col_names,row))
    print col_names
def main():
    file_name='companylist.csv'

    try:
        if(get_rows(file_name)):
            print "OK"
    except Exception,ex:
        print Exception,":",ex
if __name__=='__main__':
    main()

resulted in :OK

A: As your get_rows is a generator function, it executes only when one of the generator methods is called (e.g., for...in expression internally calls next() method for an iterable object). So rewriting your main function should help:
def main():
    file_name='companylist.csv'

    try:
        for row in get_rows(file_name):
            print row
    except:
        print 'OK'

A: You define a generator function get_rows, which only yields a value when you call it as an iterator. So, unless you insert print statements in your main function, you just print the generator function in the row get_rows(file_name) (which is fine, raising no exception), which does not execute it! Therefore, none of the many print statements are executed.
Try looping over get_rows(file_name) and see what happens, i.e. like this
for element in get_rows(file_name):
    # do something with element

A: The issue is that 'yield' stops the function from behaving as a function.  If you change it to return, you will see your exception (my python 3 says that reader has no next() function) and your prints.
I have not found any documentation (yet) on how generators suppress print statements, but that does seem to be the case with simple code such as:
def mygen():
    print('1')
    yield 1

Regarding the exception, take a look at this:
Handle generator exceptions in its consumer

A: As everyone has pointed out already, you are using a generator, which is why it doesn't execute until you call the generator's .next or .__next__ (on Python 3) for the first time. However I'm going to suggest a better way of making your get_rows function with lowercase column names:
import csv

def get_rows(csv_file):
    with open(csv_file) as f:
        return csv.DictReader(f, next(f).lowercase().split(','))


text:
Q: Pyspark Count number of non-zero, or zero, in row of RDD?

In Pyspark as a preprocessing step I am attempting to filter out rows of data from an RDD that contain below a certain number of Non-zero values. Currently we run run a sum that gets called then compared. (At this point None/na has been filled in with 0)
def clean_features(row: Row, nonzero_feature_count) -> bool:
    feature_count = row.features.sum()
    # arbitary filter on how many rows we use
    if feature_count > nonzero_feature_count:
        return True
    return False

The problem is not all of our columns have binary values. Some may be as high as 15-20, which obviously would throw off how we were trying to filter.
How can we either count the number of non-zero or the number of 0's efficiently?
So with the row [1,3,0,0,3,1] we want to either be able to calculate: '4' for the # non zero values in the row, or 2 for the # zero values in the row. Currently we calculate 8 when presented with that row of the RDD.


text:
Q: How to open DropDownButton on init page i want to make a function for init openDropDown(); when page loaded or tap on other widget
I found this in stackoverfow
but its not working maybe its outdated. how can i achieve. with flutter 2.10
here is my dropdown
DropdownButton(
                    isExpanded: true,
                    value: selectedValue,
                    items: [
                      for (var i = 0; i < this.clients.length; i++)
                        DropdownMenuItem(
                            child: Text(this.clients[i]['name'].toString() +
                                ' (' +
                                this.clients[i]['wallet'].toString() +
                                ') '),
                            value: this.clients[i]['id'].toString())
                    ],
                    onChanged: (String? newValue) {
                      setState(() {
                        selectedValue = newValue!;
                      });
                    },
                  ),

A: You can take advantage of GlobalKey to get this job done... Also use SchedulerBinding  because in initState key would be null so you won't be able to open DropDown from null key... here is the proper code how you do that task
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter DropDownButton',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey _dropdownButtonKey = GlobalKey();
  final Intent _intent = const ActivateIntent();

// Initial Selected Value
  String dropdownvalue = 'Item 1';

// List of items in our dropdown menu
  var items = [
    'Item 1',
    'Item 2',
    'Item 3',
    'Item 4',
    'Item 5',
  ];

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance?.addPostFrameCallback((_) {
      if (_dropdownButtonKey.currentContext != null) {
        _dropdownButtonKey.currentContext?.visitChildElements((element) {
          if (element.widget is Semantics) {
            element.visitChildElements((element) {
              if (element.widget is Actions) {
                element.visitChildElements((element) {
                  Actions.invoke(element, _intent);
                  return;
                });
              }
            });
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            DropdownButton(
              autofocus: true,
              key: _dropdownButtonKey,
              isDense: true,
              isExpanded: true,
              value: dropdownvalue,
              icon: const Icon(Icons.keyboard_arrow_down),
              items: items.map((String items) {
                return DropdownMenuItem(
                  value: items,
                  child: Text(items),
                );
              }).toList(),
              onChanged: (String? newValue) {
                setState(() {
                  dropdownvalue = newValue!;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}


text:
Q: HttpSelfHostServer Error 502 Connection Refused I am trying to run the sample from the Pluralsight Introduction to the APS.NET Webapi.  It is a console application with a program class
using System.Web.Http.SelfHost;
using System.Web.Http;
using System.Net.Http;
namespace ASPNETWebAPISelfHost
{
    class Program
    {
        static void Main(string[] args)
        {
            var config =
              new HttpSelfHostConfiguration("http://localhost:8999");
            config.Routes.MapHttpRoute("DefaultRoute",
            "{controller}/{id}",
            new { id = RouteParameter.Optional });
        //custom message processing
        //var server = new HttpSelfHostServer(config,
        //      new MyNewSimpleMessageHandler());
        //controller message processing
        var server = new HttpSelfHostServer(config);
        server.OpenAsync();
        Console.ReadLine();
        var client = new HttpClient(server);
        client.GetAsync(
          "http://localhost:8999/simple").ContinueWith((t) =>
          {
              var result = t.Result;
              result.Content.ReadAsStringAsync().ContinueWith((rt) =>
              {
                  Console.WriteLine("Client got " + rt.Result);
              });
          });
        Console.WriteLine("Opening Web API SelfHost");
        Console.ReadLine();
    }
}

}
and a controller
using System.Web.Http;

namespace ASPNETWebAPISelfHost
{
  public class SimpleController : ApiController
  {
    public IEnumerable<string> Get()
    {
      return new string[] { "Hello", "ControllerAPI" };

    }
  }
}

When I run it in VS, the HttpClient is able to retrieve the json data, but when I make the call from Fiddler, I get a 502 Server actively refuses connection.  I am running VS as an administrator as instructed in the video.
How can I get around this error


text:
Q: why jwt.sign() method only works on string secret key? I am trying to learn JWT authentication token, but I am having an issue.
In my code, this line works fine.
const token = jwt.sign({ foo: 'bar' }, 'ea7aae59cedb7346c');

But this line doesn't work.
const token = jwt.sign({ foo: 'bar' }, ea7aae59cedb7346c);

To me it seems like when I try to put the jet authentication secret key inline without making it a string value, it doesn't work.
Why is this happening? What's the difference between stringified key value and regular key value in jwt.sign() method?

A: Thank you for asking this question.
"secretOrPrivateKey is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA."
as stated in https://www.npmjs.com/package/jsonwebtoken
I have placed my in .env file and it is working okay.
like this.
and the .env file key is this.

A: jwt.sign(payload, secretOrPrivateKey, [options, callback])

Source
const token = jwt.sign({ foo: 'bar' }, 'shhhhh');

payload could be an object literal, buffer or string representing
  valid JSON.

So in your case  you pass "payload" as a Object  and "secret" is "shhhhh"
as per the docuemtation

secretOrPrivateKey is a string, buffer, or object containing either
  the secret for HMAC algorithms or the PEM encoded private key for RSA
  and ECDSA.

So you are not provide a valid arugument which is long value not string
you can pass value as a string or pass algorithm in secretOrPrivateKey
like this
hmacSha256(key, message) {}


text:
Q: How to add new parameter to existing SSRS Report I'm trying to add a new Parameter called CorporateIdentity to the SalesInvoice report in dynamics. I've added the parm***() method to SalesInvoiceContract and compiled the Contract, the Controller and the DataProvider forward.
But I can't get the parameter to show up in Visual Studio. I've tried refreshing the DataSources. I've tried deleting and recreating one of the DataSources. I've tried to create the Parameter manually.
How can I get this parameter to show up?

A: The answer was to perform an incremental CIL. Some other things to try are listed below.

*

*Have you performed an incremental CIL?

*Did you try refreshing your caches (Tools>Caches, just do all of them)?

*Try restarting the AOS service and the SSRS service.

*Is your WCF data up to date in your AXC file?

*Try clearing your usage data and AUC/KTI files.

There are all sorts of weird things to try, but I listed them in order of what I would try ... no need to do them all if one step works.


text:
Q: React-media query not working with large screen on pageload when hosting on Netlify I'm using react-media v1.8.0 (https://github.com/ReactTraining/react-media) with Gatsby and it's is working perfectly locally, but not working the same way when hosted on Netlify. I have set of photos that should be stacking on smaller screens and should be a grid on larger screens. As seen on this Netlify preview-branch under the red title that says "Non-contest Submission" (https://5bb630aec965921b43c49c7b--art-show.netlify.com/), if you load the site with a screen-width >768px, it doesn't load properly, but if you resize the screen <768px and then back to >768px, it loads properly. I'm not sure why there's an issue on initial load for larger screens.
Here's how I'm using react-media. In my render():
staffImages = (
  (photos).map((photo, i) => {

    let photoMobileURL = photo.url.replace(new RegExp("(.*)" + 'lg'), "$1sm");

    return (
      <Media query={{ maxWidth: 768 }}>
        {matches =>
          matches ? (
            <GridPhotoContainer>
              <Photo
                className="Photo"
                backgroundImage={photoMobileURL}
                openModal={() => this.openModal(i, false, true)}
              />
            </GridPhotoContainer>
          ) : (
              <Photo
                className="Photo"
                backgroundImage={photo.url}
                openModal={() => this.openModal(i, false, true)}
              />
            )
        }
      </Media>
    )
  })
)

renderStaffImages = (
  <Media query="(max-width: 768px)">
    {matches =>
      matches ? (
        <Grid className="Grid">
          {staffImages}
        </Grid>
      ) : (
          <Grid className="Grid" marginTop="3em">
            {staffImages}
          </Grid>
        )
    }
  </Media>
)

then I'm returning {renderStaffImages} in my component's return statement.

A: At the least, there should be a unique key assignment on your list of components that are created when you build collections of elements using map(). Also, for performance, you should just make the decision what collection type to return based on a parameter rather than checking the media query in your loop which could have bad side effects.
Try something like
staffImages = (small) => {
  const photoURL = small ? photo.url.replace(new RegExp("(.*)" + 'lg'), "$1sm") : `${photo.url}`;
  return (photos).map((photo, i) => small ? (
    <GridPhotoContainer key={i}>
      <Photo
        className="Photo"
        backgroundImage={photoURL}
        openModal={() => this.openModal(i, false, true)}
      />
    </GridPhotoContainer>
  ) : (
    <Photo
      key={i}
      className="Photo"
      backgroundImage={photoURL}
      openModal={() => this.openModal(i, false, true)}
    />
    )
  )
}

renderStaffImages = (
  <Media query="(max-width: 768px)">
    {matches => (
        <Grid className="Grid" marginTop={matches ? '0' : '3em'}>
          {staffImages(matches)}
        </Grid>
      )
    }
  </Media>
)


text:
Q: Logging count of DELETED records When I try to run this
DECLARE @by varchar(20) = 'Myself'

INSERT INTO dbo.MiscLog(LogType, onTable, Message, CreateBy)
   SELECT
      'Info', 'dbo.History',
      'There are ' + CONVERT(varchar(20), COUNT(ID)) + ' old records being purged.', @by
   FROM
       (DELETE FROM dbo.History
        OUTPUT deleted.ID
        WHERE keyDate < dateadd(y, -7, getDate())) H

I get

Msg 5322, Level 15, State 1, Line 5
  An aggregate function is not allowed in the SELECT clause when the FROM clause contains a nested INSERT, UPDATE, DELETE, or MERGE statement.

A: Try inserting a copy of the deleted records into a temp table and then run your COUNT() aggregation on the temp table.
SELECT *
INTO #tempLog
   FROM
       (DELETE FROM dbo.History
        OUTPUT deleted.ID
        WHERE keyDate < dateadd(y, -7, getDate())) H

INSERT INTO dbo.MiscLog(LogType, onTable, Message, CreateBy)
   SELECT
      'Info', 'dbo.History',
      'There are ' + CONVERT(varchar(20), COUNT(ID)) + ' old records being purged.', @by
FROM #tempLog

A: Create an AFTER DELETE trigger on the table. You can query deleted for the count.
SELECT COUNT(*)
FROM   deleted


text:
Q: Visual corruption around rounded corners In my WPF app, I see these smear-like visual corruptions, especially around rounded corners. Notice the problem with the upper corners of the button.

I tried the following but the issue persists:

*

*SnapToDevicePixels=true

*Resized and moved the app window.

*Changed the screen resolution

What might be causing this?
XAML for the button:
<Button Width="Auto" Click="btnAdd_Click" Height="Auto" x:Name="btnAdd"  VerticalAlignment="Center" HorizontalAlignment="Right" Focusable="False" Margin="20,0,0,0" SnapsToDevicePixels="True">
            <StackPanel Orientation="Horizontal" Margin="0">
                <TextBlock Text="Ekle" HorizontalAlignment="Center" VerticalAlignment="Center"  Margin="0,0,5,0"/>
                <Image Source="/FideKiosk;component/Icons/right.png" MaxWidth="30" Width="15" Height="15"/>
            </StackPanel>
        </Button>

and then I have an implicit style in Application.Resources:
<Style TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid x:Name="grid">
                        <Rectangle RadiusX="10" RadiusY="10" x:Name="rectangle" Opacity="0.995">
                            <Rectangle.Effect>
                                <DropShadowEffect ShadowDepth="0" BlurRadius="0" Color="#FFC0F3AD" Opacity="0"/>
                            </Rectangle.Effect>
                            <Rectangle.Fill>
                                <LinearGradientBrush EndPoint="0.501,0.039" StartPoint="0.501,0.971">
                                    <GradientStop Color="#FF346223" Offset="0.124" />
                                    <GradientStop Color="#FF325625" Offset="0.526" />
                                    <GradientStop Color="#FF39622B" Offset="0.534" />
                                    <GradientStop Color="#FF367021" Offset="0" />
                                    <GradientStop Color="#FF4A8535" Offset="0.986" />
                                </LinearGradientBrush>
                            </Rectangle.Fill>
                        </Rectangle>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True" Margin="15" />
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" TargetName="grid" Value="0.5"/>
                        </Trigger>
                        <Trigger Property="IsMouseCaptureWithin" Value="True">
                            <Setter Property="Effect" TargetName="rectangle">
                                <Setter.Value>
                                    <DropShadowEffect BlurRadius="30" Color="#FFC0F3AD" Opacity="1" ShadowDepth="0"/>
                                </Setter.Value>
                            </Setter>
                            <Setter Property="Fill" TargetName="rectangle">
                                <Setter.Value>
                                    <LinearGradientBrush EndPoint="0.501,0.039" StartPoint="0.501,0.971">
                                        <GradientStop Color="#FF346223" Offset="0.303"/>
                                        <GradientStop Color="#FF325625" Offset="0.526"/>
                                        <GradientStop Color="#FF39622B" Offset="0.534"/>
                                        <GradientStop Color="#FF4A8535" Offset="0"/>
                                        <GradientStop Color="#FF8AC077" Offset="0.986"/>
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

A: I used your code and could not find any artifacts in neither the designer nor when running the app. So unless you have more UI elements that are not in code you presented my guess is that the graphics card (hardware/driver) on your machine is causing this.
You could test this by switching to software rendering:  Can I force WPF rendering tier?


text:
Q: In Slick Grid inline edit I can't able to get the entire object I am using angular slickgrid for showing my data. When I am trying to edit the slick grid record, I will get the changed fields only  I need the entire object. I have given the sample data.
Columndefinition :
this.columnDefinitions = [
      {
        id: 'title', name: 'Title', field: 'title', width: 220, cssClass: 'cell-title',
        filterable: true, sortable: true,
        queryFieldSorter: 'id', type: FieldType.string,
        formatter: Formatters.tree,
        editor: {
          model: Editors.longText,
          required: true,
        },
      },
      { id: 'duration', name: 'Duration', field: 'duration', minWidth: 90, filterable: true },
      {
        id: 'child.0.percentComplete', name: '% Complete', field: 'child.0.percentComplete', minWidth: 120, maxWidth: 200,
        sortable: true, filterable: true, filter: { model: Filters.slider, operator: '>=' },
        formatter: Formatters.percentCompleteBar, type: FieldType.number,
        editor: {
          model: Editors.slider,
          minValue: 0,
          maxValue: 100,
          params: { hideSliderNumber: false },
        },
      },

    ];

SlickGrid input data set structure:
const data = [
      {
        'id': 0,
        'indent': 0,
        'parentId': null,
        'title': 'Task 0',
        'duration': '5 days',
        'percentComplete': 73,
        'start': '2003-03-21T18:30:00.000Z',
        'finish': '2003-04-21T18:30:00.000Z',
        'effortDriven': true,
        'child' : [{
            'id': 2,
            'indent': 0,
            'parentId': 1,
            'title': 'Task 0',
            'duration': '5 days',
            'percentComplete': 73,
            'start': '2003-03-21T18:30:00.000Z',
            'finish': '2003-04-21T18:30:00.000Z',
            'effortDriven': true
        }]
      },
      {
        'id': 1,
        'indent': 0,
        'parentId': null,
        'title': 'Task 1',
        'duration': '5 days',
        'percentComplete': 4,
        'start': '2004-04-24T18:30:00.000Z',
        'finish': '2004-05-24T18:30:00.000Z',
        'effortDriven': false
      }
    ];

When I start to change the employee field oncellchanged called and I got arg.Item
Current behaviour
onCellChanged(e, args) {
    this.angularGrid.gridService.updateItemById(args.item['id'], args.item);
    console.log(args.item);
}

Log
{
  "id": 0,
  "indent": 0,
  "parentId": null,
  "title": "Task 0",
  "duration": "5 days",
  "percentComplete": 73,
  "start": "2003-03-21T18:30:00.000Z",
  "finish": "2003-04-21T18:30:00.000Z",
  "effortDriven": true,
  "child": {
    "0": {
      "percentComplete": 25
    }
  }
}

Expected output:
{
  "id": 0,
  "indent": 0,
  "parentId": null,
  "title": "Task 0",
  "duration": "5 days",
  "percentComplete": 73,
  "start": "2003-03-21T18:30:00.000Z",
  "finish": "2003-04-21T18:30:00.000Z",
  "effortDriven": true,
  "child": [
    {
      "id": 2,
      "indent": 0,
      "parentId": 1,
      "title": "Task 0",
      "duration": "5 days",
      "percentComplete": 25,
      "start": "2003-03-21T18:30:00.000Z",
      "finish": "2003-04-21T18:30:00.000Z",
      "effortDriven": true
    }
  ]
}

Software versions

*

*Angular : 7.3.5

*Angular-Slickgrid : 2.17.10

*TypeScript : 3.1.6

*Node : 10.16.3

A: The issue due to the utils files used in angular slickgrid library. If you want to fix this issue, have two solutions.

*

*The library itself handle the function logic.

*Need to implement custom editor based on your requirement.

Issue area
In each editor, applyValue method sets the object value to respective path. In the method, the array value not parsed properly. You can extend the editor class and override the applyValue method. Here I shared the sample code for your reference. Especially, go through the setDeepValue method which I have mentioned below.
import { EditorArguments, InputEditor } from 'angular-slickgrid';

export class CustomInputEditor extends InputEditor {
  constructor(protected readonly args: EditorArguments, inputType: string) {
    super(args, inputType);
  }
  applyValue(item: any, state: any) {
    const fieldName = this.columnDef && this.columnDef.field;
    if (fieldName !== undefined) {
      const isComplexObject = fieldName?.indexOf('.') > 0; // is the field a complex object, "address.streetNumber"
    // is the field a complex object having array value you need to specify the index position in path (Here I used 0th index), "address.0.streetNumber"

      // validate the value before applying it (if not valid we'll set an empty string)
      const validation = this.validate(state);
      const newValue = validation?.valid ? state : '';

      // set the new value to the item datacontext
      if (isComplexObject) {
        // when it's a complex object, user could override the object path (where the editable object is located)
        // else we use the path provided in the Field Column Definition
        const objectPath =
          this.columnEditor?.complexObjectPath ?? fieldName ?? '';
        this.setDeepValue(item, objectPath, newValue);
      } else if (fieldName) {
        item[fieldName] = newValue;
      }
    }
  }

  setDeepValue<T = any>(obj: T, path: string | string[], value: any) { // Customized the set value method to handle the array data
    if (typeof path === 'string') {
      path = path.split('.');
    }

    if (path.length > 1) {
      const e = path.shift();
      if (obj && e !== undefined) {
        let innerObject;
        if (!Array.isArray(obj[e]) && typeof obj[e] != 'object') {
          obj[e] = {};
        }
        this.setDeepValue(obj[e], path, value);
      }
    } else if (obj && path[0]) {
      (obj as any)[(path as any)[0]] = value;
    }
  }
}

I hope this may helpful for you.
Kind information to the library author, If possible update the setDeepValue method in latest release.


text:
Q: how can I dynamically change the number of records that needs to be filtered out? The final report is going to be in tableau, while SQL will be used to pull records. So a solution in any of these two is appreciated.
I have three tables A,B,C. I need to sample a total of 30 records from these three tables for a report for each month. On a ideal scenario, it should be 10 records each from these table. But,if for some reason, one of the tables have less than 10 records for a month, the sample includes all the data. Also, it needs to be compensated from the other two tables. (15+10+5 or any other combination).
is there a way to dynamically achieve this?
I tried to create separate worksheets in tableau, and merge it in a dashboard, but that doesn't work. Plus, they all should be presented as one single report, not as separate reports to download.

A: This works coming from SQL. It does have the drawback of always trying to pull the missing rows from table a first, but if that is not an issue this should suffice.
EDIT: Removed extraneous WHILE bits and just used TOP to try and get 10 rows from each table to start.
DECLARE @a TABLE (id INT IDENTITY, adata VARCHAR(10))
DECLARE @b TABLE (id INT IDENTITY, bdata VARCHAR(10))
DECLARE @c TABLE (id INT IDENTITY, cdata VARCHAR(10))

INSERT INTO @a
VALUES
('a1'),
('a2'),
('a3'),
('a4'),
('a5'),
('a6'),
('a7'),
('a8'),
('a9'),
('a10'),
('a11'),
('a12'),
('a13'),
('a14'),
('a15')

INSERT INTO @b
VALUES
('b1'),
('b2'),
('b3'),
('b4'),
('b5'),
('b6'),
('b7'),
('b8'),
('b9'),
('b10'),
('b11'),
('b12'),
('b13'),
('b14'),
('b15')

INSERT INTO @c
VALUES
('c1'),
('c2'),
('c3'),
('c4'),
('c5')

DECLARE @dataset TABLE (id INT IDENTITY, datasource VARCHAR(10), mdata VARCHAR(10), sourceid INT)

DECLARE @countert INT = 0

--try to get 10 rows from table a
INSERT INTO @dataset (datasource, mdata, sourceid)
SELECT TOP (10) 'a' AS datasource
    , adata AS mdata
    , id AS sourceid
FROM @a a
ORDER BY id

--try to get 10 rows from table b
INSERT INTO @dataset (datasource, mdata, sourceid)
SELECT TOP (10) 'b' AS datasource
    , bdata AS mdata
    , id AS sourceid
FROM @b b
ORDER BY id

--try to get 10 rows from table c
INSERT INTO @dataset (datasource, mdata, sourceid)
SELECT TOP (10) 'c' AS datasource
    , cdata AS mdata
    , id AS sourceid
FROM @c c
ORDER BY id

--set the total counter to the current number of rows
SET @countert = @countert + (SELECT COUNT(id) FROM @dataset)

--try to finish off from table a
WHILE @countert < 30
BEGIN
INSERT INTO @dataset (datasource, mdata, sourceid)
SELECT TOP (1) 'a' AS datasource
    , adata AS mdata
    , id AS sourceid
FROM @a a
WHERE NOT EXISTS (SELECT 1 FROM @dataset d WHERE datasource = 'a' AND d.sourceid = a.id)
ORDER BY id
SET @countert = @countert +1
END

--try to finish off from table b
WHILE @countert < 30
BEGIN
INSERT INTO @dataset (datasource, mdata, sourceid)
SELECT TOP (1) 'b' AS datasource
    , bdata AS mdata
    , id AS sourceid
FROM @b b
WHERE NOT EXISTS (SELECT 1 FROM @dataset d WHERE datasource = 'b' AND d.sourceid = b.id)
ORDER BY id
SET @countert = @countert +1
END

--try to finish off from table c
WHILE @countert < 30
BEGIN
INSERT INTO @dataset (datasource, mdata, sourceid)
SELECT TOP (1) 'c' AS datasource
    , cdata AS mdata
    , id AS sourceid
FROM @c c
WHERE NOT EXISTS (SELECT 1 FROM @dataset d WHERE datasource = 'c' AND d.sourceid = c.id)
ORDER BY id
SET @countert = @countert +1
END

SELECT * FROM @dataset

id
datasource
mdata
sourceid

1
a
a1
1

2
a
a2
2

3
a
a3
3

4
a
a4
4

5
a
a5
5

6
a
a6
6

7
a
a7
7

8
a
a8
8

9
a
a9
9

10
a
a10
10

11
b
b1
1

12
b
b2
2

13
b
b3
3

14
b
b4
4

15
b
b5
5

16
b
b6
6

17
b
b7
7

18
b
b8
8

19
b
b9
9

20
b
b10
10

21
c
c1
1

22
c
c2
2

23
c
c3
3

24
c
c4
4

25
c
c5
5

26
a
a11
11

27
a
a12
12

28
a
a13
13

29
a
a14
14

30
a
a15
15


text:
Q: Is it normal to get 14 MB images from UIImagePicker? I am developing an iOS app which gets images from the camera with UIImagePickerController. Here is my code;
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!){

    imageTaken = image
    self.dismissViewControllerAnimated(true, completion: nil)
    self.performSegueWithIdentifier("camera", sender: self)
}

@IBAction func cameraButtonPressed(sender: UIBarButtonItem) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){

        var imagePicker = UIImagePickerController()

        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.Camera;

        imagePicker.mediaTypes = NSArray(object: kUTTypeImage)
        imagePicker.allowsEditing = false

        self.presentViewController(imagePicker, animated: true, completion: nil)

    }
    else{
        imageTaken = UIImage(named: "potato")
        self.performSegueWithIdentifier("camera", sender: self)
    }

}

I realized the image sizes are higher than I would expect (14 MB). I need to send the images to my server. My questions are;

*

*Is it normal to have 14 MB images?

*Should I attempt to compress them before I send them to my server? What is the common approach here?

A: First question:
That's absolutely normal for an 8 MP image. Keep in mind that if you take an image from the gallery, the user can pick even bigger images if she/he have stored them on the device.
Second:
It is always recommended to compress images. But in your case i think you already compressed it to JPEG or PNG with the corresponding methods.
Anyway upload such an image is totally fine if you don't have any server restrictions.
There is no lossless method to shrink the size any further.
One is to scale the image down which may be appropriate if you don't need the full 8 MP resolution.
The other is to limit the color palettes (256 colors or less) but this will result in massive loss in quality and detail. This will only make it easier for the compression algorithms of PNG or JPEG to do their work.


text:
Q: Elasticsearch suggest returns Unknown SuggestionBuilder I am using elasticsearch to reach auto suggest for Chinese documents, but I get error unknown suggestionbuilder.
Here is the code I build my elasticsearch index.
url = "http://localhost:9200/autocomplete"

payload = {
  "mappings": {
    "values" : {
      "properties" : {
        "value" : { "type" : "text" },
        "value_suggest" : {
          "type" :     "completion",
          "analyzer" :  "ik_max_word",
          # "search_analyzer" : "ik_max_word",
          # "preserve_position_increments": False,
          # "preserve_separators": False
        }
      }
    }
  }
}
payload = json.dumps(payload)
response = requests.request("PUT", url, data=payload, headers=headers)

Here is the search code.
payload = {
"suggest": {
"autocomplete": {
    "prefix": str(search_term),
    "completion": {
    "field": "value_suggest"
    }
}
}
}
payload = json.dumps(payload)
# print(payload)

url="http://192.168.4.36:9200/autocomplete/_suggest?pretty"
response = requests.request("GET", url, data=payload, headers=headers)

terminal response:
POST request called
糖
suggest {'error': {'root_cause': [{'type': 'unknown_named_object_exception', 'reason': 'Unknown SuggestionBuilder [autocomplete]', 'line': 1, 'col': 30}], 'type': 'unknown_named_object_exception', 'reason': 'Unknown SuggestionBuilder [autocomplete]', 'line': 1, 'col': 30}, 'status': 400}
192.168.16.225 - - [06/May/2020 10:13:17] "POST /autocomplete HTTP/1.1" 200 -

Thank you for your help.


text:
Q: would have been sitting/would have sat
*

*I would have been sitting there
if I hadn't been working.

*I would have sat there if I hadn't been working.
Which usage is correct "would have been sitting/would have sat"?

A: "I would have been sitting there" implies the sitting would have occurred over a period of time; "I would have sat there" implies more the process of sitting down (source: high school English class).  "I would have been sitting there when the bell rang" has a very different meaning than "I would have sat there when the bell rang".


text:
Q: How to store multi-lingual website information in database? I'm currently creating a multi-lingual website, and I have different types of words that are being translated all across the website. However, whats the best practice when it comes to storing this in the database?
This is what I currently do:
I have the language Norwegian and English.
My database looks like this:

Whenever I add a new language it get added into the languages table like this:

At the same time a new table will be created with looking like this language_en. Using the value in language_val.
Later on I use URL routing to retrieve en, no or whatever language and fetch the website information from the correct table.
My question is, should I rather have only 1 table and use the language_id in this one? or is it perfectly fine to split up languages into multiple tables?
Each language table would look just like this:

A: With Silverlight (and later with PHP) I've done this by putting the language's in the same table, this worked fine and was user friendly (easy to edit). Only when retrieving data you should off course only select the language you need.


text:
Q: Socket.io remove listener after being executed I want to create a listener on a socket.  Then once the listener has been executed, I want the listener to stop listening.  I used this SO:
socket.io Removing specific listener
But I cannot figure out how to have a listener destroy itself.  This is what I am thinking:
var ListenEventFunc = function() {
    /* Do some important stuff */
    socket.removeListener('ListenEvent',ListenEventFunc);
}

socket.on('ListenEvent',ListenEventFunc);

What is the correct/best way to do this?  Is there anyway I can use the this keyword to specify the function.

A: You can use this:
socket.once('ListenEvent', ListenEventFunc);

This works because Socket inherits from EventEmitter. This doesn't seem to be documented, but the code references it.


text:
Q: RecyclerView.Adapter notifyDataSetChanged() not working when is showing last item I'm implementing an endless data loading for a RecyclerView. When software detects the last item is going to be shown, it downloads new items and call to the following function (running it in the main thread):
int visibleItemCount = numberOfItemsPerRow;
int pastVisiblesItems = ((GridLayoutManager)recyclerView.getLayoutManager()).findLastVisibleItemPosition();
int totalItemCount = mLayoutManager.getItemCount();
if (loading) {
    if ((visibleItemCount+pastVisiblesItems) >= totalItemCount) {
    .
    .
    .

    //After downloading data

    loading = false;
    getActivity().runOnUiThread(new Runnable() {
        public  void  run() {
            mAdapter.notifyDataSetChanged();
        }
    });
}

However, if I scroll quickly and the last item is shown before receiving new data, notifyDataSetChanged() doesn't work. Only if I scroll up and down again, to force the render of the new data, these new data is shown.
Any idea about what is wrong?

A: You can try:
        RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

Edit:
For you to use it to determine the right position you use,
I bet your position does not reflect the appropriate condition:

*

*When the view is empty, last visible position will be -1

*When the view got one element, position will be 0

*Adapter count will be 1

Edit 2:
I got similar approach:

*

*Searching Thread which holds data in Queue

*On demand, the queue is emptied

*I got adapter
public class MyAdapter extends RecyclerView.Adapter<ItemCardAdapter.ViewHolder>

*In the adapter I got a list:
List<T> _itemList;

*

*I got methods add(item)/addAll(collection)/clear() to manage item list

*Three Overridden methods:
@Override
public int getItemCount() {
  return _itemList.size();
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) { }
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {}

*And holder:
public class ViewHolder extends RecyclerView.ViewHolder {}

*I'm managing data via Adapter.add();,  clear(); and then I call Adapter.notifidatasetChanged(); as Runnable on UI Thread  I have no issue like you
Which libraries do you use?
Mine are:

*

*appcompat-v7:22.2.0'

*support-v4:22.2.0'

*design:22.2.0'

*recyclerview-v7:22.2.0'

*cardview-v7:22.2.0'


text:
Q: Confusion on how to finish a new program? I am currently doing a project for my java class and im a total beginner so apologies because i'm sure the answer is quite obvious. A few weeks back I made a program called TravelExpenses which calculated how much a trip would cost. Now, I must make a new program that is completely different. After coding and pressing play, The same window pops up from my previous program, how do I get rid of it? Photo

A: In the package explorer, right click your new class and choose run as.. java program
The next time you press play it will launch the recent one.


text:
Q: Cmake: add_subproject & add_subfolder I currently want to add some self written classes ("mycode.cpp" and "mycode.hpp") to a big existing C++ project that is configured with Cmake. These classes are located in "myfolder" which is located in the "lib/pointrender" folder of the existing project (see dummy hierarchy below).
|- libs
|    |- core
|    |   |- ...
|    |- pointrender
|        |- myfolder
|        |     |- mycode.cpp
|        |     |- mycode.hpp
|        |- existingclasses.cpp
|        |- existingclasses.hpp
|        |- project.cmake
|- CMakeLists.txt

In the CMakesLists.txt the pointrender folder is declared as a subproject.
declare_subproject(libs/pointrender)

How do I best add my code to the existing cmake configuration? Do I add it as a subfolder in the project.cmake with a seperate CMakeLists.txt in myfolder? Or do I best add it as a subproject with a seperate project.cmake file? What's the difference?

A: This project.cmake is being include()d be some CMakeLists.txt and get's executed as part of it. Authors of project you are using rolled this out for some reason, so it's probably better to use their infrastructure to add custom code.
The usual way to do this is writing your own CMakeLists.txt and add_subdirectory()ing it from the upper level.
If you wish more details you should update your question with project.cmake contents.


text:
Q: How can I resolve Intent crashing? I'm beginner and don't know why my using Intent to layout makes my program crashed? But I used this code before and it works. Now it is not working. What are the wrong of my code?.
JAVA

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class Mobile_Grocery_App extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile__grocery__app);
    }
    public void signin(View view) {
        Intent i = new Intent(this, Sign_In.class);
        startActivity(i);
   }

XML

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/main_background"
    android:src="@drawable/mobile_grocery"
    android:scaleType="centerCrop"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="MOBILE GROCERY"
    android:id="@+id/mobile_grocery"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:textSize="45dp"
    android:textColor="#000000"
    android:gravity="center"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Application"
    android:id="@+id/application"
    android:textColor="#000000"
    android:textSize="25dp"
    android:layout_below="@+id/mobile_grocery"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:id="@+id/username"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/application"
    android:layout_alignEnd="@+id/application"
    android:layout_marginBottom="128dp"
    android:hint="Username"
    android:textColorHint="#000000"

    />

<EditText
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:id="@+id/password"
    android:layout_alignTop="@+id/username"
    android:layout_alignRight="@+id/username"
    android:layout_alignEnd="@+id/username"
    android:layout_marginTop="36dp"
    android:hint="Password"
    android:textColorHint="#000000"
    />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sign In"
    android:id="@+id/sign_in"
    android:layout_below="@+id/password"
    android:layout_alignLeft="@+id/password"
    android:layout_alignStart="@+id/password"
    android:onClick="signin"
    />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sign Up"
    android:id="@+id/sign_up"
    android:layout_below="@+id/password"
    android:layout_alignRight="@+id/password"
    android:layout_alignEnd="@+id/password"
    android:onClick="signup"
    />

Hope somebody can help me

A: The issue is due to android:onClick="signup". Everytime you declare the android:onclick property in one of the widgets in your xml, Android expects to find a method with the following signature
public void nameOfTheProperty(View view) {

}

in your case you declared public void signin(View view), but you are still missing
public void signup(View view) {

}

A: Try doing this:
 public void signin(View view) {
            Intent i = new Intent(Mobile_Grocery_App.this, Sign_In.class);
            startActivity(i);
       }


text:
Q: Nearest Region of a Point-cloud For a given examplary set of points p(2D)  with known NearestFunction nf
p={{0.840118, 0.610084}, {0.192507, 0.593158}, {0.924885,0.0381748}, {0.954353, 0.0854852},{0.68415,0.0401017}, {0.930616,0.272383}, {0.53465, 0.248715}, {0.493077, 0.813843}, {0.33337,0.749316},{0.702729, 0.748888}};

nf=Nearest[p];

I would like to define a region, which includes all neighbors inside a given range.
Graphics[{Lighter[Gray], Map[Disk[#, .25] &, p], Black, Point[p]}]

But
cloud=ImplicitRegion[Norm[Nearest[p][{x, y}][[1]] - {x,y}] < .1, {x, y}]

gives an error message  ImplicitRegion::msgs: Evaluation of {Norm[Nearest[p][{x,y}][[1]]-{x,y}]<0.1,True} generated message(s) {NearestFunction::neard}. which I didn't understand.
Perhaps I have to restrict x,y to be NumericQ but I have no idea how.
What's wrong with my attempt?
Thanks!


text:
Q: method doesn't finish running - works infinitly I tried to write simple program and stuck at some point into while loop.
From current output I see that it only print the same data.
But it should be executed at every iteration.
Snippet of code:
public void fight(Droid first, Droid second) {

        while (first.isAlive() & second.isAlive()) {

            if ((random.nextInt(10) + 1) % 2 == 0) {
                shoot(first, second);
            } else {
                shoot(second, first);
            }

            // testing output
            System.out.printf("Droid %s has %d power level%n", first.getName(), first.getPower());
            System.out.printf("Droid %s has %d power level%n", second.getName(), second.getPower());
        }

        if (first.getPower() <= 0) {
            fightResult(second);
        } else {
            fightResult(first);
        }
    }

And here is output:
Droid John has 5 power level
Droid Dik has 8 power level
Droid John has 5 power level
Droid Dik has 8 power level
Droid John has 5 power level
Droid Dik has 8 power level
Droid John has 5 power level
Droid Dik has 8 power level

I made some silly mistake and couldn't find one.
Update:
here is shoot():
private void shoot(Droid first, Droid second) {
    second.setPower(first.getImpact());
}

and Droid class:
public abstract class Droid {

    protected Random random;
    private String name;
    private int power;
    private int impact;

    public Droid(int aPower, int anImpact) {
        power = aPower;
        impact = anImpact;
    }

    public String getName() {
        return name;
    }

    public void setPower(int aPower) {
        power = aPower;
    }

    public void setImpact(int anImpact) {
        impact = anImpact;
    }

    public int getPower() {
        return power;
    }

    public int getImpact() {
        return impact;
    }

    public abstract void fight(Droid first, Droid second);

    public boolean isAlive() {
        boolean result = false;
        if (this.getPower() > 0) result = true;
        return result;
    }
}

*

*How to solve this trouble?

A: Your shoot method is incorrect, it keeps setting the droids to each other's impact value.
I suspect you'd want to subtract the impact from the droid's power instead.
Something along the lines of
private void shoot(Droid first, Droid second) {
    second.setPower(second.getPower() - first.getImpact());
}

or somewhat more OO-style:
first.shoot(second);

public void shoot(Droid second) {
    second.absorbImpact(getImpact());
}

public void absorbImpact(int impact) {
    power -= impact;
}

A: You have to call setAlive(false) for one of the Droids to end the infinite loop...
While shooting you set the power of the second Droid to the impact of the first one. But you never lower the impact of the Droids...

A: try
private void shoot(Droid first, Droid second) {
    second.setPower(second.getPower() - first.getImpact());
}

A: You seem to be using & (bitwise operator) instead of && (boolean and)

A: Change this:
while (first.isAlive() & second.isAlive())

to this
while (first.isAlive() && second.isAlive())


text:
Q: How do I progressively render a header before content in ASP.NET master pages? I have a large slow ASP.net site that uses master pages.
I've identified that the user will have a  better experience if they can see the header and navigation while the rest of the page is being generated/processed/loaded from  the database.
I've done some simple tests and I can do Response.Write() followed by Response.Flush() in page_load(), and IIs will use chunked encoding and send the output to the browser immediately while the rest of the page renders.
I want to do the same thing, but only send the master page header and navigation.
Any pointers on how to achieve this?
Using ASP.net 4 and IIs 7.5
Edit
If anyone can give some pointers on how to change the site to use AJAX without having to change every page and link, I'd appreciate it. Thanks!

A: If you flush the response stream at some point manually and do not manually set the content length it will enable chunked encoding.
This question seems related: How can I set Transfer-Encoding to chunked, explicitly or implicitly, in an ASP.NET response?
And this blog post talks about response flushing and chunked encoding: http://www.rahulsingla.com/blog/2010/06/asp-net-sets-the-transfer-encoding-as-chunked-on-premature-flushing-the-response

A: I suggest you use control caching. Asp.Net provides native caching of pages and controls.
See these links to know more.
ASP.NET Caching: Techniques and Best Practices
http://msdn.microsoft.com/en-us/library/aa478965.aspx
ASP.NET Caching
http://msdn.microsoft.com/en-us/library/xsbfdd8c(v=VS.100).aspx
Control caching
As you have mentioned, it appears that you already use page-caching. Try using control-caching to further improve the caching. To use control caching, place PartialCachingAttribute over the control class.
You can use the ControlCachePolicy of the control to set caching behavior:
control.GetCachePolicy()

A: I would suggest tracing the page, and try to figure out why exactly the page is rendering slow. The following might help...
http://www.dotnetscraps.com/dotnetscraps/post/How-to-troubleshoot-issues-with-Page-Rendering-in-ASPNET.aspx
And use DIVs in place of TABLEs!
Regarding AJAX usage, AFAIK... there is no shortcut. You can use AJAX script manager in your master page, and use the script manager proxy to the pages where you want to ajaxify the page. Change your Form to introduce an Update panel and you should be good for most pages.

A: This might be helpful to you.
I alway use yslow for FF alongwith firebug to check out the performance.
https://addons.mozilla.org/en-us/firefox/addon/yslow/
https://addons.mozilla.org/en-US/firefox/addon/firebug/
http://msdn.microsoft.com/en-us/library/ff647787.aspx
http://developer.yahoo.com/performance/rules.html
Thanks


text:
Q: PowerBuilder App - Database transaction information not available We have an older PowerBuilder application which is getting moved from Windows 7 to WIndows 10.  When launched on Windows 10 it only gives the following error:
Database transaction information not available
Call SetTrans or SetTransObject function.
Error prompt
Windows 10 does not have the following drivers that Windows 7 has, and I'm listing them below.  Could that be one of the reasons?  I don't want to sway anyone thinking about drivers though.

*

*ODBC Driver 11 for SQL Server, Version: 2014.120.2000.08, Microsoft
Corporation, File: MSODBCSQL11, Date: 2/21/2014

*SQL Native Client, Version: 2005.90.5000.00, Microsoft Corporation,
SQLNCLI.DLL, Date: 12/10/2010

*SQL Server, Version 6.01.7601.17514, Microsoft Corporation,
SQLSRV32.DLL, Date: 11/20/2010

*SQL Server Native Client 10.0, Version 2009.100.1600.01, Microsoft
Corporation, SQLNCLI10.DLL, Date 4/3/2010

*SQL Server Native Client 11.0, Version 2011.110.2100.60, Microsoft
Corporation, SQLNCLI11.DLL, 2/11/2012

The database is SQL Server 2008 R2, and we know it isn't supported from Windows 10, but other PowerBuilder applications on Windows 10 work with that SQL Server version.  That's one of the reasons we're confused.

A: IF there are no SQL drivers you won't be connecting to the database.  You need to install the drivers.  Exactly which one I can't say since you provided no information on which connection parameters the application uses.

A: Doublecheck that you've installed the 32-bit driver for SQLServer 2008 R2.  Installing the SQLServer client on Windows10 will install the 64-bit driver by default...
-Paul-


text:
Q: rnoaa station data pull times out I'm trying to pull NOAA data using R. I've done this pull before but all of a sudden it's not working. I have rnoaa loaded (package/library) and I have an authorization key from the NOAA. I try to run this command:
station_data <- ghcnd_stations()

And I get this error:
Error in curl::curl_fetch_memory(x$url$url, handle = x$url$handle) : Timeout was reached: Operation timed out after 10000 milliseconds with 0 out of 0 bytes received

I found pages online that suggested updating everything. First I updated all my packages and then updated to a new version of R. All that done, it's still giving me a timeout message with this simple command. I know that the ghcnd pull sometimes take a while, but it's timing out after about 10 seconds. Is this just an noaa issue (as is sometimes the case) and I should try again tomorrow? Or is there something I can actually do to make this work? Can I change the timeout period so that it waits longer? Is the NOAA just overloaded because of the hurricane?

A: Looks like it was just something on the NOAA end of things. It took a day, but it's finally back up and running properly.


text:
Q: echo xml in php and can used to decode in php I have script :
<?php
$url = 'http://www.example.com';
$post = 'response=xml';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST ,1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_URL, $url)
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
echo $result;
?>

but it show like this :
<?xml version="1.0" encoding="utf-8"?> <interface-response> <test>this is test</test><Done>true</Done> <RequestDateTime>1/16/2016 7:50:01 AM</RequestDateTime> <debug><![CDATA[]]></debug> </interface-response>

it's look text and can't used,i want echo it look like this
it look this but i want to look this

A: Add the below line as the first statement in php script. That solves it
header('Content-type: application/xml');


text:
Q: Need help to fix mozilla addon I need help to fix my mozilla addon issue. I need to append my html code in body for this i send request on my server to check user session. After request reponse i want to append html according to user status. In my code it says jQuery not define. here's my main.js code:
var buttons = require('sdk/ui/button/action');
var tabs = require("sdk/tabs");
var button = buttons.ActionButton({
id: "mozilla-link",
label: "Visit Mozilla",
icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png",
    "64": "./icon-64.png"
}

});
var data = require("sdk/self").data;
var request = require("sdk/request");
var contentScriptString = '';
var text ='';
var pageMod = require("sdk/page-mod").PageMod({
include: "*",
contentScriptFile: data.url("jquery.min.js"),
contentScriptWhen: "ready",
onAttach: function(worker) {
    var tabUrl = worker.tab.url;

    var mapObj = {
        'http://': "",
        'https://': ""

    };
    var re = new RegExp(Object.keys(mapObj).join("|"), "gi");
    tabUrl = tabUrl.replace(re, function(matched) {
        return mapObj[matched];
    });
    tabUrl = tabUrl.split("/");
    if (tabUrl) {
        request.Request({
            url: "https://www.karmora.com/checkstore/" + tabUrl[0],
            onComplete: function(response) {
                console.info(response.json);
                if (response.json.storeId !== null) {
                    var storeName = response.json.storeTitle;
                    var amount = response.json.commPercentage;
                    var store_id = response.json.storeId;
                    text = '';
                    if (response.json.loginStatus) {

                        if (response.json.visitStatus === true) {
                            text = '';
                        } else {
                            var url_check = "https://www.karmora.com/index/VisitExtension/" + store_id;
                            request.Request({
                                url: url_check,
                                onComplete: function(response) {
                                    location.href = response.json;
                                }
                            });
                            console.info(url_check);
                            text = '';

                        }
                    } else {
                        text = '';
                    }
                    writecanvesPopup(text);
                    //}
                    // });

                }
                function writecanvesPopup(text) {

                    jQuery("body").append('

' + text + '

Get ' + amount + '

at ' + storeName + '

');
                }

            }
        }).get();
    }
}
});

A: This is because you're calling jQuery from the browser context, not in the DOM context. You can't manipulate the page in browser context. Take a look at Content Scripts that can manipulate the DOM.
See it in action: https://gist.github.com/AdrianArroyoCalle/f8535807ebd738e938b7