text:
Q: Emit signal if all children widgets lose focus I have a QStackedWidget which holds several pages full of various QLineEdit and QComboBox children. I want to emit a signal whenever the QStackedWidget no longer has any child with focus (given that a child had focus to begin with). So moving from child to child will not emit a signal, but once a widget is selected outside of the QStackedWidget, a signal is emitted. Any advice on how to implement this? I've looked at InstallEventFilter and QSignalMapper, but neither of those appear to fit my needs. Any advice would be appreciated.

A: You can connect to the QApplication::focusChanged signal in order to evaluate the focus widgets within a corresponding slot. The clean way to do this is to derive from QStackedWidget:
class StackedFocusWidget : public QStackedWidget {

    Q_OBJECT

public:

    StackedFocusWidget(QWidget *parent = 0) : QStackedWidget(parent) {
        connect(qApp, SIGNAL(focusChanged(QWidget *, QWidget *)), this, SLOT(onFocusChanged(QWidget *, QWidget *)));
    }

private slots:

    void onFocusChanged(QWidget *old, QWidget *now) {
        bool focusOld = old != 0 && isAncestorOf(old);
        bool focusNow = now != 0 && isAncestorOf(now);
        if (!focusOld && focusNow) {
            emit gotFocus();
        } else if (focusOld && !focusNow) {
            emit lostFocus();
        }
    }

signals:

    void gotFocus();
    void lostFocus();
};

The signals StackedFocusWidget::gotFocus and StackedFocusWidget::lostFocus will be emitted whenever the stacked widget or any of its childs receives or loses focus.

A: This is a bit tricky. Even when cycling from child to child, there is a brief period after a child loses focus and before another child gains focus where no child of the stacked widget has focus. Although this state is extremely short lived, it's a matter of fact.
The only option I can see is to decide how long a period between a child widget losing focus and no child widget gaining focus you would consider to be long enough to declare that indeed, no child widget has focus anymore. This would be a mechanism similar to what is used to distinguish two single mouse clicks from one double-click.
This could be achieved using a timer and an event filter in the parent registered with each child, that looks for focus in and out events. Set the timer for some interval (100 ms?) and start it whenever a focus out event is received. If you receive a focus in event while the timer is still running, stop the timer. If the timer completes you can fire a signal of your own to indicate that no child widget has focus.


text:
Q: PHP Session Handler not writing to database I need help with the class below - its not writing to the database and I have no idea why.  I know the "read" method is called, but not the "write" method :S
This is the code I'm using:

require '../application/database.php';
$db = new Database('localhost', 'root', '', 'gemgale');

require '../application/session.php';
$session = new Session($db);

session_set_save_handler(
    array(&$session, 'open'),
    array(&$session, 'close'),
    array(&$session, 'read'),
    array(&$session, 'write'),
    array(&$session, 'destroy'),
    array(&$session, 'clean')
);
session_start();
var_dump($session);
$_SESSION['something'] = "gem";
var_dump($_SESSION);
#$session->delete();
#var_dump($_SESSION);

and this is the class ...

class Session
{
    ###########################################################################
    private $expiry = 3600;
    private $securityCode = "gnvriev847e8grdinvrdg5e8g4r7fr7rdvreh8^£*^£FGgyhf";
    private $tableName = "session_data";
    ###########################################################################
    private $dbh;

    function __construct(Database $db)
    {
        $this->dbh = $db->getConnection();

        ini_set('session.cookie_lifetime', 0);
        ini_set('session.gc_maxlifetime', $this->expiry);
    }

    function open($save_path, $session_name)
    {
        return true;
    }

    function close()
    {
        return true;
    }

    function read($session_id)
    {
        echo $session_id;
        print "READING";
        $time = time();
        $hua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $hua = $hua . $this->securityCode;
        $hua = md5($hua);
        try {
            $stmt = $this->dbh->prepare("
            SELECT session_data
            FROM :tableName
            WHERE session_id = :sesID
              AND session_expire > :time
              AND http_user_agent = :hua
            LIMIT 1
        ");
            $stmt->bindParam("tableName", $this->tableName);
            $stmt->bindParam("sesID", $session_id);
            $stmt->bindParam("time", $time);
            $stmt->bindParam("hua", $hua);
            $stmt->execute();
        } catch (PDOException $e) {
            echo $e->getMessage();
            return false;
        }
        $rs = $stmt->fetch();
        if (!$rs)
            return '';
        else
            return $rs['session_data'];

    }

    function write($session_id, $session_data)
    {
        print "WRITING";
        $expiry = time() + $this->expiry;
        $hua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $hua = $hua . $this->securityCode;
        $hua = md5($hua);
        try {
            $stmt = $this->dbh->prepare("
                INSERT INTO :tableName (
                  session_id,
                  http_user_agent,
                  session_data,
                  session_expiry
                )
                VALUES (
                  :sessID,
                  :hua,
                  :sdata,
                  :expiry
                )
                ON DUPLICATE KEY UPDATE
                  session_data = :sdata,
                  session_expire = :expiry
            ");

            $stmt->bindParam("tableName", $this->tableName);
            $stmt->bindParam("sessID", $session_id, PDO::PARAM_STR);
            $stmt->bindParam("hua", $hua);
            $stmt->bindParam("sdata", $session_data, PDO::PARAM_STR);
            $stmt->bindParam("expiry", $expiry);
            $stmt->execute();
        } catch (PDOException $e) {
            echo $e->getMessage();
            return false;
        }
        if ($stmt->rowCount() > 1)
            return true;
        else
            return '';

    }

    function destroy($session_id)
    {
        try {
            $stmt = $this->dbh->prepare("
                DELETE FROM :tableName
                WHERE session_id = :id
            ");
            $stmt->bindParam("tableName", $this->tableName, PDO::PARAM_STR);
            $stmt->bindParam("id", $session_id, PDO::PARAM_STR);
            $stmt->execute();
        } catch (PDOException $e) {
            echo $e->getMessage();
            return false;
        }
        return true;
    }

    function clean($maxLifeTime)
    {
        try {
            $x = time() - $maxLifeTime;
            $stmt = $this->dbh->prepare("
                DELETE FROM :tableName
                WHERE session_expire < :x
            ");
            $stmt->bindParam("tableName", $this->tableName, PDO::PARAM_STR);
            $stmt->bindParam("x", $x, PDO::PARAM_INT);
            $stmt->execute();
        } catch (PDOException $e) {
            die($e->getMessage());
        }
        return true;
    }

    function delete()
    {
        $oldID = session_id();
        session_regenerate_id();
        $this->destroy($oldID);
        session_unset();
        session_destroy();
    }

    function getActive()
    {
        $this->clean($this->expiry);
        try {
            $stmt = $this->dbh->prepare("
                SELECT COUNT(session_id) as count
                FROM :tableName
            ");
            $stmt->bindParam("tableName", $this->tableName, PDO::PARAM_STR);
            $stmt->execute();
            $rs = $stmt->fetch();
            return $rs['count'];
        } catch (PDOException $e) {
            die($e->getMessage());
        }
    }

}

Hope you guys can help :)
Thanks,
Gem

A: One, you don't need to pass by reference.  Do this instead:
session_set_save_handler(
   array($session, 'open'),
   array($session, 'close'),
   array($session, 'read'),
   array($session, 'write'),
   array($session, 'destroy'),
   array($session, 'clean')
);

To test if the save/write is working, you could try this:
session_start();
$_SESSION['something'] = "gem";
session_write_close();
echo "- Foo";

This should trigger a write to the session store and flush anything to be written.  In this case it should display WRITING- Foo if your write method is being called.
If the DB is not being written, but the method is being called, there are other issues.
The first thing I'd look at is the :tableName you're replacing in the prepared statement.  You cannot prepare-replace column names or tables. Change your statement to this:
 $stmt = $this->dbh->prepare("
            INSERT INTO ".$this->tableName."  (
              session_id,
              http_user_agent,
              session_data,
              session_expiry
            )
            VALUES (
              :sessID,
              :hua,
              :sdata,
              :expiry
            )
            ON DUPLICATE KEY UPDATE
              session_data = :sdata,
              session_expire = :expiry
        ");

If you do substitue in variables for table names or columns, make sure you whitelist them before using to be safe against opening an injection hole.

redpajama_set_name: RedPajamaStackExchange


text:
Q: reload data never stops in tableview I want to reload the data in tableview when I finish the query in Parse.com but once it starts reloading, it never stops.
Here's the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WishlistCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" ];
    wishlist *temp=(wishlist*)[_dataSource objectAtIndex:[indexPath indexAtPosition:1]];
    PFQuery * retrieveExpos = [PFQuery queryWithClassName:@"_User"];
    [retrieveExpos whereKey:@"username" equalTo:temp.exponom];
    [retrieveExpos findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        NSLog(@"%@",objects);
        if (!error) {
            exposArray =[[NSArray alloc] initWithArray:objects];
        }
    }];

    PFQuery * retrieveImage = [PFQuery queryWithClassName:@"CarDescription"];
    [retrieveImage whereKey:@"objectId" equalTo:temp.idvoiture];
    [retrieveImage findObjectsInBackgroundWithBlock:^(NSArray *objects1, NSError *error) {
        NSLog(@"%@",objects1);
        if (!error) {

            exposArray1 =[[NSArray alloc] initWithArray:objects1];

        }
        [tableview reloadData];

    }];

    PFObject * tempObject = [exposArray objectAtIndex:indexPath.row];
    cell.EXPONAME.text=[tempObject objectForKey:@"Exponame"];
    cell.PHONENUMBER.text=[tempObject objectForKey:@"Number"];
    PFObject * tempObject1 = [exposArray1 objectAtIndex:indexPath.row];
    PFFile * imageFile= [tempObject1 objectForKey:@"FrontImage"];
    cell.loadingSpinner.hidden=NO;

    [cell.loadingSpinner startAnimating];
    [imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        if (!error) {
            //                       NSLog(@"%@",data);
            cell.CarImage.image=[UIImage imageWithData:data];
            [cell.loadingSpinner stopAnimating];
            cell.loadingSpinner.hidden=YES;
        }
    }];
    return  cell;
}

A: I think you run into an never-ending recursion
reloadData makes tableView to build it up again. One of the last steps is to create cells for all visible rows. in tableView: cellForRowAtIndexPath:, where you trigger reloadData again (although it is deferred in a block) — resulting in a circle.
Another issue could be that you call [tableView reloadData] in a background thread. UI in general has to happen on the main thread.


text:
Q: AES decryption after sending message to IP address So I am making an app that sends secure messages to the specified IP address. I am using AES to encrypt the message and that part works great. I am able to encrypt the message and also decrypt it before I send the message. However, when I try to decrypt a message that has been recieved from the server, I can not decrypt it. It gets displayed in it's encrypted form.
I get this error "java.lang.NumberFormatException: Invalid int: "ne"" and I think it may have to do with the character encoding or something? Is a string altered in any way when it is sent over a network?
Here are snippets that may be related to the issue.
public static String encrypt(String seed, String cleartext)
        throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] result = encrypt(rawKey, cleartext.getBytes());
    return toHex(result);
}

public static String decrypt(String seed, String encrypted)
        throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] enc = toByte(encrypted);
    byte[] result = decrypt(rawKey, enc);
    return new String(result);
}

public static byte[] toByte(String hexString) {
    int len = hexString.length() / 2;
    byte[] result = new byte[len];
    for (int i = 0; i < len; i++)
        result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                16).byteValue();
    return result;
}

public static String toHex(byte[] buf) {
    if (buf == null)
        return "";
    StringBuffer result = new StringBuffer(2 * buf.length);
    for (int i = 0; i < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
}

This is where I do the decryption for the message to be displayed.
while (!goOut) {
    if (dataInputStream.available() > 0) {
        incoming = dataInputStream.readUTF();

        if(encrypt == true) {
            try{
                msgLog += AESHelper.decrypt(seed,incoming);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else msgLog += incoming;

        MainActivity.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                chatMsg.setText(msgLog);
            }
        });

This is encrypting the message:
OnClickListener buttonEncryptOnClickListener = new OnClickListener()   {
        public void onClick(View v) {
            if (chatClientThread == null) {
                return;
            }
            if (editTextSay.getText().toString().equals("")) {
                return;
            }

            if(!editTextSay.getText().toString().equals("")){

                String message = editTextSay.getText().toString();
                encrypt = true;
                int secLvl = Integer.parseInt(editTextSecurity.getText().toString());

                String encryptedMsg;
                try {
                     encryptedMsg = AESHelper.encrypt(seed, message);
                    textEncryptedmsg.setText(encryptedMsg);
                    textEncryptedmsg.setVisibility(View.VISIBLE);

                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

        }
    };

This is sending the message:
OnClickListener buttonSendOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (editTextSay.getText().toString().equals("")) {
                return;
            }

            if(chatClientThread==null){
                return;
            }

            if (encrypt == true){

                chatClientThread.sendMsg(textEncryptedmsg.getText().toString() + "\n");
            } else {
                chatClientThread.sendMsg(editTextSay.getText().toString() + "\n");
            }

            editTextSay.setText("");
            textEncryptedmsg.setText("");
            textDecryptedmsg.setText("");
            encrypt = false;
            incomingmsg.setVisibility(View.VISIBLE);
        }

    };

A: I'll assume that you're sending the ciphertext in a hex encoded form. DataInputStream#readUTF() reads a single Unicode character from the stream. Since you're sending hex characters this will mean that a single ciphertext byte can be constructed from two of such Unicode characters.
The problem is that AES operates on blocks. Trying to decrypt every single "half"-byte separately won't work.
You will need to rewrite the decryption method to either

*

*use streaming decryption or

*read the whole ciphertext and decrypt in one go.

If you want to try streaming decryption, then you have basically two options:

*

*update the internal buffer of a Cipher object using the offset-version of Cipher#update() or

*use a CipherInputStream.

Here is an (pseudo-code) example of reading the whole thing before trying to decrypt it:
StringBuilder incoming = new StringBuilder();
while (!goOut && ) {
    incoming.append(dataInputStream.readUTF());
}
if(encrypt == true) {
    try{
        msgLog += AESHelper.decrypt(seed, incoming.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
} else msgLog += incoming;

A: I found a way around the issue without using CipherInputStream.
Whenever I encrypted a message and sent it, the encryption/decryption algorithm would not decrypt the message received from the server. Since the output encrypted message was identical to what I sent, I printed the incoming encrypted message into a TextView then I copied the TextView into a String and decrypted it and it works great now.
 while (!goOut) {

            if (dataInputStream.available() > 0) {

                final String incoming = dataInputStream.readUTF();

                MainActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                        incomingmsg.setText(incoming);
                        mustDecrypt = incomingmsg.getText().toString();

                        if (encrypt)
                            try {
                                mustDecrypt = AESHelper.decrypt(seed, mustDecrypt);
                                msgLog += mustDecrypt;

                            } catch (Exception e){
                                e.printStackTrace();
                            }
                            else msgLog += mustDecrypt;

                        chatMsg.setText(msgLog);
                    }
                });
            }


text:
Q: remove the ubuntu-desktop package How does one go about removing the packages installed by ubuntu-desktop. I couldn't imagine going back to that after using LXDE.

A: This only applies to Oneric 11.10
These removal commands were created based on what Ubuntu, Kubuntu, etc. packages were added to a default Lubuntu installation. It's possible that the commands might remove some other packages you have since added to the default and want to keep. If that's the case, keep track of which packages those are and reinstall them. Your settings should still be there.
sudo apt-get remove acpi-support acpid adium-theme-ubuntu aisleriot apg app-install-data app-install-data-partner appmenu-gtk appmenu-gtk3 appmenu-qt apt-xapian-index apturl apturl-common at-spi2-core avahi-autoipd bamfdaemon banshee banshee-extension-soundmenu banshee-extension-ubuntuonemusicstore baobab binfmt-support bluez-alsa bluez-cups bluez-gstreamer branding-ubuntu brasero brasero-cdrkit brasero-common brltty c2esp checkbox checkbox-gtk cli-common compiz compiz-core compiz-gnome compiz-plugins-default compiz-plugins-main-default compizconfig-backend-gconf cups-bsd dc deja-dup dmz-cursor-theme doc-base duplicity dvd+rw-tools empathy empathy-common eog espeak espeak-data evolution-data-server evolution-data-server-common example-content exiv2 firefox firefox-globalmenu firefox-gnome-support foo2zjs gamin gbrainy gcalctool gcc gcc-4.6 gedit gedit-common geoclue geoclue-ubuntu-geoip ghostscript-x ginn gir1.2-atspi-2.0 gir1.2-gconf-2.0 gir1.2-gmenu-3.0 gir1.2-gtksource-3.0 gir1.2-indicate-0.6 gir1.2-launchpad-integration-3.0 gir1.2-peas-1.0 gir1.2-totem-1.0 gir1.2-totem-plparser-1.0 gir1.2-wnck-3.0 gnome-accessibility-themes gnome-codec-install gnome-control-center gnome-control-center-data gnome-desktop3-data gnome-font-viewer gnome-games-common gnome-icon-theme-symbolic gnome-mahjongg gnome-media gnome-menus gnome-nettool gnome-online-accounts gnome-orca gnome-power-manager gnome-screensaver gnome-screenshot gnome-search-tool gnome-session gnome-session-bin gnome-session-canberra gnome-session-common gnome-settings-daemon gnome-sudoku gnome-system-log gnome-system-monitor gnome-terminal gnome-terminal-data gnome-utils-common gnomine growisofs gstreamer0.10-alsa gstreamer0.10-gconf gstreamer0.10-plugins-base-apps gstreamer0.10-pulseaudio gstreamer0.10-tools guile-1.8-libs gwibber gwibber-service gwibber-service-facebook gwibber-service-identica gwibber-service-twitter hplip hplip-cups hplip-data hwdata ibus ibus-gtk ibus-gtk3 ibus-pinyin ibus-pinyin-db-android ibus-pinyin-db-open-phrase ibus-table im-switch indicator-appmenu indicator-datetime indicator-power indicator-session indicator-sound inputattach intel-gpu-tools kerneloops-daemon lftp libappindicator0.1-cil libasound2-plugins libatk-adaptor libatspi2.0-0 libavahi-gobject0 libbamf0 libbamf3-0 libboost-serialization1.46.1 libbrasero-media3-1 libbrlapi0.5 libc-dev-bin libc6-dev libcamel-1.2-29 libcanberra-pulse libcompizconfig0 libcrypt-passwdmd5-perl libdbus-glib1.0-cil libdbus1.0-cil libdbusmenu-qt2 libdconf-dbus-1-0 libdconf-qt0 libdconf0 libdecoration0 libdotconf1.0 libebackend-1.2-1 libebook1.2-12 libecal1.2-10 libedata-book-1.2-11 libedata-cal-1.2-13 libedataserver1.2-15 libedataserverui-3.0-1 libespeak1 libexempi3 libexiv2-10 libfile-copy-recursive-perl libfolks-telepathy25 libfolks25 libgail-3-common libgail-common libgamin0 libgconf2.0-cil libgd2-xpm libgdata-common libgdata1.7-cil libgdata13 libgdiplus libgeoclue0 libgexiv2-0 libgkeyfile1.0-cil libglew1.5 libglewmx1.5 libglib2.0-bin libglib2.0-cil libglib2.0-data libgmime-2.4-2 libgmime2.4-cil libgnome-control-center1 libgnome-desktop-3-2 libgnome-media-profiles-3.0-0 libgnome-menu-3-0 libgnome-menu2 libgnome2-common libgnomekbd-common libgnomekbd7 libgnomevfs2-0 libgnomevfs2-common libgoa-1.0-0 libgomp1 libgtk-sharp-beans-cil libgtk-vnc-2.0-0 libgtk2.0-cil libgtkmm-3.0-1 libgtksourceview-3.0-0 libgtksourceview-3.0-common libgtkspell3-0 libgudev1.0-cil libgvnc-1.0-0 libgweather-3-0 libgweather-common libgwibber-gtk2 libgwibber2 libhyphen0 libibus-1.0-0 libidl0 libido3-0.1-0 libjson-glib-1.0-0 liblaunchpad-integration1.0-cil liblightdm-gobject-1-0 liblouis-data liblouis2 libmetacity-private0 libmission-control-plugins0 libmng1 libmono-addins-gui0.2-cil libmono-addins0.2-cil libmono-cairo4.0-cil libmono-corlib4.0-cil libmono-csharp4.0-cil libmono-i18n-west4.0-cil libmono-i18n4.0-cil libmono-posix4.0-cil libmono-security4.0-cil libmono-sharpzip4.84-cil libmono-system-configuration4.0-cil libmono-system-core4.0-cil libmono-system-drawing4.0-cil libmono-system-security4.0-cil libmono-system-xml4.0-cil libmono-system4.0-cil libmono-zeroconf1.0-cil libmysqlclient16 libmythes-1.2-0 libnotify-bin libnotify0.4-cil libnux-1.0-0 libnux-1.0-common liboauth0 libopencc1 liborbit2 liboverlay-scrollbar-0.2-0 liboverlay-scrollbar3-0.2-0 libpeas-1.0-0 libpeas-common libprotobuf7 libprotoc7 libpulse-mainloop-glib0 libqt4-dbus libqt4-declarative libqt4-network libqt4-opengl libqt4-script libqt4-sql libqt4-sql-mysql libqt4-svg libqt4-xml libqt4-xmlpatterns libqtbamf1 libqtcore4 libqtdee2 libqtgconf1 libqtgui4 libquadmath0 libquvi0 libraptor2-0 librasqal3 librdf0 libreoffice-base-core libreoffice-calc libreoffice-common libreoffice-core libreoffice-draw libreoffice-emailmerge libreoffice-gnome libreoffice-gtk libreoffice-help-en-us libreoffice-impress libreoffice-math libreoffice-style-human libreoffice-writer librest-0.7-0 librsync1 libsane-hpaio libsdl1.2debian-pulseaudio libspeechd2 libspeexdsp1 libstlport4.6ldbl libsyncdaemon-1.0-1 libtaglib2.0-cil libtelepathy-farsight0 libtelepathy-logger2 libtextcat-data libtextcat0 libtotem-plparser17 libtotem0 libubuntuone-1.0-1 libubuntuone1.0-cil libunique-1.0-0 libunity-2d-private0 libunity-core-4.0-4 libunity-misc4 libutempter0 libuuid-perl libwmf0.2-7-gtk libwnck-3-0 libwnck-3-common libwnck-common libwnck22 libxp6 libxres1 libyajl1 libyaml-tiny-perl libzeitgeist-1.0-1 light-themes lightdm linux-libc-dev make media-player-info metacity metacity-common mono-4.0-gac mono-gac mono-runtime mousetweaks mscompress mysql-common nautilus nautilus-sendto nautilus-sendto-empathy nautilus-share notify-osd notify-osd-icons nux-tools onboard oneconf openprinting-ppds overlay-scrollbar pinyin-database pkg-config plymouth-theme-ubuntu-logo protobuf-compiler ptouch-driver pulseaudio pulseaudio-esound-compat pulseaudio-module-bluetooth pulseaudio-module-gconf pulseaudio-module-x11 pulseaudio-utils pxljr python-brlapi python-configglue python-dateutil python-egenix-mxdatetime python-egenix-mxtools python-farsight python-gconf python-ibus python-imaging python-indicate python-libproxy python-louis python-openssl python-pam python-papyon python-pexpect python-piston-mini-client python-protobuf python-pyatspi2 python-pyinotify python-serial python-speechd python-telepathy python-twisted-bin python-twisted-core python-twisted-names python-twisted-web python-ubuntuone-client python-ubuntuone-control-panel python-ubuntuone-storageprotocol python-uno python-virtkey python-webkit python-wnck qdbus qt-at-spi radeontool rastertosag-gdi rdesktop rfkill rtkit sane-utils seahorse shotwell sni-qt software-center speech-dispatcher splix ssh-askpass-gnome syslinux syslinux-common telepathy-butterfly telepathy-gabble telepathy-haze telepathy-idle telepathy-indicator telepathy-logger telepathy-mission-control-5 telepathy-salut thunderbird thunderbird-globalmenu thunderbird-gnome-support tomboy toshset totem totem-common totem-mozilla totem-plugins ttf-opensymbol ubufox ubuntu-artwork ubuntu-desktop ubuntu-docs ubuntu-mono ubuntu-sounds ubuntu-sso-client ubuntu-system-service ubuntu-wallpapers ubuntuone-client ubuntuone-client-gnome ubuntuone-control-panel ubuntuone-control-panel-gtk ubuntuone-couch ubuntuone-installer unity unity-2d unity-2d-launcher unity-2d-panel unity-2d-places unity-2d-spread unity-asset-pool unity-common unity-greeter unity-lens-applications unity-lens-files unity-lens-music unity-scope-musicstores unity-services uno-libs3 update-inetd ure usb-creator-common usb-creator-gtk vinagre vino whois wodim xbitmaps xcursor-themes xdg-user-dirs-gtk xdiagnose xfonts-mathml xterm xul-ext-ubufox zeitgeist zeitgeist-core zeitgeist-datahub zeitgeist-extension-fts zenity zenity-common && sudo apt-get install lubuntu-desktop

Reference
Getting Back to a Pure LXDE on Ubuntu


text:
Q: Is it possible to add JPA annotation to superclass instance variables? I am creating entities that are  the same for two different tables. In order do table mappings etc. different for the two entities but only have the rest of the code in one place - an abstract superclass. The best thing would be to be able to annotate generic stuff such as column names (since the will be identical) in the super class but that does not work because JPA annotations are not inherited by child classes. Here is an example:
public abstract class MyAbstractEntity {

  @Column(name="PROPERTY") //This will not be inherited and is therefore useless here
  protected String property;

  public String getProperty() {
    return this.property;
  }

  //setters, hashCode, equals etc. methods
}

Which I would like to inherit and only specify the child-specific stuff, like annotations:
@Entity
@Table(name="MY_ENTITY_TABLE")
public class MyEntity extends MyAbstractEntity {

  //This will not work since this field does not override the super class field, thus the setters and getters break.
  @Column(name="PROPERTY")
  protected String property;

}

Any ideas or will I have to create fields, getters and setters in the child classes?
Thanks,
Kris

A: You might want to annotate MyAbstractEntity with @MappedSuperclass class so that hibernate will import the configuration of MyAbstractEntity in the child and you won't have to override the field, just use the parent's. That annotation is the signal to hibernate that it has to examine the parent class too. Otherwise it assumes it can ignore it.

A: Mark the superclass as
@MappedSuperclass

and remove the property from the child class.

A: Annotating your base class with @MappedSuperclass should do exactly what you want.

A: Here is an example with some explanations that may help.
@MappedSuperclass:

*

*Is a convenience class

*Is used to store shared state & behavior available to child classes

*Is not persistable

*Only child classes are persistable

@Inheritance specifies one of three mapping strategies:

*

*Single-Table

*Joined

*Table per Class

@DiscriminatorColumn is used to define which column will be used to distinguish between child objects.
@DiscriminatorValue is used to specify a value that is used to distinguish a child object.
The following code results in the following:

You can see that the id field is in both tables, but is only specified in the AbstractEntityId @MappedSuperclass.
Also, the @DisciminatorColumn is shown as PARTY_TYPE in the Party table.
The @DiscriminatorValue is shown as Person as a record in the PARTY_TYPE column of the Party table.
Very importantly, the AbstractEntityId class does not get persisted at all.
I have not specified @Column annotations and instead are just relying on the default values.
If you added an Organisation entity that extended Party and if that was persisted next, then the Party table would have:

*

*id = 2

*PARTY_TYPE = "Organisation"

The Organisation table first entry would have:

*

*id = 2

*other attribute value associated specifically with organisations

    @MappedSuperclass
    @SequenceGenerator(name = "sequenceGenerator",
            initialValue = 1, allocationSize = 1)
    public class AbstractEntityId implements Serializable {

        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(generator = "sequenceGenerator")
        protected Long id;

        public AbstractEntityId() {}

        public Long getId() {
            return id;
        }
    }

    @Entity
    @Inheritance(strategy = InheritanceType.JOINED)
    @DiscriminatorColumn(name = "PARTY_TYPE",
            discriminatorType = DiscriminatorType.STRING)
    public class Party extends AbstractEntityId {

        public Party() {}

    }

    @Entity
    @DiscriminatorValue("Person")
    public class Person extends Party {

        private String givenName;
        private String familyName;
        private String preferredName;
        @Temporal(TemporalType.DATE)
        private Date dateOfBirth;
        private String gender;

        public Person() {}

        // getter & setters etc.

    }

Hope this helps :)

A: This is old, but I recently dealt with this and would like to share my solution. You can add annotations to an overridden getter.
@MappedSuperclass
public abstract class AbstractEntity<ID extends Serializable> implements Serializable {

  @Column(name = "id", nullable = false, updatable = false)
  @Id
  private ID id;

  public ID getId() {
    return id;
  }

  ...

}

@Entity
@Table(name = "address")
public final class Address extends AbstractEntity<UUID> implements Serializable {

  ...

  @Override
  @GeneratedValue(generator = "UUID")
  @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
  public final UUID getId() {
    return super.getId();
  }

  ...

}


text:
Q: Creating new row values within same pandas dataframe based on difference of other row values Below is an existing df
           data = np.array([['','Market','Product Code','Week','Sales','Units'],
            ['Total Customers',123,1,500,400],
            ['Total Customers',123,2,400,320],
            ['Major Customer 1',123,1,100,220],
            ['Major Customer 1',123,2,230,230],
            ['Major Customer 2',123,1,130,30],
            ['Major Customer 2',123,2,20,10],
            ['Total Customers',456,1,500,400],
            ['Total Customers',456,2,400,320],
            ['Major Customer 1',456,1,100,220],
            ['Major Customer 1',456,2,230,230],
            ['Major Customer 2',456,1,130,30],
            ['Major Customer 2',456,2,20,10]])

            df =pd.DataFrame(data)

I wish to create new rows based on the value difference between the row value in the 'Market' column (Total Customers) and  the row values in the 'Market' Column (Major Customer 1 + Major Customer 2).  I wish to assign the new row value in 'Market' Column as 'Remaining Customers' and append within the same df.
Overall, I'm basically trying to work out the remaining Sales and Unit 'Gap' of the market
This is what I have tried so far using loc but I keep getting a key error.  Can anyone help?
 df.loc[df['Market'] == 'Remaining Customers'] =
                        df.loc[df['Market'] == 'Total Customers']-
                        (df.loc[df['Market'] == 'Major Customer 1']+df.loc[df['Market'] == 'Major Customer 2'])

A: Please see this notebook for more details.
https://nbviewer.jupyter.org/github/emican86/48999037/blob/master/48999037.ipynb
.loc is primarily label based.  Data had to be aligned and labels set.


text:
Q: Let's make it easier to reply within comments! Here's my proposal.  Every comment has a 'Reply' link after it.  Clicking on this link adds the standard @UserName: to the comment edit box.
After posting, the @UserName: is converted into a javascript 'link'.  By 'link' I mean that it appears to be a hyperlink, but is actually a span with the hyperlink style and javascript in its onmouseover event.  When you hover over this link, the comment it references is highlighted in some fashion (background color changes, its outlined, whatever).
When the referenced comment is hidden, one of two things can happen:

*

*The comments section is expanded and unshown comments are revealed, or

*A hovering div appears next to the pointer containing the comment that is referenced.

No. 2 is probably easier to implement.

A: I wrote this related post: Make recent activity and responses show new comments on questions/answers I have commented on (even if I don't own them)
However, after thinking about it some more, I really think that Twitter-style @username replies would be a better option.  Here are some of the potential problems, and my solutions to them.

*

*Usernames are not unique.  You should only show notifications to users with matching names who are either: a) the owner of the post; b) active in the current comment thread; or possibly c) the owner of the question (if this is a comment on an answer).  Collisions should be rare enough that this is not a big deal.

*Usernames can have spaces.  I think this makes simple "@username" Twitter-style replies difficult, but we could easily do a sytax which is delimited on both ends.  I'd suggest @username:, or possibly @[username].  A Twitter-style reply button (as suggested in this feature request) would fill in the comment box so the user doesn't even have to do this himself most of the time.

*Usernames are not permanent.  That's fine.  If a user changes their name, they shouldn't expect a way of tracking old comment responses to their new name.  Besides, I don't think active users change their name very often because they'd lose some of their name recognition.  (Anyone want to diff usernames between July and August dumps to see how many name changes there actually were, and how much rep those users had on average?)

A: It'd be nice if it also alerted the first Comment's User, that a reply has been left.  This can be part of the Responses section.

A: I'd suggest to make two simple things for starters:

*

*Make a hyperlink next to each comment with a Reply written on it.
Say, user named James Kilter made a comment: Oh, I really like your answer!.

*Whenever I click on that hyperlink, two things happen:

*

*The text field that allows me to type in a comment shows up (as if you clicked add comment)

*Text **@James Kilter** appears in the beginning of the text field and I can write thanks! into that field.
That will allow James Kilter to see that the comment with the word thanks is addressed to him.
I'm not an expert in making web sites, but it appears to me this is quite an easy task to do.
And this will help a lot, as many of the users as for now have to make their comments addressed to certain people manually.

A: Here's great UserScript from balpha ♦ which does exactly the same you need
install / update script – view source

A: It would be nice if you could reply to a specific comment and it was threaded. For example:

This answer saved my marriage, career and $4.99 - mrX
  I'm glad I could help - BrianG
This is clearly the wrong answer, -1 and I'm not talking to you for 23 minutes - dave
  Infact, make that 26 minutes - dave

But do the number of questions that actually have large amounts of comments make it worth it?

A: Normally, you only get notified of comments when you own the post.
You will now get notified of any comments that refer to you by @username in a comment, even if you do not own the post.
Rules:

*

*Only applies to other people in the comments that you are commenting on, or editors of the current post.

*Response must include @username that you are referring to, where "username" is a reasonable match to the user's current display name (as seen in the comments above yours).

*There must be a starts-with, case insensitive match of at least THREE characters to the displayname. So @a and @ab will never match anyone or anything.

*Spaces cannot be used to match, so if the person's display name is "Peter Smith" then just use @peter or @petersmith to match.

*Matching is performed in reverse chronological order, so if there are five people named "John" in the comments, writing "hey @john, have you considered apples?" will match the most recent John to comment.

A: I would prefer it it used the user id instead.
@[1337] Hey, look I'm talking to myself.
**@[1337]** Now I'm yelling at myself!
That would completely prevent collisions.

This would be easy to do if there was a Reply to: link on every comment.
The @[1337] would get changed to:
@Brad Gilbert

based on the current name associated with the userid.
This could be done browser side, perhaps as a Grease Monkey script ( hint hint ).

A: Oh dear, don't let Jeff hear this...
Else he'll change those @username replies into Twitter messages.
But I like the idea

A: Are we losing the point of a Q & A site?
The comment system should be simple and not take anything away from the questions and answers.
If the comment system gets too complex, then it will be used instead.


text:
Q: UWP InkToolbar ToolTip I'm designing a InkToolbar with InkToolbarCustomToolButton, like below
<InkToolbar x:Name="inkToolbar1" x:FieldModifier="Public" Grid.Column="0" Grid.RowSpan ="2" Grid.ColumnSpan="2" InitialControls="None" TargetInkCanvas="{x:Bind inkCanvas}" HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Horizontal">
            <InkToolbarCustomToolButton x:Name="toggleButtonNewInk" Click="toggleButtonNewInk_Click">
                <SymbolIcon Symbol="Page2" ToolTipService.ToolTip="NewInk"/>
            </InkToolbarCustomToolButton>
</InkToolbar>

As is shown, the button's tooltip is fixed.

Now I want to show in different languages, using Resources.resw.
For example, you can set a button's content using Resources.resw.
How can I do in the same way?
By the way, I don't want to use PointerEntered event.

A: For your requirement, you could set the Content of ToolTip just like button that you have mentioned.
<InkToolbarCustomToolButton x:Name="toggleButtonNewInk" Click="toggleButtonNewInk_Click" Margin="20">
    <SymbolIcon Symbol="Page2" >
        <ToolTipService.ToolTip>
            <ToolTip Content="" x:Uid="ToolTip"/>
        </ToolTipService.ToolTip>
    </SymbolIcon>
</InkToolbarCustomToolButton>

And then set the different value for ToolTip in different resources file like the following:
en-US
<data name="ToolTip.Content" xml:space="preserve">
  <value>NewInk</value>
  <comment>Prompt the user this is a new ink button</comment>
</data>

zh-CN
<data name="ToolTip.Content" xml:space="preserve">
  <value>新画笔</value>
  <comment>提示用户这是一个新画笔按钮</comment>
</data>

For more, please refer to Put UI strings into resources.


text:
Q: iOS doesn't receive push from Azure Notification Hub In my iOS app I'm trying to add push notifications via Azure Mobile Services.
I have followed this article: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-javascript-backend-ios-get-started-push/
But my app still receive no push notifications!
In the iOS dev center I registered App ID with Dev and Production push certificates.
Added Dev certificate (.p12) to Sandbox in the Azure.
I wrote POST function
exports.post = function(request, response) {
    var text = 'You\'ve just received a push!';
    var push = request.service.push;
        push.apns.send(null, {
          alert: "Alert",
          payload: {
              inAppMessage: text
          }
        }, {
          success: function(pushResponse) {
          console.log("Sent iOS push:", pushResponse);
          response.send(statusCodes.OK, { message : 'Push send success' });
        }, error: function(error) {
          console.log("Sent iOS push error:", error);
          response.send(statusCodes.BAD_REQUEST, { message : 'Push send error: ' + error });
        }
    });
};

In the log I'm getting this everytime:
Sent iOS push: { isSuccessful: true,
statusCode: 201,
body: '',
headers:
{ 'transfer-encoding': 'chunked',
   'content-type': 'application/xml; charset=utf-8',
   server: 'Microsoft-HTTPAPI/2.0',
   date: 'Sat, 02 Apr 2016 18:27:42 GMT' },
md5: undefined }

Also, in the app I register for push:
if let client = self.azureClient {
    client.push.registerNativeWithDeviceToken(deviceToken, tags: nil, completion: { (error: NSError?) in
        if let error = error {
            print(error)
        }
    })
}

I'm stuck and don't know what to do to make Azure send pushes to my app.
It would be great if anyone could explain me what I'm doing wrong.
Thanks!
UPDATED
I've just found that in Notification Hub Debug tab when I try to broadcast push it shows that there is no registrations:

Despite the fact that Notification Hub Monitor shows, that there was some Registration Operations and Incoming Messages:

A: The alert key needs to be inside an aps object, like so:
push.apns.send(null, {
    aps: {
        alert: "Alert"
    },
    payload: {
        inAppMessage: text
    }
}, .... );

Apple has a page on push notification payloads with more examples.
Also make sure you are running your app on a device, as the simulator can't receive notifications.
If you still aren't getting notifications, see Apple's troubleshooting page for push notifications or update your question.

A: It is strange, but when I replaced Developer Push Certificate with Production Push Certificate, my app suddenly began to receive pushes! Isn't it bug of Azure? Any guess why it happens?


text:
Q: How to generate all Feynman diagrams with Mathematica? I'm using the words "Feynman diagrams" for indexing purposes, but the question is  in fact purely graph-theoretic.
Given a list n={n1,n2,...} of non-negative integers, I want a function that generates all graphs with n1 1-valent vertices, n2 2-valent vertices, etc., with their corresponding symmetry factors. (These are, by definition, the number of automorphisms of the corresponding graph).
I'm aware of the existence of some packages that generate such graphs, but I was looking for something that doesn't require any installation. Just to copy+paste code. This is a self-answered question, but any alternative answer is obviously welcome and appreciated.

Note: by graph I mean pseudograph, i.e., multiple edges and self-loops are allowed.

Note also: the $j$-th element in the list n is the cardinality of $j$ in the degree sequence of the graphs. I'm not sure if there is an accepted name for the list n, although it would be nice to know. This list is important in physics (because the graphs for a given n contribute to order $g_1^{n_1}g_2^{n_2}\cdots$ to the perturbative expansion in powers of the coupling constants $g_1,g_2,\dots$).

A: Here is a piece of code that is inspired by quantum field theory. The physics background can be found in this physics.SE post.
First, we define some auxiliary functions:
ClearAll[Δ, corr, reduce, allgraphs]
SetAttributes[Δ, Orderless];

corr[{a_, b_}] := Δ[a, b];
corr[{a_, b__}] := corr[{a, b}] =
                   Sum[
                     corr[{a, List[b][[i]]}] corr[Flatten@{List[b][[;; i - 1]], List[b][[i + 1 ;;]]}]
                   , {i, 1, Length[List[b]]}];

reduce[permutations_][graphs_List] /; Length[graphs] == 1 := {{First[graphs], 1}};
reduce[permutations_][graphs_List] := Map[MapAt[First, 1], Tally[(# /. permutations) & /@ graphs, ContainsAny], {1}]

The function Δ[a,b] represents an edge that joins the vertices a,b. The function corr (for correlation function) generates all Wick pairings, so it contains all graphs we are after. Most of the graphs are isomorphic, so we need a function that tests for equality under permutations of vertices. This is precisely the purpose of reduce.
We now define the main function:
allgraphs[n_List] /; OddQ[Sum[i n[[i]], {i, 1, Length[n]}]] := {}
allgraphs[{2, 0 ...}] = {{{1 <-> 2}, 2}};
allgraphs[n_List] := Block[{permutations, gathered, removeiso, coeff},

    permutations = Dispatch[Thread /@
     Thread[ConstantArray[Range[Total[n]], Total[n]!] -> Permutations[Range[Total[n]]]]
     /. Rule[a_, a_] -> Nothing];

    gathered = GatherBy[
      Select[
        {Expand[corr[Flatten[Table[ConstantArray[Total[n[[;; i - 1]]] + j + 1, i], {i, 1, Length[n]}, {j, 0, n[[i]] - 1}]]]] /. Plus -> Sequence}
        , WeaklyConnectedGraphQ[Graph[{#} /. {Times[a_Integer, g__] :> g, Times -> Sequence} /. Power[a_, b_] :> Sequence @@ ConstantArray[a, b] /. Δ -> UndirectedEdge]] &]
      , If[Head[First[#]] === Integer, First[#], 1] &];

    coeff = Map[If[Head[#[[1, 1]]] === Integer, #[[1, 1]], 1] &, gathered];

    removeiso = reduce[permutations] /@ (Map[Sequence @@ {# /. Times -> Δ /.  Power[a_, b_] :> Sequence @@ ConstantArray[a, b]} &, (gathered/coeff), {2}]);

    Flatten[
      Table[Map[{(List @@ #[[1]]) /. Δ -> UndirectedEdge, Apply[Times, n!] Apply[Times, (Range[Length[n]]!)^n]/(#[[2]] coeff[[j]])} &, removeiso[[j]], {1}]
      , {j, 1, Length[coeff]}], 1]
]

This function generates all graphs represented as lists. To plot these lists as actual graphs, we use
allgraphsplot[n_] := Graph[First[#], PlotLabel -> Last[#]] & /@ allgraphs[n]

Some examples:

(The plot title is the symmetry factor of the corresponding graph.)
Remarks:

*

*For efficiency, the function allgraphs generates connected graphs only. If the user wishes to obtain disconnected graphs too, they shall modify the code Select[X,WeaklyConnectedGraphQ[...]&] to just X. This makes the computation slower. Alternatively, if the user wishes to obtain k-edge-connected graphs, they may modify the code to Select[X,KEdgeConnectedGraphQ[...,k]&] for some k. Idem for any other criterion.

*As the examples above show, the graphs contain self-loops (a.k.a. tadpoles). Such graphs can be eliminated by setting Δ[a_,a_]:=0 at the beginning of the code. If we do so, the second example above becomes

as expected.

*The graphs considered herein are unlabelled. If the user wishes to label the 1-valent vertices (an operation that is useful in physics), they shall modify the code as follows: in permutations, change
Thread[ConstantArray[Range[Total[n]], Total[n]!] -> Permutations[Range[Total[n]]]]
into
Thread[ConstantArray[Range[n[[1]] + 1, Total[n]], (Total[n] - n[[1]])!] ->
Permutations[Range[n[[1]] + 1, Total[n]]]]
so as to consider permutations of internal vertices only. To have the correct symmetry factors, we should also modify Apply[Times, n!] to Apply[Times, Rest[n]!]. Finally, the plotting function should be modified to
allgraphsplot[n_] := Graph[First[#], PlotLabel -> Last[#],
VertexLabels -> Thread[Range[n[[1]]] -> Range[n[[1]]]]] & /@ allgraphs[n]
where we have added the option VertexLabels to label the external vertices. For example,

(Note in particular that the second and third graphs are not symmetric under $1\leftrightarrow2$.)

*The slowest step in the code above is reduce, where we check all permutations and compare graphs pair-wise. A nice way to speed-up the process is to first classify the graphs into subsets where we know for sure there are no isomorphic graphs, so that we make fewer pair-wise comparisons. This was partially done in the GatherBy step, but there is still some room for classification into smaller subsets. To further classify the graphs into such subsets, we may use any graph invariant. A particularly powerful one is the Tutte polynomial. Mathematica has a built-in function that calculates such polynomial, although some preliminary tests suggests that a user-defined function is slightly faster. In any case, if we use Tutte polynomials to classify graphs (before testing for isomorphisms), the whole computation is sped-up significantly for large-enough graphs, but it is slowed down for smaller ones. I haven't been able to find the exact size where this behaviour changes, so I'm not including that option here. If someone  tries it for themselves and comes up with something meaningful, please let me know.

*Once the graphs have been classified into subsets of potentially isomorphic graphs, we check all permutations of vertices and Tally them. This results in a classification into sets of truly isomorphic graphs, and whose cardinality is essentially the symmetry factor of the graph (up to some combinatorial factors that are easy to obtain). To further speed-up the process, it would be nice to discard from the outset some of the permutations that we know for sure will not lead to another graph in the subset. This would eliminate unnecessary comparisons, thus making the whole computation much more efficient. For example, it seems to me that we need not consider permutations among vertices of different valence, or among vertices that belong to different strongly connected subgraphs. I haven't been able to programmatically find all irrelevant permutations yet, so the code above checks for all permutations. There is therefore a lot of room for improvement there. Again, if someone comes up with something useful please let me know.

*Finally, let me mention that in physics we typically use coloured graphs. Given the unlabelled graphs as above, one considers all possible colouring up to isomorphisms. This should not be too difficult to do once the underlying unlabelled graph is known. This is left to the reader.


text:
Q: 'npm start' fails after not finding the module '..\scripts\start.js' I am trying to run npm start, but it keeps failing.
I've removed node_modules and package-lock.json and ran npm install. It still failed.
I've tried removing node_modules again, and this time I ran npm install -g npm@latest, and reinstalled them, but still, it just keeps faling.
This is the terminal log I'm getting:
> foy@0.1.0 start C:\Users\Yanay\Documents\Coding\foy
> node scripts/start.js

internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module 'C:\Users\Yanay\Documents\Coding\foy\scripts\start.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! foy@0.1.0 start: `node scripts/start.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the foy@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Yanay\AppData\Roaming\npm-cache\_logs\2020-12-16T12_08_00_997Z-debug.log

C:\Users\Yanay\Documents\Coding\foy>

And this is the complete report
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Users\\Yanay\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start' ]
2 info using npm@6.14.9
3 info using node@v10.16.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle foy@0.1.0~prestart: foy@0.1.0
6 info lifecycle foy@0.1.0~start: foy@0.1.0
7 verbose lifecycle foy@0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle foy@0.1.0~start: PATH: C:\Users\Yanay\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\Yanay\Documents\Coding\foy\node_modules\.bin;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64_win\compiler;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Calibre2\;C:\Android;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\Program Files\Git\cmd;C:\Program Files\MongoDB\Server\4.0\bin;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\nodejs\;C:\Program Files\Notepad++;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Perforce;C:\HashiCorp\Vagrant\bin;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Users\Yanay\AppData\Local\Programs\Python\Python38-32\Scripts\;C:\Users\Yanay\AppData\Local\Programs\Python\Python38-32\;C:\Users\Yanay\AppData\Local\Microsoft\WindowsApps;C:\Program Files\heroku\bin;C:\Users\Yanay\Documents\flutter\bin;C:\Users\Yanay\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\Yanay\AppData\Roaming\npm;C:\Users\Yanay\AppData\Local\Android\Sdk\platform-tools;C:\Users\Yanay\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\JetBrains\IntelliJ IDEA 2020.1.2\bin;C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.1.2\bin;C:\Users\Yanay\AppData\Local\Microsoft\WindowsApps
9 verbose lifecycle foy@0.1.0~start: CWD: C:\Users\Yanay\Documents\Coding\foy
10 silly lifecycle foy@0.1.0~start: Args: [ '/d /s /c', 'node scripts/start.js' ]
11 silly lifecycle foy@0.1.0~start: Returned: code: 1  signal: null
12 info lifecycle foy@0.1.0~start: Failed to exec start script
13 verbose stack Error: foy@0.1.0 start: `node scripts/start.js`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Users\Yanay\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Users\Yanay\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid foy@0.1.0
15 verbose cwd C:\Users\Yanay\Documents\Coding\foy
16 verbose Windows_NT 10.0.18363
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Yanay\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v10.16.0
19 verbose npm  v6.14.9
20 error code ELIFECYCLE
21 error errno 1
22 error foy@0.1.0 start: `node scripts/start.js`
22 error Exit status 1
23 error Failed at the foy@0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

What is wrong?


text:
Q: Save Special Character into Database I am currently using html and php for my site but I have this problem while saving in textarea.
Everytime I use a different font with special character like ' and " it saves like � (a black diamond with question mark inside). This usually happens when I copy a text from other site or when I copy a text document then paste it but when I type in the textarea it works fine.
sample:

don�t take no for an answer and are individuals who care about

Here is my html code
    <form action="savepost.php" method="POST">
    <fieldset style="width:600px; height:580px">

Title <input id="posttitle" name="posttitle" type="text">

Content

<textarea id="postform" name="postform" style="width:600px; height:450px; resize: none"></textarea>

<input type="submit" value="Post" id="postbutton"/>
    </fieldset>
    </form>

Mysql Insert
    $title = strtolower(mysql_real_escape_string($_POST['posttitle']));
    $post_title = preg_replace('/[^a-zA-Z0-9\s]/','', $title);
    $timestamp=time();
    $post = $_POST['postform'];

    $newtitle= preg_replace('/\\s+/', ' ',$post_title);
    $striptitle = trim($newtitle, ' ');
    $url = strtolower($timestamp.'/'.str_replace(" ", "-", $striptitle));

    mysql_query("INSERT INTO blog (title, url, timestamp, post) VALUES ('$title', '$url', '$timestamp', '$post')");

what could be the problem here?

A: This is an character encoding issue - if you are copying the content from a desktop program (MS Word) then Word puts in the angled quote not a straight quote, but if the HTML page is not in the correct encoding to display that character it will show like above.
try looking in the header of your page for
<meta charset="utf-8" />
or something similar
if it is not utf-8 or missing try changing it and see what happens.

A: Are you copying some of this text from Microsoft Word?  By default, Word will change your regular "straight" quotes into "curly" quotes.  There's a way to turn this feature off.  To fix the text you have, you might have to do a find/replace.


text:
Q: Is there an equivalent to the line integral for area in $\mathbb R^3$? So the following line integral is known to give the area of some figure in $\mathbb R^2$:
$$A=\frac{1}{2}\oint_C x\;dy-y\;dx$$
Is there an equivalent expression in $\mathbb R^3$ for volume?

A: You can use the Divergence Formula for $\vec{F} = \langle x,y,z \rangle$ and you will have:
$$\frac 13 \iint _A \vec{F}\cdot \vec{n} \, dA = \frac 13 \iiint _V \operatorname{div} \vec{F} \, dV = \iiint_V dV = V$$
In a similar manner you can use the same trick for $\vec{G} = \langle x,0,0 \rangle$
$$\iint _A \vec{G}\cdot \vec{n} \, dA =  \iiint _V \operatorname{div} \vec{G} \, dV = \iint_V dV = V$$
But keep in mind the formulae aren't really that simple as in $\mathbb{R}^2$, as after all it depends on the normal vector. So sometimes we have to make the right choice for the vector field in order to get an easier computation problem.

A: First, let's look at how it is that the (signed) area of the region $R$ with boundary $C$ can be computed via $\frac12\int_Cx\,dy-y\,dx$. Stokes' theorem tells us that this integral is equal to $$\frac12\int_Rd(x\,dy-y\,dx)=\frac12\int_{\partial R}2\,dx\wedge dy=\int_Cdx\wedge dy.$$ If we apply Stokes' Theorem in the other direction, it tells us that we can use any antiderivative of $dx\wedge dy$. E.g., $x\,dy$ works just as well as an integrand and can often be more convenient for computation. In general, we can use any convenient 1-form $\omega=x\,dy+\tau$, where $d\tau=0$ ($\tau$ is analogous to the constant of integration in single-variable indefinite integrals).
This has an obvious generalization to $n$ dimensions: the integrand $\omega$ must be such that $d\omega=dx^1\wedge\cdots\wedge dx^n$. One possible such $(n-1)$-form is the generalization of the form used to calculate areas: $$\frac1n(x^1\,dx^2\wedge\cdots\wedge dx^n+x^2\,dx^3\wedge\cdots\wedge dx^n\wedge dx^1+\cdots+x^n\,dx^1\wedge dx^2\wedge\cdots\wedge dx^{n-1})\tag{*}$$ which you can find via an educated guess or the algorithm described here. In three dimensions, this is $$\int_Vdx\wedge dy\wedge dz=\frac13\int_{\partial V}x\,dy\wedge dz+y\,dz\wedge dx+z\,dx\wedge dy.$$ This is just an instance of the divergence theorem (a.k.a. Gauss' theorem) expressed in terms of differential forms.
On the other hand, just as in the two-dimensional case, there are other integrands that can be much more convenient for computation. For instance, $x^1\,dx^2\wedge\cdots\wedge dx^n$ is also an antiderivative of the volume element, as are all of the other terms inside of the parentheses in (*). Indeed, you can think of that entire expression as the average of those individual antiderivatives, each one in the direction of a particular basis vector. There are other linear combinations of these terms that might also be more convenient in various situations.
The integrand $\frac12(x\,dy-y\,dx)$ has a nice geometric interpretation as the area of the triangle with vertices $(0,0)$, $(x,y)$ and $(x+dx,y+dy)$, and the $(n-1)$-form generalization of it can also be interpreted geometrically. After parameterization, the terms in the sum can be computed as determinants, which in turn have an interpretation as volumes of certain paralleletopes that cover the volume being computed.


text:
Q: Hint for solving an indefinite integral I would like to solve the following integral
$$\int \frac{dx}{x^2 \sqrt[4]{(a-x^2)(b+x^2)}},$$
where $a$ and $b$ are the real constants.
My attempt:
$$\sqrt[4]{(a-x^2)(b+x^2)} = \sqrt[4]{-\bigg[x^4 + (b-a)x^2 + (\frac{a-b}{2})^2\bigg]+(\frac{a+b}{2})^2} = \sqrt[4]{(\frac{a+b}{2})^2 - (x^2-\frac{a-b}{2})^2}$$
Substituting $t=x^2 - \frac{a-b}{2}$ one gets
$$\int \frac{dt}{2(t+ \frac{a-b}{2})^\frac{3}{2}\sqrt[4]{(\frac{a+b}{2})^2 - t^2}}$$
 I do not know what to do here!


text:
Q: $\frac{0}{0}$ means functions have a common factor and can be simplified? Say for example we have the following function
$$\frac{2x+8}{x^2+x-12}$$
at $-4$ both functions have the same value which is zero which means at this point the functions cross.

How is it that their division at this given point means they must share a common factor and thus can be simpilfied?

A: Not all such functions can be simplified. Take for example $f(x)=x$ and $g(x)=e^x-1$. Then while both functions have a root at $0$, their ratio
$$\frac{f(x)}{g(x)}=\frac{x}{e^x-1}$$
cannot be simplified (without say appealing to a Taylor expansion).
The point is that there is something special about the ratio of polynomials with matching roots. This comes from the factor theorem which states that if $h(x)$ is a polynomial, it has a factor of $(x-a)$ if and only if $h(a)=0$.
So, if $f(x)$ and $g(x)$ are polynomials and they both have a root at $a$, that is $f(a)=g(a)=0$, then we can write $f(x)=(x-a)p(x)$ and $g(x)=(x-a)q(x)$ where $\deg(p(x))<\deg(f(x))$ and $\deg(q(x))<\deg(g(x))$.
Hence we have
$$\frac{f(x)}{g(x)}=\frac{(x-a)p(x)}{(x-a)q(x)}$$
and in particular for $x\ne a$, we can simplify this to
$$\frac{f(x)}{g(x)}=\frac{p(x)}{q(x)}$$
Note that at $x=a$, the ratio $\dfrac{f(x)}{g(x)}$ is undefined.

A: The fact that they have a factor $x-a$ where $a$ is a root to the polynomial $p(x)$ follows that if you try to divide it by $x-a$ you'll get $p(x) = q(x)(x-a)+r(x)$ where $r(x)$ is a polynomial of degree less than one (that is a constant $C$), $q(x)$ being a polynomial. Now $0 = p(a) = q(a)(a-a)+r(a)=r(a)=C$, cosequently $C=0$ so $p(x) = q(x)(x-a)$, that is that $(x-a)$ is indeed a factor of $p(x)$.


text:
Q: Unable to deploy WSF/PHP WebService on WSO2 ESB few days ago I started to work on my own WebServices. I decided to use WSO2 WSF/PHP framework and according to http://wso2.org/project/wsf/php/2.0.0/docs/manual.html created my first helloService. Here's code:
function greet($message) {
    $responsePayloadString = <<<XML
        <greetResponse>Hello Client!</greetResponse>
    XML;

    $returnMessage = new WSMessage($responsePayloadString);
    return $returnMessage;
}
$service = new WSService(array("operations" => array("greet")));
$service->reply();

I've deployed it on my server and tried to call it using simple helloClient (described in wso2 wsf/php manual) and SoapUI - everything works fine.
Now I would try to deploy it on my WSO2 ESB, so I've defined new proxy service like this:
<proxy name="helloService" transports="https http" startOnLoad="true" trace="disable">
    <target endpoint="helloService">
        <inSequence>
            <log level="full"/>
        </inSequence>
        <outSequence>
            <filter xpath="get-property('FAULT')">
                <then>
                    <log level="full" category="WARN" separator=",">
                        <property name="message" value="SOAP Fault detected"/>
                    </log>
                </then>
                <else/>
            </filter>
            <send/>
        </outSequence>
        <faultSequence>
            <log level="full">
                <property name="MESSAGE" value="Executing default 'fault' sequence"/>
                <property name="ERROR_CODE" expression="get-property('ERROR_CODE')"/>
                <property name="ERROR_MESSAGE" expression="get-property('ERROR_MESSAGE')"/>
            </log>
            <drop/>
        </faultSequence>
    </target>
    <publishWSDL uri="http://myAPIAddress/helloService.php?wsdl"/>
</proxy>
<endpoint name="helloService">
    <address uri="http://myAPIAddress/helloService.php" format="soap11"/>
</endpoint>

New service is visible on "Deployed services" list in ESB management console, I can get WSDL from myESBaddress:8280/services/helloService?wsdl and everything looks fine on the myESBaddress:8280/services list. But, when I want to use "Try this service" option, there's timeout error. I tried to call my WS using SoapUI - the request to endpoint myESBaddress:8280/services/helloService looks like (the same request worked fine when I sent it to myAPIAddress/helloService.php)
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.wso2.org/php/xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <greet>asdfasdfas</greet>
   </soapenv:Body>
</soapenv:Envelope>

Unfortunately, as a response, I've got a fault:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <soapenv:Fault>
            <faultcode>411</faultcode>
            <faultstring>Unexpected response received. HTTP response code : 411 HTTP status : Length Required exception : First Element must contain the local name, Envelope , but found html</faultstring>
            <detail>Unexpected response received. HTTP response code : 411 HTTP status : Length Required exception : First Element must contain the local name, Envelope , but found html</detail>
        </soapenv:Fault>
    </soapenv:Body>
</soapenv:Envelope>

What did I wrong? I have feeling, that it's something completely stupid and obvious, so forgive me if it's newbie question but after few days of digging for solution I'm really desperate.
PS. Sorry for my english, it's not my mother tongue

A: Finally, I got it to work! The problem was caused by version of HTTP. Here's solution:
...
<inSequence>
    <log level="full"/>
    <property name="FORCE_HTTP_1.0" value="true" scope="axis2" type="BOOLEAN"/>
</inSequence>
...

Hope, it will be someday helpful for somebody.

A: What's type of your php services ?
How to Invoke External PHP Web Services with WSO2 ESB
i have same problem with you, but i have changed my server to Apache, and problem is solved.


text:
Q: If a row under a column in a .csv file contains 1, then the same row in another column should be overwritten using python, else should be left empty I have a .csv file with about 300,000 rows. I have created a new column manually and I wish to extract information from some older columns but I can't do this manually because of the length of the file. The title of the older columns are Present, Online, Absent and the new column is Attendance.
The older columns have values of 1 and 0 where the observation is true or false i.e if an observation came to the event then the "Present" column will have a value of 1 and if anything else, it carries a value of 0. Same with "online" and "absent" column.
I want the new column to take the information from the older ones, i.e if any of the older ones has a value of 1 the same row in "Attendance" should have a value of either "present", "online" or "absent" depending on which is true.
I've been trying to do this using Pandas but haven't found a way that works for .csv files.
for i in f['Present']:
    if i == 1:
       f['Attendance'].write("present")

I don't mind if the solution works for one column and is repeated for the others. It doesn't have to work for all at once.
This is what it should look like

Thanks

A: A more pandasonic solution (than a loop, list of conditions and loc),
based actually on Numpy is:
df['Attendance'] = np.select([df.Present == 1, df.Online == 1, df.Absent == 1],
    choicelist = ['present', 'online', 'absent'], default = '')

It should run substantially quicker than the other solution.
For details see the documentation of np.select.

A: for i in range(len(df)):
    if int(df.loc[i, 'present']) == 1:
        df.loc[i, 'attend'] = 'present'
    elif int(df.loc[i, 'online']) == 1:
        df.loc[i, 'attend'] = 'online'
    else:
        df.loc[i, 'attend'] = 'absent'

You can traverse each row of the dataframe and set the value of the new column based on the previous 3 columns.
Refer https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy


text:
Q: SEO - Is it correct to say "optimize your code putting the JS code in the bottom of the page"? I'd like to know if this is an urban story or if is the truth.
I've heard that web crawlers, when they inspect a page on the web, terminate after an amount of time to catch the Available code (such html) and go to inspect another page. So, if the JS code is in the head, I'll lose a huge part of the reserved time for the catching.
If that's true, it is not good put the JS on the head, but maybe in the bottom, inside a jQuery syntax such $(document).ready().
What can you tell me about this? Thanks everybody!

A: Your assertion that javascript should go at the end of the file is correct, but not really for the reason you state.
The primary reason for putting your javascript at the bottom of the file is that browsers try to render a page as it is being downloaded.  However, if javascript is encountered the browser will pause rendering to parse/run the javascript.  This can result in a user perception that the page is slow to load.  Putting the javascript at the end allows the browser to render the whole page (or most of it) before pausing to parse and process the javascript.

A: Regardless of whether it's a myth or not, you should put your JavaScript at the bottom of the <body> in an external .js file. This means you don't have to use $(document).ready at all and the browser will only parse the JavaScript after loading the body content, which makes the page-loading faster. There is no point in putting the JavaScript in the <head>.


text:
Q: uitableviewcontroller edit Row at index not working with uipageviewcontroller i have a UIPageViewController that holds a bunch of viewcontrollers. One of the child view controllers is a uitableviewcontroller which has certain rows that can be edited/deleted
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0  || indexPath.row == 1 || indexPath.row == 2 || (indexPath.row == 3 && hasMore) || indexPath.row == 1 + 1 + 1 + 1 + self.media.comments.count - 1 + (hasMore ? 1 : 0)){
    return NO;
}
Comment *comment = [self.media.comments objectAtIndex:(indexPath.row - 3 - (hasMore ? 1 : 0))];
if (comment.user.userId != [Data sharedInstance].currentUser.userId)
    return NO;
return YES;

}
my problem now is that since i have a uipageviewcontroller as the parent when i swipe on one of the cells that should be editable the uipageviewcontroller gets the touches and changes page instead of the table receiving the touches and showing the edit menu
any ideas out there?
Thanks
Chris

A: i actually found out that you can use this third party library which will allow the swipe gesture of the menu to have president over the uipageviewcontroller swipe
https://github.com/WinterKirk/MKSlidingTableViewCell
the important thing is that your whole view shouldnt only have these kind of cells cause then the uipageviewcontroller wont be able to swipe
but it works great in situations where you lets say have an image and comments under it and people should be able to delete the comments but swipe to the next pic on all other cells


text:
Q: Check for a string with line break in a column using java drools I have the below data in a table -
ID    ABC_23_02
--    --------
01    See your note and security instrument for information about
      -what happens if you fail to make your payments,
      -what is a default on the loan.

Now, I want to trigger a rule when the same value is found in the column. Here is my code snippet -
rule "Rule - Success"
    when
        form: Form_ABC()
        $m: Map()
        $ID: Object() from $m["ID"]
        $x: Object() from $m["ABC_23_02"]
        Map(Utility.rtnString($x) == "See your note and security instrument for information about\n-what happens if you fail to make your payments,\n-what is a default on the loan.")
    then
        Utility.helper(drools);
        if(!($ID.toString().equalsIgnoreCase("ID")))
        {
        form.setCD_23_02(Utility.rtnString($x));
        System.out.println("Rule - Pass\t\t" + $ID.toString()
                                             + "\tField 1 is: " + $x.toString());
        }
end

And, here is the Utility.rtnString($x) function that i am calling -
public static String rtnString(Object Input)  {
            //String numOnly = Input.toString().replaceAll("[^\\w\\s\\.]","");
            String numOnly = Input.toString().replaceAll("[^\\w\\s\\.\n]","");
            return numOnly.toUpperCase();
        }

But, I am not able to look for the string in the column using the above. Can you please suggest a better way to achieve the same. Thanks.


text:
Q: ValueError: Error when checking target: expected dense_8 to have shape (1,) but got array with shape (10,) Well, I'm trying to utilize maxpooling as a first layer by keras framework. I Work on MNIST famous dataset towards digits recognition and have a problem with the input and output dimensions.
Here's my model summary:
    Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_5 (Conv2D)            (None, 26, 26, 32)        320
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 24, 24, 64)        18496
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 64)        0
_________________________________________________________________
dropout_6 (Dropout)          (None, 12, 12, 64)        0
_________________________________________________________________
flatten_3 (Flatten)          (None, 9216)              0
_________________________________________________________________
dense_7 (Dense)              (None, 128)               1179776
_________________________________________________________________
dropout_7 (Dropout)          (None, 128)               0
_________________________________________________________________
dense_8 (Dense)              (None, 10)                1290
=================================================================
Total params: 1,199,882
Trainable params: 1,199,882
Non-trainable params: 0

I got this error at the final step:
ValueError: Error when checking target: expected dense_8 to have a shape (1,) but got an array with shape (10,)

I'm trying to do the classification task.
These are the main part of my program:
from keras.utils import to_categorical
num_class = 10

y_train = to_categorical(y_train, num_class)
y_test = to_categorical(y_test, num_class)
#
#Model created
from keras.models import Sequential
#Layers added
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D

model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3),
     activation = 'relu', #A "relu" activation stands for "Rectified Linear Units", which takes the max of a value or zero
     input_shape=(img_rows, img_cols, 1)))
#
model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
#
model.add(Dropout(0.25))
#
model.add(Flatten())
#
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_class, activation='softmax'))
#"softmax" activation is used
#when we'd like to classify the data into a number of pre-decided classes
model.compile(loss = 'sparse_categorical_crossentropy',
             optimizer='adam',
             metrics=['accuracy'])
#
batch_size = 128
epochs = 10

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
model.save("test_model.h5")

A: You are using the wrong loss, sparse_categorical_crossentropy requires integer labels, not one-hot encoded labels, so you can just use categorical_crossentropy as loss, which requires one-hot encoded labels.


text:
Q: JavaScript - How can I change the background color on all TDs in a TR at the same time on Mouseover/Mouseout? When I mouseover one TD in a row I want all the TDs to change background color at the same time, then reverse on mouseout.
How do I do this?

A: var tds = document.getElementsByTagName("td");
for(var i = 0; i < tds.length; i++) {
    tds[i].onmouseover = function() {
       this.parentNode.style.backgroundColor = "#ff0000";
    }
    tds[i].onmouseout = function() {
      this.parentNode.style.backgroundColor = "#fff";
    }
}

This actually changes the background colour of the parent tr, not each td, but it could be easily modified to do so. You could also attach the events to the tr elements instead of the td elements, and then you wouldn't have to use parentNode, but I don't know whether you need to do other stuff in the event handler specifically related to the td.

A:

        Water
        Air
        Fire
        Earth

        Spring thunderclouds
        Yes
        Yes
        No
        No

        Roasting chestnuts
        No
        No
        Yes
        Yes

        Winter snowbanks
        Yes
        Yes
        No
        Yes

        Ice cream on a hot summer day
        Yes
        Yes
        Yes
        Yes

A: I don't know what your exact use-case is, but for such tasks I would stick to CSS only:
td {
    background: #f00; }
tr:hover td {
    background: #fc0; }

http://jsfiddle.net/feeela/53JBV/

A: In CSS you could do
tr td { background-color: white }
tr:hover td { background-color: black };

or just
tr { background-color: white }
tr:hover { background-color: black };

if the tds don't have their own background color.
Both should make the row black on mouseover, and white otherwise.
You could also do it in Javascript of course, but that isn't necessary (except for IE6, which doesn't understand the :hover pseudo-class on anything but  tags)

A:
...

This is faster than using jQuery, also, not everybody uses jQuery.

A: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);
You can use code like this:
HTML

        cell1,1
        cell1,2
        cell1,3

        cell2,1
        cell2,2
        cell2,3

Style sheet
.hover {
    background-color: silver;
}

JavaScript
$("td").hover(
  function () {
    $(this).parent("tr").addClass("hover");
  },
  function () {
    $(this).parent("tr").removeClass("hover");
  }
);

The .hover class obviously can be styled as you like.
Regards and happy coding!

A: In jQuery:
$('td').mouseover(function( obj ) {
    $(obj).parent().children().css("background-color","green");
});

$('td').mouseout(function( obj ) {
    $(obj).parent().children().css("background-color","red");
});

Or in Javascript:
var tds = document.getElementsByTagName( "td" );

for( var i = 0; i < tds.length; i++ ) {
    tds[i].addEventListener("mouseover",function(){
        var children = this.parentNode.getElementsByTagName("td");

        for( var j = 0; j < children.length; j++ )
            children[j].style.background-color = "green";
    });

    tds[i].addEventListener("mouseout",function(){
        var children = this.parentNode.getElementsByTagName("td");

        for( var j = 0; j < children.length; j++ )
            children[j].style.background-color = "red";
    });
}

A: This jsFiddle I created shows you how to do it with jQuery.
I am using jQuery's hover event to handle what you are trying to do.

A: If you want a framework-agnostic solution, you can try this:
function highlightCells(tableRow) {
    for (var index = 0; index < tableRow.childNodes.length; index++) {
        var row = tableRow.childNodes[index];
        if (row.style) {
            row.style.backgroundColor = "red";
        }
    }
}

function unhighlightCells(tableRow) {
    for (var index = 0; index < tableRow.childNodes.length; index++) {
        var row = tableRow.childNodes[index];
        if (row.style) {
            row.style.backgroundColor = "white";
        }
    }
}

Example:  http://jsfiddle.net/9nh9a/
Though practically speaking, wouldn't it be simpler to just bind your listener to the
 elements instead of the  elements?  Is there some reason you want to listen only on the  elements?

A:

        cell 1-1
        cell 1-2
        cell 1-3
        cell 1-4

        cell 2-1
        cell 2-2
        cell 2-3
        cell 2-4

        cell 2-1
        cell 2-2
        cell 2-3
        cell 2-4

A: When I did it in all java script I did it like this
<!DOCTYPE html>

<title>Chapter 11 Problem 1</title>

Paragraph Text

I really hope this doesn't garble it all up


text:
Q: MongoDB 'upsert' from Grails I'm trying to implement a simple "insert or update" (so-called 'upsert') method in Grails / GORM / mongodb plug-in / MongoDB.
The approach I used with Hibernate (using merge) fails with a duplicate key error. I presume perhaps merge() isn't a supported operation in mongodb GORM, and tried to get to the native upsert method through GMongo.
I finally have a version that works (as posted below), but it is probably not the best way, as adding any fields to the object being saved will break the code silently.
 public void upsertPrefix(p) {
    def o = new BasicDBObject()
    o.put("_id", p.id)
    o.put("someValue", p.someValue)
    o.put("otherValue", p.otherValue)

    // DBObject o = p as DBObject // No signature of method: mypackage.Prefix.keySet() is applicable for argument types: () values: []

    db.prefix.update([_id : p.id], o, true, false)
    // I actually would want to pass p instead of o here, but that fails with:
    // No signature of method: com.gmongo.internal.DBCollectionPatcher$__clinit__closure2.doCall() is applicable for argument types: (java.util.ArrayList) values: [[[_id:keyvalue], mypackage.Prefix : keyvalue, ...]]

    /* All of these other more "Hibernatesque" approaches fail:
    def existing = Prefix.get(p.id)
    if (existing != null) {
        p.merge(flush:true) // E11000 duplicate key error
        // existing.merge(p) // Invocation failed: Message: null
        // Prefix.merge(p) // Invocation failed: Message: null

    } else {
        p.save(flush:true)
    }
    */
}

I guess I could introduce another POJO-DbObject mapping framework to the mix, but that would complicate things even more, duplicate what GORM is already doing and may introduce additional meta-data.
Any ideas how to solve this in the simplest fashion?
Edit #1: I now tried something else:
    def existing = Prefix.get(p.id)
    if (existing != null) {
//      existing.properties = p.properties // E11000 duplicate key error...
        existing.someValue = p.someValue
        existing.otherValue = p.otherValue
        existing.save(flush:true)
    } else {
        p.save(flush:true)
    }

Once again the non-commented version works, but is not well maintainable. The commented version which I'd like to make work fails.
Edit #2:
Version which works:
public void upsertPrefix(p) {
    def o = new BasicDBObject()

    p.properties.each {
        if (! (it.key in ['dbo'])) {
            o[it.key] = p.properties[it.key]
        }
    }
    o['_id'] = p.id

    db.prefix.update([_id : p.id], o, true, false)
}

Version which never seems to insert anything:
def upsertPrefix(Prefix updatedPrefix) {
     Prefix existingPrefix = Prefix.findOrCreateById(updatedPrefix.id)
     updatedPrefix.properties.each { prop ->
          if (! prop.key in ['dbo', 'id']) { // You don't want to re-set the id, and dbo is r/o
                existingPrefix.properties[prop.key] = prop.value
          }
    }
    existingPrefix.save() // Never seems to insert anything
}

Version which still fails with duplicate key error:
def upsertPrefix(p) {
    def existing = Prefix.get(p.id)
    if (existing != null) {
        p.properties.each { prop ->
            print prop.key
            if (! prop.key in ['dbo', 'id']) {
                existingPrefix.properties[prop.key] = prop.value
            }
        }
        existing.save(flush:true) // Still fails with duplicate key error
    } else {
        p.save(flush:true)
    }
}

A: Assuming you have either an updated version of the object, or a map of the properties you need to update with their new values, you could loop over those and apply the updates for each property.
Something like this:
def upsert(Prefix updatedPrefix) {
    Prefix existingPrefix = Prefix .findOrCreateById(updatedPrefix.id)
    updatedPrefix.properties.each { prop ->
        if (prop.key != 'id') { // You don't want to re-set the id
            existingPrefix.properties[prop.key] = prop.value
        }
    }
    existingPrefix.save()
}

How to exclude updating the ID may not be quite correct, so you might have to play with it a bit. You also might consider only updating a property if it's corresponding new value is different from the existing one, but that's essentially just an optimization.
If you have a map, you might also consider doing the update the way the default controller scaffolding does:
prefixInstance.properties = params

A: MongoDB has native support for upsert. See the findAndModify Command with upsert parameter true.


text:
Q: why is the rule not working on Flex using C++? I have this code, but the action is not working properly using c++.
I've tried, but I don't get any error, what do you think?. Does anybody knows which is the error?.
ejem05.l
%x use
%{
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>

using namespace std;

#define MAX_USE_NUM 10
YY_BUFFER_STATE use_stack[MAX_USE_NUM];
int use_stack_ptr = 0;
%}

%option c++ noyywrap

%%
<INITIAL,use>[0-9]+ {cout<< "Number found: "<< endl;}
use[[:blank:]]+ {BEGIN(use);}
<use>[[:alpha:][:punct:][:digit:]]+ {
    cout << "Nombre de archivo: "<< YYText() << endl;
    if ( use_stack_ptr >= MAX_USE_NUM ) {
        fprintf( stderr, "Too much files" );
        exit(1);
    }
    use_stack[use_stack_ptr++] = YY_CURRENT_BUFFER;
    ifstream in(YYText());
    yyin = ∈
    if (!yyin) {
        cout<< "ERROR file not found" << endl;
        exit(1);
    }
    yy_switch_to_buffer(
    yy_create_buffer( yyin, YY_BUF_SIZE ) );
    BEGIN(0);
}
<<EOF>> {
        if (--use_stack_ptr < 0 ) {
            yyterminate();
        }  else {
            yy_delete_buffer( YY_CURRENT_BUFFER );
            yy_switch_to_buffer(use_stack[use_stack_ptr] );
            }
}
%%

int main(int argc, char** argv) {
    ++argv, --argc; /* skip over program name */
    ifstream in(argv[0]);
    yyFlexLexer* lexer = new yyFlexLexer(&in);
    while(lexer->yylex()!=0)
        ;
    return 0;
}

My entry file is:
entrada.txt
use entrada1.txt
use entrada2.txt

The content of the file:
entrada1.txt
45
56

The content of the file:
entrada2.txt
34
67
89

I get this outcome:

Nombre de archivo: entrada1.txtNombre de archivo: entrada2.txt

I've compiled this file using these commands:
flex ejem05.l
c++ lex.yy.cc -o ejem05
./ejem05 entrada.txt

The rule that isn't working is:
<INITIAL,use>[0-9]+ {cout<< "Number found: "<< endl;}

Thanks in advance. I'm sorry, my english is bad.

A: I don't know if this is the cause of the behaviour you are seeing, since it is basically undefined behaviour, but it seems likely that it has something to do with the problem.
None of this is appropriate use of C++ I/O objects:
{
  // ...
  ifstream in(YYText());    // Point 1
  yyin = ∈               // Point 2
  if (!yyin) {              // Point 3
    cout<< "ERROR file not found" << endl;
    exit(1);
  }
  yy_switch_to_buffer(      // Point 4
    yy_create_buffer( yyin, YY_BUF_SIZE ) );
  BEGIN(0);
}

*

*in has automatic storage duration (i.e. it's a local variable), so it will be destructed when the scope is exited, which will be very soon (but not before it is passed to yy_create_buffer. See below.)

*yyin is a member variable, so its lifetime is the lifetime of the FlexLexer object. &in is the address of a local object (as noted above). When the block exits, yyin becomes a dangling pointer because the object it pointed to no longer exists. Any attempt to use it will be Undefined Behaviour. (I suspect the reason you get away with this is that yyin is not actually every used, but I don't know for sure.)

*Since yyin has just been set to the address of an actual object, it cannot be a null pointer. So the test will never succeed. Even if the file was not opened correctly, the error will never be detected. The C idiom is to check the return value of fopen, which returns a pointer to a FILE and thus could be NULL. The C++ idiom for checking if a file was correctly opened would be:
if (!in) {

which relies on the overridden operator!. You could also call in.fail(), which has the same semantics.

*Finally, you pass yyin (by reference) to yy_create_buffer. The yy_create_buffer function is not well-documented (one of the reasons I rarely use the C++ interface myself), but it stands to reason that it does not take ownership of the std::istream* which it receives as an argument. (The yyFlexLexer object is somewhat documented; in the description of its constructor, the documentation notes that "yyFlexLexer does not take ownership of its stream arguments. It's up to the user to ensure the streams pointed to remain alive at least as long as the yyFlexLexer instance" and it turns out that roughly the same warning applies in this case. That's not surprising because there is no way that the yy_create_buffer member function can copy the std::istream object it is passed -- these objects are not copyable -- and without copying, there is no way to take ownership.
What yy_create_buffer does do is to retain a pointer to the std::istream's rdbuf(). (This isn't documented, but it's clearly visible in the generated code.) However, because it is a std::fstream, when in is destructed, it will also dispose of its rdbuf(). Subsequently attempting to use the pointer to the destructed rdbuf is, of course, more Undefined Behaviour, but if you are very very lucky (or maybe unlucky), enough bits will still be valid in the memory pointed to that the rdbuf reports an end of file or an error on the first attempt to read from it. That would definitely explain the symptoms you are seeing, but it is all highly speculative.
Bottom line: If you are going to use C++, play the game by the rules. Don't create dangling pointers, don't let objects which should persist be prematurely destructed, and check std::fstream objects' validity after you create them and before you use them.


text:
Q: Define an exclusion for DHCP reservation Lets suppose I define an IP address reservation in Windows Server 2003 DHCP Server. Is it mandatory to define an exclusion of this IP address also?
IP Scope: 192.168.1.1 to 192.168.1.5
IP Reservation: 192.168.1.2
IP Exclusion: 192.168.1.2 <-- is this entry mandatory?
What will happen if the entry is not present? Is there a 20% chance the IP address will be assigned to some other computer?

A: Nope.  The reservation will automatically create a "hold" on that IP address preventing it being issued to something else.


text:
Q: Popping Fragment from backstack on BACK key press I am adding a Fragment and transaction is committed to the back stack using the following code:
getSupportFragmentManager().beginTransaction().add(id, fragment, "TAG").addToBackStack(null).commit();

Now when is press the BACK key. Activity is getting finished. But I just want to remove the fragment.
Should I manually handle the BACK key press and do the task of popping backstack or is there any way I can make activity to handle this automatically.

A: I found one reason for why it may happen:
If you are using app.Activity but making transactions with SupportFragmentManager, or using support.Activity and making transactions with FragmentManager, it seems that the activity ignores the fragments back-stack.
The usage should be consistent, support or normal.


text:
Q: Last child not working as expected with p tag I have an issue with using :last-child with a certain class for my p tag, but works fine with other classed p tags, so here's my code:

Portfolio

Who am I?

...

What do I do?

...

Current Projects?

...

Contact me

...

My CSS:
.pull-center {
                position:absolute;
                margin:auto auto;
                top:0;bottom:0;
                left:0;right:0;
}

div.port-container {
                width:975px;
                height:auto;
                overflow:auto;
                margin:auto auto;
}
                div.port-container > .bg-toggle {
                                background-color:rgba(44,62,80,0.25);
                                border-color:rgba(0,0,0,0.5) !important;
                }
                div.port-container > div.header {
                                height:200px;
                                line-height:200px;
                                border:solid 1px #FFF;
                                border-top-left-radius:5px;
                                border-top-right-radius:5px;
                                text-align:center;
                                color:#FFF;
                }
                div.port-container > p.header {
                                padding:10px;
                                border-bottom:solid 1px #FFF;
                                border-left:solid 1px #FFF;
                                border-right:solid 1px #FFF;
                                color:#FFF;
                                cursor:pointer;
                }
                div.port-container > p.header:last-child { /*<----- Issue */
                                border-bottom-left-radius:5px;
                                border-bottom-right-radius:5px;
                }
                div.port-container > p.header.active {
                                border-bottom-left-radius:0px;
                                border-bottom-right-radius:0px;
                }
                div.port-container > p.info {
                                padding:10px;
                                border:solid 1px #FFF;
                                border-top:none;
                                display:none;
                                color:#FFF;
                }
                div.port-container > p.info:last-child { /*<----- Works fine */
                                border-bottom-left-radius:5px;
                                border-bottom-right-radius:5px;
                }
img.bg-button {
                width:32px;
                height:32px;
                top:auto;left:auto;
}

note: the ref attribute is used in my jQuery
tl;dr:
This works fine:
div.port-container > p.info:last-child {
    border-bottom-left-radius:5px;
    border-bottom-right-radius:5px;
}

But this doesn't:
div.port-container > p.header:last-child {
    border-bottom-left-radius:5px;
    border-bottom-right-radius:5px;
}

A: p.info:last-child matches all p.info elements that are also the last children of their parent.
In your markup, p.header are not the last children of their parent so while p.header matches various elements, p.header:last-child will match none.
Unfortunately, there is no :last-of-its-class selector. Matching is not possible unless you make some assumptions about the HTML structure. I made one:
p.header:nth-last-child(2) { }

It matches all p.header elements that are second last children of their parent. Note that this requires CSS3 selectors support.

p { background: #CCC; }
p.info:last-child { background: #FC0; }
p.header:nth-last-child(2) { background: #FC6; }

Portfolio

Who am I?

...

What do I do?

...

Current Projects?

...

Contact me

...

A: Because p.header isn't the last-child ... it's always the p with class info.

Selector is last-child (node) not last with class " "

The classname here just works as a conditional so if the last-child has the class info then style it.
To clarify if you have this selector:

div.port-container > p.header:last-child

All are conditionals to target the element:

*

*If it's inside a container div with class port-container

*And it's direct child >

*And it's p tag with class header

*And it's the last-child

A: You got the selector concept wrong.
The fact that you used a class selector does not filter the selection. In css, the combined selectors work as an && condition, so:
p.header:last-child

Will target a
 tag that is both an element with the class .header and also is the last child of its container.
Unfortunatelly
There's no way to get the last element of some class

A: As everyone else has stated your css selector will not work because p.header:last-child has to be the last child period. You can get around this by using jQuery.
CSS:
.port-container > .last-header {
    border-bottom-left-radius:5px;
    border-bottom-right-radius:5px;
}

JS:
$('.port-container > p.header:last').addClass('last-header');