text:
Q: Error in database connection I have been working on a project, which is a simple Spring, Hibernate, JSF, MySQL integration; and I run it on Eclipse. The aim of the program is to add a Person(id, first name, last name, gender, age etc.) database on MySQLWorkbench and run it on server. I used Spring4, Hibernate4, Primefaces 5.0.2 and Eclipse Luna as tools.And I constructed the project as maven.
When I run the program on main, I want to see that a new Person is included in my table.
I used "GRANT ALL ON" and "FLUSH PRIVILEGES" commands for the user I have created, on terminal and received "Query OK" message.
Despite specifying username and password on necessary files, I cannot add a new record to my table.My Project structure is as follows:

And other files are:
domain-classes.hbm.xml:
    <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class table="testPerson" name="com.hibernate.data.Person">
        <id column="person_id" type="int" name="id">
            <generator class="increment" />
        </id>
        <property name="firstName" column="person_firstname" type="string" />
        <property name="lastName" column="person_lastname" type="string" />
        <property name="gender" column="person_gender" type="string" />
        <property name="age" column="person_age" type="int" />
    </class>
</hibernate-mapping>

hibernate.cfg.xml:
    <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 <hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/PERSONDB</property>
        <property name="hibernate.connection.username">fulden2</property>
        <property name="hibernate.connection.password">secret_pass</property>
        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Show SQL -->
        <property name="show_sql">true</property>
        <!-- Specify session context -->
        <property name="hibernate.current_session_context_class">thread</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- Autocommit -->
        <property name="hibernate.connection.autocommit">false</property>
        <!-- Referring Mapping File -->
        <mapping resource="domain-classes.hbm.xml" />
    </session-factory>
 </hibernate-configuration>

applicationContext.xml:
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <!-- Enable Spring Annotation Configuration -->
    <context:annotation-config />
    <!-- Scan for all of Spring components such as Spring Service -->
    <context:component-scan base-package="com.*"></context:component-scan>
    <!-- Create Data Source bean -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/PERSONDB" />
        <property name="username" value="fulden2" />
        <property name="password" value="secret_pass" />
    </bean>
    <!-- Define SessionFactory bean -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
    </bean>
    <!-- Transaction Manager -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <!-- Detect @Transactional Annotation -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

pom.xml:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>test</groupId>
  <artifactId>PersonApp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>PersonApp</name>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.0.2</version>
        <configuration>
          <source>1.4</source>
          <target>1.4</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <url>http://maven.apache.org</url>
  <repositories>
     <repository>
         <id>prime-repo</id>
         <name>PrimeFaces Maven Repository</name>
         <url>http://repository.primefaces.org</url>
         <layout>default</layout>
     </repository>
   </repositories>
 <dependencies>
  <!-- Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
   <!-- Faces Implementation -->
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.10</version>
    </dependency>
    <!-- Faces Library -->
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.2.10</version>
    </dependency>
    <!-- Primefaces Version 5 -->
    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>5.2</version>
    </dependency>
    <!-- JSP Library -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
    <!-- JSTL Library -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- Primefaces Theme Library -->
    <dependency>
        <groupId>org.primefaces.themes</groupId>
        <artifactId>blitzer</artifactId>
        <version>1.0.10</version>
    </dependency>
    <!-- Hibernate library -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.9.Final</version>
    </dependency>
    <!-- MySQL driver connector library -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.35</version>
    </dependency>
    <!-- Spring ORM -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <!-- Spring Web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
 </dependencies>
</project>

Main class:
    package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import com.hibernate.data.Person;

public class Main {
    public static void main(String [] args){
        Configuration configuration = new Configuration();
        System.out.println("CFG and hbm files loaded successfully.");//just to test

        configuration.configure("hibernate.cfg.xml");

        SessionFactory factory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());

        Session session = factory.openSession();

        Transaction tx = session.getTransaction();
        tx.begin();
        System.out.println("Transaction began");//just to test

        Person newPerson = new Person();
        newPerson.setFirstName("aa");
        newPerson.setLastName("bbb");
        newPerson.setGender("Male");
        newPerson.setAge(2);

        session.save(newPerson);
        session.flush();

        tx.commit();
        session.close();
        System.out.println("Session closed");//just to test
    }

}

Is there an extra step to achieve this database connection?
Or what is my mistake here?
Thanks for any help..

A: Probably your session is not getting flushed; might be a glitch in your configuration. It happens many a time for an instance if you have configured OpenSessionInView Filter it changes the default flush mode of your configuration. In the DAO layer check the flushMode session.getFlushMode()
The flush mode should not be NEVER or MANUAL
If the session is not getting flushed, you db will not be updated. You have to manually flush the session after your transaction by session.flush()
Also in the in configuration file just change the property to true from false & check <property name="connection.autocommit">true</property>


text:
Q: Sending only order number instead of item names to PayPal in Woocommerce In PayPal standard gateway of Woocommerce, I want to make Woocommerce sends only "order number" as the only item in the cart, instead of the itemized product list.
For that, I tried to edit the class which is responsible for making a PayPal request here:
woocommerce/includes/gateways/paypal/includes/class-wc-gateway-paypal-request.php
I tried to edit get_order_item_names() function to return "invoice" . $order->get_order_number() as the name of the only item, but it wasn't successful since if there would be several items, Only the first one was returned with the order number, and other items remained.
Also, I nailed the add_line_item() function because to approach the purpose, practically there should be only "item_name_1" with the amount of total amount of the card.
$this->line_items[ 'item_name_' . $index ]   = $this->limit_length( $item['item_name'], 127 );
$this->line_items[ 'quantity_' . $index ]    = $item['quantity'];
$this->line_items[ 'amount_' . $index ]      = $item['amount'];
$this->line_items[ 'item_number_' . $index ] = $this->limit_length( $item['item_number'], 127 );

No success here too.
I'd appreciate your assistance.

A:
Recommendation: You should really avoid overriding woocommerce core files.

Instead you could use in this particular case  the filter hook woocommerce_paypal_args, where you will be able to manipulate the arguments that are used in get_request_url() function (that will get the PayPal request URL for an order).
1) TESTING AND GETTING THE DATA SENT
Just to register and get the arguments sent to paypal, I have used the hook this way:
add_filter('woocommerce_paypal_args', 'custom_paypal_args', 10, 2 );
function custom_paypal_args ( $args, $order ) {
    // Saving the data to order meta data (custom field)
    update_post_meta( $order->get_id(), '_test_paypal', $args );
    return $args;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Now I can get the data simply using this (setting the correct order ID):
$order_id = 648;
$data_sent_to_paypal = get_post_meta( $order_id, '_test_paypal' );
echo '
'; print_r( $data_sent_to_paypal ); echo '
';

Or in a hook ( visible in shop pages in this example only for admins ):
// Only visible on shop pages by admins
add_action( 'woocommerce_before_main_content', function(){
    // Only visible by admins
    if( ! current_user_can( 'manage_options' ) ) return;

    $order_id = 648;
    $data_sent_to_paypal = get_post_meta( $order_id, '_test_paypal' );
    echo '
'; print_r( $data_sent_to_paypal ); echo '
';
}, 10, 0 );

This gives me an output like that (for 2 products and different quantities):
Array
(
    [0] => Array
    (
        [cmd] => _cart
        [business] => email@example.com
        [no_note] => 1
        [currency_code] => EUR
        [charset] => utf-8
        [rm] => 2
        [upload] => 1
        [return] => https://example.com/checkout/order-received/8877?key=wc_order_55445ndfgbulfdf&utm_nooverride=1
        [cancel_return] => https://example.com/cart/?cancel_order=true&order=wc_order_55445ndfgbulfdf&order_id=8877&redirect&_wpnonce=34m7kl83455
        [page_style] =>
        [image_url] => https://example.com/wp-content/uploads/2012/06/logo.png
        [paymentaction] => sale
        [bn] => WooThemes_Cart
        [invoice] => pp-8877
        [custom] => {"order_id":8877,"order_key":"wc_order_55445ndfgbulfdf"}
        [notify_url] => https://example.com/wc-api/WC_Gateway_Paypal/
        [first_name] => John
        [last_name] => Doe
        [address1] => Test st.
        [address2] =>
        [city] => wef
        [state] => AR
        [zip] => 43242
        [country] => US
        [email] => myemail@example.com
        [night_phone_a] => 078
        [night_phone_b] => 653
        [night_phone_c] => 6216
        [no_shipping] => 1
        [tax_cart] => 16.55
        [item_name_1] => Test Product - Service
        [quantity_1] => 1
        [amount_1] => 71
        [item_number_1] =>
        [item_name_2] => Test Product 1
        [quantity_2] => 1
        [amount_2] => 66
        [item_number_2] =>
        [item_name_3] => Test Product 2
        [quantity_3] => 1
        [amount_3] => 120
        [item_number_3] =>
        [item_name_4] => Test Product 3
        [quantity_4] => 1
        [amount_4] => 45
        [item_number_4] =>
    )

)

As you can see now, with woocommerce_paypal_args you will be able to alter or remove any arguments.

There is always only one: 'item_name_1', 'quantity_1', 'amount_1' and 'item_number_1' with always index 1 sent to paypal.

2 MANIPULATING THE DATA SENT (example):
We can still use woocommerce_paypal_args, filter hook for example on 'item_name_1' key, to replace the items names by the order number, just as you want:
add_filter('woocommerce_paypal_args', 'custom_paypal_args', 10, 2 );
function custom_paypal_args ( $args, $order ) {
    $$args_keys = array_keys($args);
    $i = 0;
    // Iterating through order items
    foreach( $order->get_items() as $item_id => $item_product ){
        $i++; // updating count.
        if( ! empty($args["item_name_$i"]) ){
            // Returning the order invoice in the item name
            $args["item_name_$i"] = "invoice #" . $order->get_id();
        }
    }
    return $args;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and works on WooCommerce 3+

To finish: As you get the WC_Order object as argument in your hooked function, you can use it to get any data from the order, and manipulate as you like the data sent to paypal gateway.

See this related answer: How to get WooCommerce order details

A: I'm using below function for getting Order ID, You can edit and use below function for your needs.
public function process_payment( $order_id ) {
    global $woocommerce;
    $order = new WC_Order( $order_id );
    return array(
        'result'  => 'success',
        'redirect' => $order->get_checkout_payment_url( true )
    );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integral Solutions of $x+y=x^2−xy+y^2$
Find all integral solutions of
$x+y=x^2−xy+y^2$

In this answer, in the last step(of 1st answer) if $-3x^2+6x+1\ge 0$
how did they find the values of $x$ and how to prove that they are the only ones ?

A: It's just a matter of finding the roots of the quadratic.
$$-3x^2+6x+1\ge0\implies3x^2-6x-1\le0$$
The leading term is positive and the inequality points left, so we know that the range of satisfying $x$ is finite. The roots are $1\pm\frac2{\sqrt3}$, and $x=0,1,2$ are the only integers between those roots, as said in the linked answer.

A: Because the leading coefficient of the given quadratic equation is negative, the equation attains negative values for $x$ greater than both roots or less than and positive values for $x$ between the roots. In this particular case, there happens to be three integers between the roots, therefore three integers where the quadratic is non negative.


text:
Q: How to extract timestamp from output of cmdlet using powershell I have the following output from a cmdlet in powershell, I would like to extract timestamp from output so that I can select jobs which has elapsed time > 24 hours
Command : Get-JAMSEntry -Name * -Server xxxxxx -State Executing

Output :
Entry  Name                   Description
-----  ----                   -----------
1     Sample                  Executing, elapsed time: 602.18:57:06.
3     Sample                  Executing, elapsed time: 481.18:57:02.
5     Sample                  Halted , elapsed time: 484.18:56:58.
7     Sample                  Hold, elapsed time: 680.18:56:55.
7     Sample                  Executing, elapsed time: 680.18:56:54.
7     Sample                  Executing, elapsed time: 680.18:56:53.
9     Sample                  Halted, elapsed time: 666.18:57:09.
1     Sample                  halted, elapsed time: 684.18:57:01.

Appreciate the help.
Thanks

A: When you pipe the output of your command to a Select-Object which inserts calculated properties by splitting the Description first at the , and then at the : like this:
Get-JAMSEntry -Name * -Server xxxxxx -State Executing |
    Select-Object Entry,Name,@{n='State';e={$_.Description.split(',')[0]}},
        @{n='ElapsedHrs';e={($_.Description.Split(',')[1]).Split(':')[1].Trim()}}

you'll get this output:
Entry Name   State     ElapsedHrs
----- ----   -----     ----------
1     Sample Executing 602.18
3     Sample Executing 481.18
5     Sample Halted    484.18
7     Sample Hold      680.18
7     Sample Executing 680.18
7     Sample Executing 680.18
9     Sample Halted    666.18
1     Sample Halted    684.18

you can further reduce with an appeded
|Where-Object {[double]$_.ElapsedHrs -gt 670}

to get only matching values
Entry Name   State     ElapsedHrs
----- ----   -----     ----------
7     Sample Hold      680.18
7     Sample Executing 680.18
7     Sample Executing 680.18
1     Sample halted    684.18


text:
Q: C# Element not found while trying to open serial port I have strange trouble, when I want to print on printer connected via Bluetooth. When I run my program, I get error message:

System.IO.IOException: Element not found. *(I hope it's good translate)
v System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
     v System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)

The code is:
        SerialPort port = new SerialPort();

        port.PortName = listBox.SelectedItem.ToString();
        port.BaudRate = 9600;
        port.Parity = Parity.None;
        port.StopBits = StopBits.One;

        port.DtrEnable = true;
        port.RtsEnable = true;

        if (port.IsOpen)
            port.Close();

        try
        {
            port.Open();
            port.Write("Test.");
            port.Close();
        }
        catch (Exception ex)
        {
            textBox.Text = ex.ToString();
        }

The thing is, when I run this app on Win 8/8.1 it prints OK. When I try it on Windows 10, I got this message. Is there anyone, who can give me any advice? Thanks.


text:
Q: Does Hibernate 3.5.0-CR-2 release support JPA2.0 I see that Hibernate home page has a symbol informing that it implements JSR 317, but I couldn't find if it implements the full spec. Does anybody knows if Hibernate 3.5.0-CR-2 fully implements the JSR 317?
I can see from their JIRA that everything is closed related to JPA 2.0:
http://opensource.atlassian.com/projects/hibernate/browse/HHH-4190?subTaskView=all
Anyone has experienced using JPA2.0 with Hibernate? Does it implement the full spec?

A: The release notes for 3.5-CR1 claim full JPA 2.0 compliance:

I am pleased to announce that we have
  just released Hibernate version
  3.5.0-CR-1. As a refresher, Hibernate follows the JBoss versioing scheme
  where CR is a "Candidate for Release"
  (what many of you might call RC).
  The main stated goal of 3.5 is JPA 2 compliance. This is the first release
  we believe achieves that goal
  entirely. In fact we are in the
  process of certifying for standalone
  JPA 2 compliance and have integrated
  this CR into the imminent JBoss AS M2
  release as part of their effort
  towards full Java EE 6 compliance.

A: I am afraid to tell you that my own experience with the JPA2 implementation of Hibernate convinced me to wait a little.
For some reason, I could not get some very simple beans persisted, even worse when trying to generate some really basic relations. Replacing the Hibernate implementation with EclipseLink made the same code, which I promise is consistent with the JPA2 reference, work.
I would vote for EclipseLink.


text:
Q: Chrome value on load I have some problems with the browser Chrome, when it remembers password, username, etc. I cannot check if the input field is empty.
I use the following code, but the if statement doesn't work in Chrome while it works in all other browsers.
$(document).ready(function() {
    $('.inputWithLabel').each(function(){
        if ($(this).val().length != 0){
            var element_id = $(this).attr('id');
            $('label[for="' + element_id + '"]').addClass('inputWithText');
        }
    });
});

I tried to alter the following labels
<form action="" method="post">

        Brugernavn*
        <input class="inputLabel inputWithLabel" id="username" name="username" type="text">

        Adgangskode*
        <input class="inputLabel inputWithLabel" id="password" name="password" type="password">

        Gentag adgangskode*
        <input class="inputLabel inputWithLabel" id="password_again" name="password_again" type="password">

        Fornavn*
        <input class="inputLabel inputWithLabel" id="first_name" name="first_name" type="text">

        Efternavn
        <input class="inputLabel inputWithLabel" id="last_name" name="last_name" type="text">

        Email*
        <input class="inputLabel inputWithLabel" id="email" name="email" type="text">

        <input type="Submit" class="submit-button" value="Registre">

</form>

I hope someone can help me.

A: To check and see if the input is empty or not you can do something simpler like this.
$(document).ready(function() {
    $(".inputWithLabel").change(function() {
        if ($(this).val() == null || $(this).val() == "") {
            alert("Input is null!");
        } else {
            alert("Input is valid");
        }
    });
});

A: Don't change your code, apply this instead:
$(document).ready(function() {

    $('.inputWithLabel').each(function(){
        if ($(this).val().length != 0 && $(this).val().length != null){
            var element_id = $(this).attr('id');
            $('label[for="' + element_id + '"]').addClass('inputWithText');
        }
    });
});

Only set && $(this).val().length != null after $(this).val().length != 0 and it should run on different browsers. Try it!

A: Try the following code:
    $(document).ready(function() {
      $('body .inputWithLabel').each(function(){
        if ($(this).val().length != 0){
          var element_id = $(this).attr('id');
          $('label[for="' + element_id + '"]').addClass('inputWithText');
        }
      });
   });

Just append body i.e $('body .inputWithLabel') in your each loop.

A: Your Code looks fine...
Label does not have .val() .. if we want innertext of label it should be .text()
so replace .val() with .text() and it will work hopefully....
Also first append body i.e
$('body .inputWithLabel')

A: Try this:

$(document).ready(function() {

    $('.inputWithLabel').each(function() {
        if ($(this).val()) {
            var element_id = $(this).attr('id');
            $('label[for="' + element_id + '"]').addClass('inputWithText');
        }
    });
});

A: You can try it in your site
$('.inputWithLabel').each(function() {
    if ($(this).val() !== null && $(this).val() !== "") {
        var element_id = $(this).attr('id');
        $("#" + element_id).removeClass('inputWithLabel').addClass('inputWithText');
    }
});

A: I'd tried a similar thing. All you have to do is first turn your form id into a jQuery variable,
var $elem = document.getElementById("yourformid").value; //make sure your id has no # symbol
if ($elem > 0) {
    //do stuff
}

that should work.

A: There is currently no possibility to detect if the form is filled by the browser autocompletion. Some alternatives I would suggest are:
Disable autocomplete: If you dont need it, this would be an easy solution
<input autocomplete="off">

or on the whole form:
<form autocomplete="off">

Using the change event to detect any change on the field:
$('#username').on('change keyup',function(){
    // to something
});

Here I can imagine to set a class if there is any change on the input field like:
$('#username').on('change keyup',function(){
    $(this).addClass('changed');
});

Or change the name attribute on the submitted field. e.g.: use this as default:
<input class="inputLabel inputWithLabel" id="username" name="usernameAutofill" type="text">

and change it later to this if anything is done with the input:
$('#username').on('change keyup',function(){
    $(this).attr('name', 'username');
});

But before you do any of this ask yourself following questions:
Why you want to proof the Fields?
What should happen if they are autofilled?
What should happen if they are empty?
What should happen if they are regulary filled?
Because what solution is the best depends pretty much on what exactly you want to do. If you answer this question we can help you more.

A: try using:
$('').value

or
this.value

or
this.textContent

or
$('').innerHTML

A: Your code is checking each input element which HAS some value, not the ones which are empty.
Try changing your condition to:
if ($(this).val().length == 0){
...

this would add the class to the empty field label(s).


text:
Q: Exception in thread "main" java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime I'm quite new to use the build and artifacts features. I have a program that reads a JSON file, evaluates it and return a different JSON file. After creating an artifact and built it, I go in the terminal in the same folder as the one where jar that I built (that I would call programExample.jar for example) is, and type in the terminal to launch the program.

java -jar programExample.jar jsonToRead.json jsonOutput.json

The issue is that after typing this command, this error shows up:

Exception in thread "main" java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime (class file version 63.0), this version of the Java Runtime only recognizes class file versions up to 52.0

I don't understand how I have to solve that and have been looking for a few hours now.
The project use openjdk-19 and when typing java -version in the terminal, I have java version "1.8.0_351" and typing javac -version, I have

javac : The term 'javac' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Would love to have an insight.
If needed, here is also my Maven file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Declarations</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.9.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>19</source>
                    <target>19</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
Q: Getting error in migration, "Syntax error or access violation:1064" I'm trying to insert a json string in to my Laravel 5.2 migration and I get an error, "Syntax error or access violation:1064".
I currently using MySQL version 5.6.17 as my database.
This is from my migration file:
 Schema::create('profile', function (Blueprint $table) {
        $table->increments('id');
        $table->json('settings')->nullable();
        $table->timestamps();
    });

Can i somehow make this happen with my MySQL database or do i need to switch it up with MongoDB?

A: As of Laravel 5.2, the $table->json() method will try to create an actual JSON field in the database. However, the JSON field was not added to MySQL until MySQL 5.7.8.
Therefore, if you're using a version of MySQL previous to 5.7.8, you need to just create it as a text field (which is how Laravel < 5.2 handles it).

A: You need to use MySQL 5.7.8 or higher to use json columns.
https://laracasts.com/discuss/channels/eloquent/table-json-generates-an-error-when-running-migrations
You could update your MySQL version, or you could try to use text as alternative. If it will not work as is, you could decode and encode your json data before and after using DB.


text:
Q: How to fix Terminal not loading ~/.bashrc on OS X Lion Whenever I open a new tab in Terminal using Cmd + T, it opens bash in the same directory, as the previous tab. This works fine when I'm in the ~ directory, but if I'm anywhere else, I get an error loading .bashrc
Last login: Sat Oct 15 21:10:00 on ttys002
-bash: .bashrc: No such file or directory
Jakub-Arnolds-MacBook-Pro:projects darth$

It looks like .bashrc is loaded via relative and not absolute path, because if I do source ~/.bashrc, everything works smoothly.

I think this is a OS X Lion related problem, because before the upgrade from Snow Leopard, I didn't have the same issue. But that might be caused by Terminal always opening at ~, I don't remember if it tried to open the same directory.
However the question remains the same, how can I make Terminal load ~/.bashrc via absolute path, and not relative?

A: Terminal opens a login shell. This means, ~/.bash_profile will get executed, ~/.bashrc not.
The solution on most systems is to "require" the ~/.bashrc in the ~/.bash_profile: just put this snippet in your ~/.bash_profile:
[[ -s ~/.bashrc ]] && source ~/.bashrc

A: Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

A: I have the following in my ~/.bash_profile:
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

If I had .bashrc instead of ~/.bashrc, I'd be seeing the same symptom you're seeing.


text:
Q: Is there an easy way to do vacuum bake-out for UHV or other applications? Do you have issues trying to apply surface heat for vacuum bake-out?  Particularly UHV applications?  I see lots of suggestions on the web and also here, that inevitably talk about heat tape (make sure you know the distinction between flat heating cable which some people call heat tape, and a true, flexible heating tape element) and cables, and they usually end up insulated with wads of tinfoil.  End up looking like that turkey drumstick at Thanksgiving!!!
Seems a better solutions is cloth heating jackets, which can be controlled by a lab PID or modular system type PIDs where each cloth jacket has it's own PID.  You get complete coverage so there are no cold spots, and also avoid having to wrap with a tape and then an insulator.  Cloth heating jackets can be made custom or find a company that already makes component heaters.

A: I did just do a bing search for ultra high vacuum bake out.  I found an application note here at this link.
https://www.briskheat.com/applications/process-temperature-control-and-maintenance/vacuum-bake-out.html


text:
Q: Scalar Insert Query return null I am using Sybase Server, project connected to DB via DataSet.
I created insert query on my tableAdapter
INSERT INTO DBA.opt_port(port, port_level, prim, kluch_raz, speed, agr_port, port_bad)
VALUES (?, ?, ?, ?, ?, ?, ?)

Query execute mode is set to Scalar, but after calling this query it always return null.
var newId = opt_portTableAdapter.InsertNewPort(int.Parse(textBox1.Text), int.Parse(textBox2.Text),
                        textBox3.Text, kluch, int.Parse(textBox4.Text), ToNullableInt(textBox5.Text),
                        ToNullableInt(textBox6.Text))

I also added parameter to query parameters collection, set Direction as ReturnValue and SourceColumn to my primary key, but still null result.
When I manually check new record in my table, it exist and it's pKey is set.
How can I get my primary key after inserting row?
Table creation query is
CREATE TABLE "DBA"."opt_port" (
    "port" smallint NOT NULL,
    "port_level" smallint NOT NULL DEFAULT 1,
    "prim" char(128) NULL,
    "n_pp" integer NOT NULL DEFAULT autoincrement,
    "kluch_raz" smallint NULL,
    "speed" smallint NULL,
    "agr_port" smallint NULL,
    "port_bad" smallint NULL,
    PRIMARY KEY ( "n_pp" )
);

A: CREATE PROCEDURE [dbo].[Add_opt_port]
     ( @input1 varchar(50),
      @input2 varchar(50),
      @id int output
)
AS
BEGIN
      SET NOCOUNT ON;
      INSERT INTO DBA.opt_port
        (port, port_level)
        VALUES (@input1 , @input2)
  SET @id=SCOPE_IDENTITY()
  RETURN  @id

END


text:
Q: Segmentation fault while reading input with getchar() I have a silly problem while reading input with the following code.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

void read(char*** query)
{
    *query = (char**) malloc ( sizeof(char*) );

    int f=0;
    int i=0,j=0,c;

    while((c=getchar())!=EOF)
    {
        if(!isalpha(c))
            continue;

        if(f==1)
            *query=(char**) realloc(*query,(i+1)*sizeof(char*));

        (*query)[i]=(char*) malloc(sizeof(char));
        (*query)[i][j]=tolower(c);
        j++;

        while( (c=getchar())!=EOF&&c!=' '&&c!='\t'&&c!='\n' )
        {

            (*query)[i]=(char*) realloc((*query)[i],(j+1)*sizeof(char));

            (*query)[i][j]=tolower(c);
            ++j;
        }

        (*query)[i][j]='\0';

        ++i;
        f=1;
        j=0;

        if(c==EOF)
        {
            *query=(char**) realloc(*query,(i+1)*sizeof(char*));
            query[i]=NULL;
            return;
        }
    }

    *query=(char**) realloc(*query,(i+1)*sizeof(char*));
    query[i]=NULL;

}

int main()
{

    char** query;
    int i=0;
    read(&query);

    while(query[i]!=NULL)
    {
        printf("%s\n",query[i]);
        i++;
    }

    return 0;
}

So, I want to input any number of strings consisting of alphabetic characters separated by any number of spaces and tabs along a single line then press enter and give EOF signal.(CTRL+D under linux terminal.)  Then, it should output strings line by line fashion.
The problem is when I enter 3 strings it gives segmentation fault, but when I enter more or less strings no problem.
What might be the problem?
Please, help!

A: query[i]=NULL; wrong. –  BLUEPIXY
@BLUEPIXY: Good catch. Also, in the OP's logic, there should be a reallocation before
(*query)[i][j]='\0';

to make room for the null char. –  M Oehm


text:
Q: File download from FTPS folder via HTTPS Protocol I have an activeX Control which is downloading some files from an FTPS server.
Now I want to change the protocol to HTTPS .
Is there some way to access an ftp folder like https://192.0.0.0/filename.xml where 192.0.0.0 is the ftp host name?

A: Many HTTP proxy servers let you request FTP resource via them. So if you can route the request to the proxy, you can ask it to retrieve the file from FTP URL for you. Otherwise no, you would have to run (and properly configure) an HTTP server on the system where the file resides.


text:
Q: How can I run a curl command for each line of output from my Perl script? I have a perl script that writes out an array filled with integers to stdout, each on a separate line.  So I would get output like:
412
917
1
etc

What I would like to do is be able to pipe the output of this script into xargs, and make a curl call using each integer.  Something like this:
cat input.json | ./jsonValueExtracter.pl -s exampleId | xargs curl http://brsitv01:8080/exampleId/$1 > example$1.json

Below is an excerpt of a simple script I am using.
my @values;
while(<STDIN>) {
     chomp;
     s/\s+//g; # Remove spaces
     s/"//g; # Remove single quotes
     push @values, /$opt_s:(\w+),?/g;
}

print join(" \n",@values);

However, this doesn't work the way I would expect.  When I run the following command:
cat input.json | perl jsonValueExtracter.pl -s exampleId | xargs echo http://brsitv01:8080/exampleId/$1

I get the output:
http://brsitv01:8080/exampleId/ 412 917 1

Is there anything special I need to do to use the output of a perl script in xargs?
Thanks

A: Add -n 1 to xargs to make it eat only one argument on each run.

A: xargs doesn't use $1 like that. $1 is blank, and xargs just puts the numbers at the end of the command line.
You probably want to use a bash for loop like:
for i in `./jsonValueExtracter.pl -s exampleId < input.json`
do
  curl http://brsitv01:8080/exampleId/$i > example$i.json
done

Which can be written on one line with semi-colons:
for i in `./jsonValueExtracter.pl -s exampleId < input.json`; do curl http://brsitv01:8080/exampleId/$i > example$i.json; done

Note that you don't need cat:
cat [file] | script.foo

Is equivalent to:
script.foo < [file]


text:
Q: Get page number from line number with synctex from command line I have several hundreds of line numbers in LaTeX file and I need to get corresponding page numbers on pdf. I would like to perform "command line" forward search, using some Synctex command line interface (that I don't want to develop).
Is there some way to get this using available synctex tools?
Cumbersome solution (without synctex): put \refstepcounter{foo}\label{l-<linenumber>} on each such line and get page number from aux file.

A: You can do
synctex -i linenumber:columnnumber:texfile -o pdffile

If I understood synctex correctly, the columnnumber is currently not used, i.e., it can be set to 1.
This command might show multiple locations which could correspond to the line in the source code. (I would typically take the first one).


text:
Q: IOC dependency injection deployment (bin ? GAC ?) Are there any deployment requirements for the most popular IOC containers (example: Windsor, Ninject, Unity, StructureMap, Autofac) ?  Do they all deploy the same?
If you're on a shared host, what challenges will that present (ex. medium trust, etc...)
Can they be bin deployed?  GAC deployed?
Any web-hosters that come "IOC-ready"?

A: Most of the IOC frameworks works with private assemblies and i dont know much Web hosters that allows you to deploy files into the GAC.


text:
Q: Not allowing to procceed using Javascript So basically what I'm trying to do is to block access to submit information. I usually do this by onsubmit=CheckForm() and if a false is returned then the data just won't be sent.
In this code, I'm using different functions and haven't found a way in which I could return false and not allow to continue.
*The functions basically say if the typed URL is a valid image, or not, by an alert. After the alert, it sends the data. I would like it to show the alert, but just simply not send anything but refresh(For instance).
Javascript:
        var test = function () {
            document.getElementById('image2').src = document.getElementById('image').value;
        }

        var errorCallback = function () {
            alert('Image did not exist');
            return false;
        }

        var loadCallback = function () {
            alert('Image existed');
        }

HTML:

URL to prested Image:
<input type="text" id="image" name="image" class="URLs" value="http://"/>

<input type="submit" class="myButton" style="padding: 25px 150px; line-height:6px;" value="Submit Details" onclick="test()" />

Thanks in advance!

A: Option 1: Return false in the function.
By returning false in the onclick handler, it will prevent the submit event from taking place.
Change:
var test = function () {
  document.getElementById('image2').src = document.getElementById('image').value;
};

<input type="submit" class="myButton" style="padding: 25px 150px; line-height:6px;" value="Submit Details" onclick="test()" />

To:
var test = function () {
  document.getElementById('image2').src = document.getElementById('image').value;
  return false;
};

<input type="submit" class="myButton" style="padding: 25px 150px; line-height:6px;" value="Submit Details" onclick="return test()" />

Option 2: Pass the event handler and stop the default event from occurring.
Change:
var test = function () {
  document.getElementById('image2').src = document.getElementById('image').value;
};

<input type="submit" class="myButton" style="padding: 25px 150px; line-height:6px;" value="Submit Details" onclick="return test()" />

To:
var test = function (e) {
  document.getElementById('image2').src = document.getElementById('image').value;
  e.preventDefault();
};

<input type="submit" class="myButton" style="padding: 25px 150px; line-height:6px;" value="Submit Details" onclick="return test(event)" />

Option 3: Change the input to type=button as to not trigger a submit event.
Change:

<input type="submit" class="myButton" style="padding: 25px 150px; line-height:6px;" value="Submit Details" onclick="test()" />

To:

<input type="button" class="myButton" style="padding: 25px 150px; line-height:6px;" value="Submit Details" onclick="test()" />

A: The first step is to prevent default action of submit to take place, i.e.:
function test(e)
{
    e.preventDefault();
    // ...
}

<button type="submit" ... onclick="test.call(this, event);" ... >

The above binds the element as this in the test() function and passes the event object.
The second step requires an asynchronous action of loading an image, so get rid of all the other functions and the hidden image; then proceed with just this:
function test(e)
{
    e.preventDefault();

    var form = this.form; // keep reference of the form

    var i = new Image(); // create image object
    i.onload = function() {
        form.submit(); // hurray, it works, save it!
    };

    i.onerror = function() {
        alert('awww, image did not exist');
    };

    // all set, load the image!
    i.src = document.getElementById('image').value;
}


text:
Q: How to get current texture from current frame of animation in SKAction? I'm trying to animate something that spins / left to right, but whenever I call
 spinLeft() or spinRight() then the animation always starts from frame 0.
In other words, I want to be able to say spin something 4 out of 10 frames, stop, then
 spin in the opposite direction, FROM frame 4. Right now, it resets to frame 0.
var textures = [SKTexture]() // Loaded with 10 images later on.
var sprite = SKSpriteNode()

func spinLeft() {
  let action = SKAction.repeatForever(.animate(with: textures, timePerFrame: 0.1))
  sprite.run(action)
}

func spinRight() {
  let action = SKAction.repeatForever(.animate(with: textures, timePerFrame: 0.1)).reversed()
  sprite.run(action)
}

A: You could do this (Syntax may be a little off, but you get the point):
The key here is the .index(of: ... ) which will get you the index.
func spinUp() {
    let index = textures.index(of: sprite.texture)
    if index == textures.count - 1 {
        sprite.texture = textures[0]
    }
    else {
        sprite.texture =  textures[index + 1]
    }
}

func spinDown() {
    let index = textures.index(of: sprite.texture)
    if index == 0 {
        sprite.texture = textures[textures.count - 1]
    }
    else {
        sprite.texture =  textures[index - 1]
    }
}

func changeImage(_ isUp: Bool, _ amountOfTime: CGFloat) {
    let wait = SKAction.wait(duration: amountOfTime)
    if isUp {
        run(wait) {
            self.imageUp()
        }
    }
    else {
        run(wait) {
            self.imageDown()
        }
    }
}

If you use something like a swipe gesture recognizer, you can use it's direction to set the isUp Bool value and the velocity of that swipe for the amountOfTime for the changeImage function.
The changeImage will only change the image once, so you will need to handle this somewhere else, or create another function if you want it to continuously spin or die off eventually.
Hope this helps!


text:
Q: How to add "On Click" event to dynamically created menuStrip item from mySQL? I've coded my form to take name values from a table in MySQL and add them as sub menu items. Now I would like for my code to load information from another table corresponding to the menu item that was created. How can i do that?
Here is my working code. All it's missing is the "On click" event.
Cheers and thanks.
private void populateMenuItem()
{
    Query = "select * from serpesa.proveedores;";
    mysqlConnect();

    while (mysqlReader.Read())
    {
        string menuItem = mysqlReader.GetString("nombre");
        abrirToolStripMenuItem.DropDownItems.Add(menuItem);
    }
    mysqlDisconnect();
}

A: Add() returns the ToolStripItem that it creates.
You can then add a handler to its Click event.


text:
Q: Keras fit_generator: random augmentation inside the generator + shuffling I have created a generator to input it in the fit_generator function of keras. The generator creates some random values. This is how I have done it:
class DataGenerator(object):
    def __init__(self, X_Y_file_path, batch_size, N):
        self.X_Y_file_path = X_Y_file_path
        self.batch_size = size
        self.N = N

    def initialize_zeros(self):
        X = np.zeros((self.batch_size, 1), dtype='int32')
        Y = np.zeros((self.batch_size, 1), dtype='int32')
        Y_neg = np.zeros((self.batch_size, self.N))
        return X, Y, Y_neg

     def generate(self):
        while True:
            i = 0
            X, Y, Y_neg = initialize_zeros()
            for row in load_data_per_line(self.X_Y_file_path): # load_data_per_line is generator function which goes each line at a time from one file.
                x, y = row
                y_neg = random.sample(id_list, self.N) # a list of id to pick randomly
                X[i] = x
                Y[i] = y
                Y_neg[i] = y_neg
                if i == self.batch_size:
                    yield ([X, Y_neg], Y) # Y_neg goes as input in the model.(not important here. just mentioning)
                    X, Y, Y_neg = initialize_zeros()
                    i = 0

So this is my generator. With same sample data it seems its working correctly though.
I was wondering how can I implement in this generator a shuffle function to shuffle after each epoch?
Searching a bit I found out about Sequence which you can override on_epoch_end method but it is not clear how I can implement the above generator with Sequence inheritance. Any help on that? (btw is the above function 'safe' to use use_multiprocessing in fit_generator?)
Edit
The X_Y_file_path is one file(with known length).
The load_data_per_line is a generator function which yields one per line.

A: You are on the right track to use a Sequence. It will guarantee that every data point is seen once when used with multi-processing. An easy way to construct the Sequence is preload the raw data, do on the fly processing every time a batch is requested.
class MySeq(Sequence):
    def __init__(self, X_Y_file_path, batch_size, N):
        self.X_Y_file_path = X_Y_file_path
        self.batch_size = size
        self.N = N
        self.data = load_data_per_line(self.X_Y_file_path)

     def __len__(self):
        return int(np.ceil(len(self.data) / self.batch_size))

     def __getitem__(self, idx):
        # Just slice the data based on batch index (idx)
        batch_data = self.data[idx*self.batch_size:(idx+1)*self.batch_size]
        X = np.zeros((len(batch_data), 1), dtype='int32')
        Y = np.zeros((len(batch_data), 1), dtype='int32')
        Y_neg = np.zeros((len(batch_data), self.N))
        for row, i in enumerate(data):
            x, y = row
            y_neg = random.sample(id_list, self.N) # a list of id to pick randomly
            X[i] = x
            Y[i] = y
            Y_neg[i] = y_neg
        return [X, Y_neg], Y # This is a single batch

Now you can perform any processing on your self.data using on_epoch_end()


text:
Q: What are alternatives to ExtJS? So what I'm looking for is a javascript framework I can use that has several UI controls. I have taken a look at jQuery but those controls are very basic compared to ExtJS. Are there any other competitive alternatives?

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. More info: help center.

A: Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don't want to be locked into.

-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Leading client widget libraries

*

*Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs

*Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples

*react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

*kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools

*OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO

*DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

*Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

*Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

*PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license.  Small GitHub community. 35 premium themes available.

*qooxdoo - "a universal JavaScript framework
with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).

Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community

*jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

*angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

*DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Wikipedia • GitHub • Themes • Demos • Desktop widgets • SO

*Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

*The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

*Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

*CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

*ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

*Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

*CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

Widgets - Demo Apps - Examples - GitHub
Full-stack frameworks

*

*SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

*Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

*

*Wakanda Server (server-side JavaScript (custom engine) + open-source NoSQL database)

*desktop IDE and WYSIWYG editor for tables, forms, reports

*Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.

*Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

*SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

*Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

*Backbase - portal software

*Shiny - front-end library on top R, with visualization, layout and control widgets

*ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
CSS libraries + minimal widgets
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

*

*Bootstrap

*Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

*UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Libraries using HTML Canvas
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

*

*Zebra - demos
No longer developed as of Dec 2014

*

*Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.

*echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.

*ampleSDK

*Simpler widgets livepipe.net

*JxLib

*rialto

*Simple UI kit

*Prototype-ui
Other lists

*

*Best of JS - component toolkits

*Wikipedia's Comparison of JavaScript frameworks

*Wikipedia's list of GUI-related JavaScript libraries

*jqueryuiwidgets.com - detailed jQuery widgets feature comparison


text:
Q: Glyphicons are different colour on iOS compared to Android For example:

The 'btn-header-*' only applies padding.
.header-glyph, header-glyph:active, header-glyph:focus, header-glyph:hover,
header-glyph:visited {
    color: #428bca !important;
    font-size: 25px !important
}

Android this is blue (#428bca), yet on iOS this is an orange colour.
Can't see anything behind the scenes that would make it inherit this colour.
Looking for a platform specific issue that can be hopefully overridden?? I am developing on iOS 9.0.2 also.

A: I was asked to update my iOS from 9.0.2 to 9.1.0. This styling issue cannot be replicated any longer. Looked at the release notes out of curiosity, but nothing that specific.


text:
Q: Magento 2 - remove .html from URL by using .htaccess We have some wrong URLs in our store ending with .html. If the user opens such a URL, then the .html should get removed, otherwise the site cant get found.
So I added this rule to my .htaccess file in pub/.htaccess, i also tried the normal .htaccess in the magento root.
<IfModule mod_rewrite.c>

...

############################################
## Remove .html from end of URL

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^(.*)\.html$ /$1 [L,R=302]

</IfModule>

But if I enter a URL with .html at the end, then it is still not getting removed.
I want to make it work by using the .htaccess, otherwise I will have to create plenty of URL rewrites by hand.

A: Hi I understand actually you want to redirect .html page to without.html page
You can add following code in .htaccess :
for example :
Redirect /specific-page.html /specific-page


text: Q: Generating Qt moc files in VS2019 How to generate all the moc files in VS2019? I use VS terminal to generate moc files like "C:\moc path" somefile.h > moc_somefile.cpp one by one and then include to the project. Is there a way to create all the moc's in terminal? Or any other way to do this?


text:
Q: LWJGL Indexed VBO, a lot of confusion I cannot figure out how to use an Indexed VBO, IMHO there's a lack of information about it (for example the lwjgl site in which the indexed vbo page is missing ATM).
The structure i'm using in my vertex buffer is {pos.x, pos.y pos.z}, {tex.u, tex.v tex.W} and {norm.x, norm.y norm.z}, my index buffer structure is {posIndex, texIndex, normIndex}
I'm reading all this data from an .obj file, if tex or norm is missing i set it to{-1,-1,-1}.
Here's the code part in which i send data to the GPUs buffers:
    this.VBOSize = Vertices.size();
    FloatBuffer vbo = BufferUtils.createFloatBuffer(this.VBOSize);
    for (int i = 0; i < this.VBOSize; i++) {
        vbo.put(Vertices.get(i));
    }
    vbo.flip();
    glBindBuffer(GL_ARRAY_BUFFER, VBOHandle);
    glBufferData(GL_ARRAY_BUFFER, vbo, GL_STATIC_DRAW);

    this.IBOSize = Indices.size();
    IntBuffer ibo = BufferUtils.createIntBuffer(this.IBOSize);
    for (int i = 0; i < this.IBOSize; i++) {
        ibo.put(Indices.get(i));
    }
    ibo.flip();
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBOHandle);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, ibo, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

and here's how i [incorrectly] render it:
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    glBindBuffer(GL_ARRAY_BUFFER, Object3D.getVBOHandle());
    glVertexAttribPointer(0, 3, GL_FLOAT, true, 12, 0);//3 floats * 4 sizeof(float)
    glVertexAttribPointer(1, 3, GL_FLOAT, true, 12, 13);
    glVertexAttribPointer(2, 3, GL_FLOAT, true, 12, 25);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Object3D.getIBOHandle());
    glDrawElements(GL_TRIANGLES, Object3D.getIBOSize(), GL_UNSIGNED_INT, 0);

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);

A: THis is not how opengl works. In openGL, a vertex is a set of attributes like position, normal, color, textcoord, whatever. Indexed rendering just references vertices. You cannot have different indices for the various attributes, but just one index for the whole set. If you have the situation where two vertices share their position, but, not the texcoords, they are entirely _different_ vertices, as far as the GL is concerned. You cannot directly use the data from lightwave .obj files but have to preprocess the data to generate the vertex arrays OpenGL can work this.
There is the GL_AMD_interleaved_elements extension which somewhat implements the feature you want to use. It still uses 32-Bit indices, but allowes one to split them into 2 16-Bit or 4 8-Bit indices to use different indices for different attributes, but this extension is far from being in core GL, isn't widely supported and is still very limited.
Nowadays with the programmable pipeline, one could also do the index dereferencing manually in the shaders, basically (mis)using the vertex attributes and accessing the real attribute arrays via a texture buffer object, but that is quite advanced and the performance implications are not clear.


text:
Q: Plotting three variables in ggplot on the same graph I have the following dataset:
Time               Served        MAC             BLER
07:16:18.341       7561.60       6721.60             8.33
07:16:18.641       10321.44          8198.24             16.47

I have omitted the other samples for brevity.
I would like to plot in the x-axis Time, and the Y axis the three other variables i.e. Served, MAC and BLER on the same graph in ggplot2.
How can I do this?
many thanks

A: you need data in melted form.
require(reshape2)
df.m<-melt(df,id.var="Time")

then
ggplot(df.m, aes(x=Time, y=value, color=variable))+geom_line()

but I am afraid about the scaling of y axis


text: Q: IPython notebook shows output in terminal I'm using an IPython notebook (ipython notebook &), but when I try to print something to get any output by simply giving the variable name ans pressing Shift + Enter, instead of getting the output in notebook (next to the cell), I get it in the terminal from where I launch the notebook. I want to see the output in the notebook itself, next to the concerned cell. I'm facing this problem lately, previously it was working fine.


text:
Q: Deleting browser (IE) cache and cookies using VBScript I need help deleting browser cookies and cache using VBScript.. I have tried many methods from various blogs but found useless..
Thanks in advance!

A: Set WshShell = CreateObject("WScript.Shell")
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8"

'To clear browsing cookies
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2"

'To Clear Browsing History
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1"

Try that.


text:
Q: Asset loading failing (Cocoa for OS X) I'm very new to mac development and I have a hard time understanding how all this Cocoa stuff works.
Right now I'm working on getting still images from a video file and in order to do so, I need to load my video file (asset).
NSURL *url = [[NSURL alloc]initWithString:@"/Users/EVG/Desktop/myfile.mp4"];

AVURLAsset *myAsset = [[AVURLAsset alloc] initWithURL:url options:nil];

NSArray *keys = @[@"tracks"];

[myAsset loadValuesAsynchronouslyForKeys:keys completionHandler:^()
 {
     NSError *error = nil;
     AVKeyValueStatus tracksStatus = [myAsset statusOfValueForKey:@"tracks" error:&error];

     if ( tracksStatus == AVKeyValueStatusFailed ||
         tracksStatus == AVKeyValueStatusCancelled )
     {
         NSLog(@"Failed with error: %@", [error localizedDescription]);
     }
 }];

After this code is executed I'm getting the following message:
NSView Controller[644:4413] Failed with error: The operation could not be completed
Does anyone know how to solve this problem I'm having?
Thank you!!!

A: Your URL is wrong. First of all, absolute file paths should begin with a /, as in /Users/EVG/Desktop/myfile.mp4. However, that's not a URL. A file URL should be file:///Users/EVG/Desktop/myfile.mp4.


text:
Q: counting mysql values I have a table with two fields, TAG_ID and TAG_DESC
my primary is tag_id.
I'm looking for a query that will display each TAG_DESC and the amount of times it occurs next to it.
Thanks,

A: select TAG_DESC, count(*)
from MyTable
group by TAG_DESC

A:   SELECT TAG_DESC as 'Description',
         COUNT(TAG_DESC) as 'Occurances'
    FROM table_name
GROUP BY TAG_DESC


text:
Q: Testing Spring Boot rest controller, unable to locate package for is() I'm writing a test for a REST controller in Spring Boot. Is uses is(), but my IDE is not suggesting what package this is in so I'm unable to find it.
Here's my test method;
@Test
    public void printerIsReady() throws Exception {
        /* Set the contents of status.txt to anything other than 3 */
        String statusFilePath = printerPath + "/status.txt";
        PrinterFileHelper.writeToFile("5", statusFilePath);

        this.mockMvc.perform(get("/printer"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.status", is("READY")));

    }

I'm finding a lot of examples online that use the is() method, but it's not clear at all what package I need to be adding in order to access it.

A: I found the answer here How to check String in response body with mockMvc
The package you need to import is;
import static org.hamcrest.Matchers.*;

I needed to add the package to my pom.xml file
<dependency>
    <groupId>org.testinfected.hamcrest-matchers</groupId>
    <artifactId>core-matchers</artifactId>
    <version>1.5</version>
</dependency>


text:
Q: Jquery Jslider shows wrong value on the hidden input field I am trying to add a Jslider of price in my website.
here is the slider UI code in html
<div class="layout-slider">
<input id="Slider-price" type="slider" name="price" value="5;10" class="form-control" />
</div>

and the javascript is
<script type="text/javascript">
    $('#Slider-price').slider({from: '5',   to: '10', step: 1, dimension: ' $' });
</script>

The original code is works well. Whicj is as same as the above code. But when I include it to my website, the input value goes wrong.
Fro example, if I give value="5;10" in my code, after running, it changes to value="55;55" and the value in javascript have no changes at all. Because of this, it didn't work and the slider pointer located at the end of the slider and cant slide it. What is wrong with this? Please help

A: It's because the to/from values are surrounded by single quotes and therefore being interpreted as strings  instead of integers.
'5' + '5' = '55'; // string concatenation
 5 + 5 = 10; // numeric addition

Remove the quotes on the to/from values:
<script type="text/javascript">
  $('#Slider-price').slider({
    from: 5,
    to: 10,
    step: 1,
    dimension: ' $'
  });
</script>

see: http://jsfiddle.net/y2mPJ/


text:
Q: SQL counter increment concurrency issues - The select/update issue This is more of a knowledge sharing post.
Recently in one of my projects, I came across a issue which is pretty common, but never really gave it a thought till I faced it.
There are number of solutions available, but somehow I did not find THE ONE I was looking for, which I am going to share in this post. I am sure many of you already know about the below solution, but for those who don't this can definitely be a life saver. :-)
The Problem:
Recently, I was working on a windows service. This service was supposed to insert some records into a table that long existed and being used by several other old services. There is a column (say "ID") which holds an integer value. The logic written (probably years ago) to get the Integer to insert into this table is stated below:
The logic:

*

*Read a value from a table (say Table 1 – Name/Value pair),

*Increment it by 1

*Update the value and

*Finally get the new value[/highlight].

Code
SELECT @value = [Value] from [dbo].[Table1] WHERE [Name] = @Name;
UPDATE [dbo].[ Table1] SET [Value] = @value +1  WHERE [Name] = @Name;
SELECT @value = @value+1;

The technology used has Major Concurrency issues.

*

*Same value being read by multiple threads

*Deadlock problem

What is the best way to address such an issue -  Considering this is referred to in many different applications/services?

A: The Resolution
The obvious thought would be get rid of this piece and rewrite this. But there are times, particularly when you work on areas like this where certain logic, tables, codes are already getting referenced by several other programs, it is not an easy call.
My goal was to attack the root of the problem and get rid of it. If I can do that there are supposed to be no real impacts. The output of the proc would be the same, so to the outside world nothing actually changed. :-)
So, I did some minor tweaks to the above statements to ensure that every thread updates the value and reads the updated value. No more conflicts, no more dirty reads.
Updated Code
DECLARE @table table(
    Value int NOT NULL
);

-- Update the value and output the same into a local table variable
UPDATE [dbo].[Table1] SET [Value] = [Value] + 1  OUTPUT inserted.[Value] INTO @table
WHERE [Name] = @Name

-- Now read the value from the local table variable
SELECT Value FROM @table;

For more information on output clause check https://msdn.microsoft.com/en-us/library/ms177564(v=sql.90).aspx
I ran some tests with a parallel.foreach (20,000 times). My test table had two entries -

*

*Name = First and Value = 1 - After 20,000 updates the value should be 20,001

*Name = Second, Value = 100 - After 20,000 updates the value should be 20,100

If you check the attachment, you will find out the difference in the numbers.

Deadlock issues are hard to reproduce, but the problem with multiple threads reading the same value in clearly evident from the test result.
Any thoughts on this is most welcome.
As I said earlier, many of you would already know this solution, but for those who don't this can definitely save some time. :-)


text:
Q: Form opened with ShowDialog closes after exception I have a FormA from which I open FormB like so:
FormB B = new FormB();
FormB.ShowDialog();

In FormB, I have some code in a try catch block and when it throws the exception, FormB is closed.
private void func()
{
  try
  {
     // some code
     DialogResult = DialogResult.Ok;
     throw new Exception("Test exception")
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

Take look at that two lines of code. When DialogResult assignment is above exception throw, form closes after exception.
Vice versa, the form is not closing. So can someone explain that behavior?

A: When you are changing the DialogResult property of a Form (which is shown with ShowDialog()), it will be closed. When you raise an exception before setting the property, the property won't be changed, so it won't close the form. When a form isn't displayed as a modal dialog box, clicking the Close button (the button with an X in the top-right corner of the form) causes the form to be hidden.

I'll give some more info.
Like the documentation says:

The dialog result of a form is the value that is returned from the form when it is displayed as a modal dialog box. If the form is displayed as a dialog box, setting this property with a value from the DialogResult enumeration sets the value of the dialog box result for the form, hides the modal dialog box, and returns control to the calling form. This property is typically set by the DialogResult property of a Button control on the form. When the user clicks the Button control, the value assigned to the DialogResult property of the Button is assigned to the DialogResult property of the form.

Source
So if you set the property before the exception. It will trigger the dialog to close. (it probably sends a WM_CLOSE message to the form, that's why it doesn't close directly)


text:
Q: Azure Mobile Service Authentication - App.MobileService does not exist I have a Windows 8 Store Application and I want to add Azure Authentication to it.  I have followed the example in the MSDN page.  However, the following line is giving me issues:
MobileServiceUser loginResult = await App.MobileService.LoginAsync(result.Session.AuthenticationToken);

The error is: App does not contain a definition for MobileService.  When does an instance of MobileService get added to the App class?
I have added references to the Microsoft.Live and Azure Mobile Services libraries.  Here is the entire Authenticate function:
private async System.Threading.Tasks.Task Authenticate()
        {
        LiveAuthClient liveIdClient = new LiveAuthClient("<< INSERT REDIRECT DOMAIN HERE >>");

        while (session == null)
        {
            // Force a logout to make it easier to test with multiple Microsoft Accounts
            if (liveIdClient.CanLogout)
                liveIdClient.Logout();

            LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });
            if (result.Status == LiveConnectSessionStatus.Connected)
            {
                session = result.Session;
                LiveConnectClient client = new LiveConnectClient(result.Session);
                LiveOperationResult meResult = await client.GetAsync("me");
                MobileServiceUser loginResult = await App.MobileService.LoginAsync(result.Session.AuthenticationToken);

                string title = string.Format("Welcome {0}!", meResult.Result["first_name"]);
                var message = string.Format("You are now logged in - {0}", loginResult.UserId);
                var dialog = new MessageDialog(message, title);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }
            else
            {
                session = null;
                var dialog = new MessageDialog("You must log in.", "Login Required");
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }
        }
    }

A: You have to add the class yourself.
On the Azure Mobile Services "Getting Started Page", select "Windows Store", and then "CONNECT AN EXISTING WINDOWS STORE APP" (don't mean to shout, it's literally in all caps on the page like that!).
It will tell you to do the following:

Add "using Microsoft.WindowsAzure.MobileServices;", then copy and
  paste the following code into your App.xaml.cs file:
public static MobileServiceClient MobileService = new MobileServiceClient(
    "https://[your website].azure-mobile.net/",
    "[your key]"
);


text:
Q: Export Python TensorFlow model and import it in C++ I followed this tutorial and tried to change it for my needs. I have a python file where I train a model and save the TensorFlow graph and frozen_graph, which should have the weights and architecture. And I've got a C++ file where I read the frozen_graph and try to predict an example.
// The session will initialize the outputs
vector<Tensor> outputs;
// Run the session, evaluating our "softmax" operation from the graph
status = session->Run(inputs, {"output_TT"}, {}, &outputs);
int nHits = 0;
int nClasses = 2;
for (vector<Tensor>::iterator it = outputs.begin(); it != outputs.end(); ++it) {
    auto items = it->shaped<float, 2>({nTests, nClasses}); // 2 represent number of class
    for (int i = 0; i < nTests; i++) {
        int arg_max = 0;
        float val_max = items(i, 0);

but when I try to retrieve the results from the predictions I only get NaN from items(i, 0)
Here are all the files at github:

*

*train_save_model.py (to train and save the graph)

*pima-indians-diabetes.csv (csv for learning in python)

*diabetes.cc (c++ file where I load and predict)
Did I save the frozen_graph incorrectly? I also created a frozen graph on command line with bazel, but got the same effect. Did I read the data wrong in C++?


text:
Q: Finding CORS-friendly images online WebGL only allows to use images as textures for which the hosting webserver explicitly allows to use cross-origin.
Are there image databases that I can use with my WebGL?

A: You can use Google Picasa, which supports CORS-requests (Source: WebGL Up and Running page 163).


text:
Q: Issue deploying app to Heroku from cloud 9 I have an app on cloud 9 IDE, it works perfectly on cloud 9 when I run nodemon server.js but when I deploy it to Heroku it gives an application error.
How I am deploying it to git:

*

*Login into Heroku and create an app online

*Then in cloud 9 terminal I type heroku login and then type in my details

*Then I type git init

*Then heroku git:remote -a agile-stream-37163

*Then git add .

*Then git commit -am "initial commit"

*Then git push heroku master
It deploys successfully but when I actually go to the app url it comes up with application error. I think I am deploying it wrong, I don't have much experience with git.
Heres an image from my cloud 9 terminal:

Can anyone please tell me how I can fix this.


text:
Q: How to output 3 top sales for each customer using MySQL? So i have 3 simple tables like this:
Customers table

customer_id
customer_name

1
Gigashots

2
Devshare

3
Realblab

...
...

Products table

product_id
product_name

1
Omeprazole

2
ESZOPICLONE

3
Calcipotriene

...
...

Sales table

sale_date
customer_id
product_id
total_sum

2015-02-12
1
1
45651.68

2016-01-14
2
3
19139.20

2016-04-28
5
4
40195.22

2016-05-22
3
3
33808.53

2016-05-27
8
2
11880.73

2016-07-13
4
4
13092.21

...
...
...
...

I need to select 'customer_name', 'product_name' and 'total_sum' and output 3 products for each customer on which he spent most of money in 2016, sorted by:
customer_name - ascending;
total_sum - descending.
I tried to do it using this query:
SELECT
customer_name, product_name, total_sum
FROM sales
JOIN customer
ON customer.customer_id = sales.customer_id
JOIN product
ON product.product_id = sales.product_id
WHERE sale_date >= '2016-01-01' AND sale_date < '2017-01-01'
ORDER BY customer_name ASC, total_sum DESC
LIMIT 3

BUT the 'LIMIT 3' only shows me this:

customer_name
product_name
total_sum

Gigashots
Omeprazole
37047.59

Gigashots
ESZOPICLONE
20114.64

Gigashots
Calcipotriene
19386.09

I know only the basics of SQL and can't get my head around this task. Can you help me?

A: You want to use window functions along with aggregation:
SELECT cp.*
FROM (SELECT c.customer_name, p.product_name, SUM(s.total_sum) as total_sum,
             ROW_NUMBER() OVER (PARTITION BY c.customer_id ORDER BY SUM(s.total_sum) DESC) as seqnum
      FROM sales s JOIN
           customer c
           ON c.customer_id = s.customer_id JOIN
           product p
           ON p.product_id = s.product_id
      WHERE sale_date >= '2016-01-01' AND sale_date < '2017-01-01'
      GROUP BY c.customer_id, c.customer_name, p.product_id, p.product_name
     ) cp
WHERE seqnum <= 3;


text:
Q: What non-religious expressions can I use instead of "Thank God"? I'll give an example to help:

Someone suffered a car accident, but physically the person is OK. So I
say, "Thank God, they are fine."

A: If you want to express thanks to a "higher power" but want to name it something other than God, (or God-related, like "thank heavens" "praise the lord", "lord have mercy" "hallelujah" etc.) you could say "thank goodness". "Goodness" can mean more than just lucky happenstance in that situation.
If you want to just say that it is fortunate she was not injured, due to nothing more than the particulars of the accident, you could say "thank her lucky stars" or "thankfully, she was not hurt".
I interpret many insurance accident claims phone calls, and I've noticed that most insurance company accident claims processors will avoid faith-based terms by expressing their own relief to know that no one was injured with statements like, "I'm glad to hear no one was hurt," "I'm sorry for your experience, but it's so fortunate that there were no injuries," "what a relief to know everyone is okay."
I agree with many that "thank God" is used ubiquitously, regardless of faith, religion, or spirituality.

A: You could say "thank the laws of physics".  (I've never heard anyone actually use this, and may only be funny to World of Warcraft players).
It's an obvious mockery / subversion of the common religious / spiritual phrase, and only works as a joke.  (Because science doesn't involve worshipping our current best understanding of how things work).  Even as a joke, it also draws attention to the fact that you're avoiding religious language in a really on-the-nose way.
For the love of science is less over-the-top (you can love science), and I have actually said it out loud in real life.  It doesn't exactly fits this use-case, though.

A: Thank goodness

I am pleased or happy

The Free Dictionary

A: Why is it necessary to say anything at all?  It would be like talking to the dice before you throw them.  'How about I'm glad you are alright!'

A: Replacing "thank god" with thankfully should work in all cases. Otherwise:
It's a relief that... /
I'm glad that...

A: Depending on the people and setting, this is a favourite vulgar expression of mine...

 Thank fuck for that!

Maybe just a British thing?

A: You may use the expression:

What a relief to know that you were out of danger!

A: Fritz Lieber, the science fiction author, coined "thank the bonny dew" to which I'm partial.

A: Fortunately
This gives the following sentence:

Fortunately, he/she is fine!

A: Express Happiness, Not Thanks
Many responses say something like "thank the goddess" or "thank goodness" or "thank science". But unless you believe one of these things is a person to whom you owe gratitude, that's nonsense at best and may be taken as mocking those of us who do believe in a higher power. (Which you're free to do, but it wasn't what you asked about.)
Why not say something that expresses happiness rather than thanks?

*

*"Happily, she wasn't hurt."

*"I'm glad to say she wasn't hurt."

*"You'll be relieved to know she wasn't hurt."

A: You could thank whoever or whatever is actually responsible:
"Hank was struck by lightning, but thanks to the doctors who worked on him, he's going to be okay.
"Lucy was attacked by a velociraptor, but thanks to the quick response of the park rangers, she only suffered minor cuts and scrapes."
"Ben was hit by a bus, but thanks to the fortunate angle at which the bus hit him, he's going to be okay."

A: There are also sub-culturally specific answers, thanking whatever omnipotent entity or idea is prominent in their defining literature.
For instance, wiccans would be likely to say "thank the goddess"; avid anime fans might say "thank kami"; a big lovecraft fan could say "thank azathoth"; a mythology lover might say "thank baal"; science fans could say "thank physics"; I even heard someone say "thank frog" once.
In other words, you can use absolutely any expression you want, and as long as it doesn't have a clear other meaning (e.g. "thank obama" might not be taken so well), people will understand it from context.

A: "Thank Goodness". It is intentionally meant to look/sound similar to "Thank God" (ie "God" vs "Goodness"), but as to explicitly not mention "God". This is an example of "minced oath"

A minced oath is a euphemistic expression formed by misspelling, mispronouncing, or replacing a part of a profane, blasphemous, or taboo term to reduce the original term's objectionable characteristics. Some examples include gosh, darn, dang, fudge and heck.

A: This are few that I like to use.
Oh my Goodness
Yes We/you did it
Oh really
Awesome
Great
Glad to hear that he is OK

A: I've always been partial to "Blessed be!", although that's been construed as religious too.


text:
Q: prove $2^{1/4}$ not in $Q(\xi)$ $\xi$ is a root of unity and $f(x)\in Q[x]$ ,prove that $f(\xi) \ne 2^{1/4}$ for all $f(x)$ and $\xi$
I know it means $2^{1/4} \notin Q(\xi)$.
If $i \in Q(\xi)$ I can prove that by considering the Galois group of $X^4 -2=0$ as it is not cyclic but generally it will not happen. Can anyone give some help ?

A: The Galois group of $\Bbb Q(\xi)/\Bbb Q$ is Abelian. If $\alpha\in
\Bbb Q(\xi)$ then $\Bbb Q(\alpha)$ is a Galois extension, with Abelian Galois group over $\Bbb Q$. But $\Bbb Q(\sqrt[4]2)$ is not Galois over $\Bbb Q$.


text:
Q: How to add a constraint where depending on your date of birth you can only borrow a certain number of books? I have the following tables:
Book (sNo)
Borrow (sNo, lNo)
Person(lNo, name, dob)
Now here I need to add a constraint the if the loaner is a certain age, they can only get so many books.
I was thinking about something that counts the lNo where the name is the same and if it is already at the limit, they cannot loan another book. But I don't know how to do this. Is there any way to do it with only constraints and not triggers?

A: No, I don't think that is possible.
If you want a solution free from race conditions, you probably have to denormalize too: Add a borrow_count to the person with an appropriate check constraint. This number is maintained by triggers on borrow.


text:
Q: I can't delete records from MySql I have two tables. table a references table b I believe.
When I try to delete the package alltogether like this:
$query="DELETE a, b FROM classified as a, $sql_table as b WHERE a.ad_id = '$id'
AND a.classified_id = b.classified_id AND a.poster_password='$pass'";

b MUST be deleted first I guess.
Even in PhpMyAdmin I cant delete a if b is still there, so I delete b first.
But what decides the order in which comes first?
The tables are alla InnoDB.
What should I do?
Thanks

A: The MySQL manual says about multi-table DELETE and foreign keys:

If you use a multiple-table DELETE
  statement involving InnoDB tables for
  which there are foreign key
  constraints, the MySQL optimizer might
  process tables in an order that
  differs from that of their
  parent/child relationship. In this
  case, the statement fails and rolls
  back. Instead, you should delete from
  a single table and rely on the ON
  DELETE capabilities that InnoDB
  provides to cause the other tables to
  be modified accordingly.

So that when a record in your main table is deleted, so are its foreign references, e.g:
ALTER TABLE products
  ADD CONSTRAINT fk_supplier
      FOREIGN KEY (supplier_id, supplier_name)
      REFERENCES supplier(supplier_id, supplier_name)
      ON DELETE CASCADE;

A: Your Delete syntax is invalid. You need to do this in two statements (unless as nuqqsa mentioned, you have CASCADE DELETE enabled on the relationship between table a and table b):
Delete From b
Where Exists    (
                Select 1
                From a
                Where a.poster_password = '$pass'
                    And a.ad_id = '$id'
                    And a.classified_id = b.classified_id
                )

Delete From a
Where a.poster_password = '$pass'
    And a.ad_id = '$id'

What decides which comes first is the foreign keys relationships. Whichever table is the parent table must be deleted from last.


text:
Q: Application.Exit() not working properly I have a separate windows form for user to select background music and it will always stay there unless the application is closed. I prevented the user from closing the music form by using the code:
private void Music_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
    }

and in my main Program.cs i run a page called login like so:
Application.Run(new Login());

I also have a FormClosed event in all my forms that closes the whole program after pressing the cross
private void Login_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

However, after i add the code that the user is not able to close the music form, my application is only able to exit by pressing the cross when it is in the login page, which is the start of the program ran by the main page (the application used to be able to exit in all of my forms by pressing the cross)
I want to know if there is any way for me to properly exit my application or a way to make user not able to close the music form without affecting my other form's closing. Thank you

A: The code inside Music_FormClosing is preventing your application from exiting. To get the desired behavior (prevent the user closing the music form), you can utilize the FormClosingEventArgs CloseReason property:
private void Music_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
        e.Cancel = true;
}


text:
Q: Pyplot figsize attribute values resize plot for Series but not dataframe with subplots = True Here are two plots:
One plot is a pandas series (ao). The code resizes the plot using pyplot. The second plot (aonao), is a pandas dataframe combining AO and NAO series.The code sets subplots attribure to 'True' and uses the same figsize dimensions, however the dataframe does not resize? Here's the graphic from jupyter notebook. Not sure of this is notebook issue or a pyplot issue? Any thoughts?

A: To create subplots (in aonao) with subplots=True, pandas needs to create a new figure and ignores your previous figure creation. You have to pass the figsize to the plot() function.
aonao.plot(subplots=True, figsize=(15,6))


text:
Q: Estimating the number of tokens in a pile We have a pile of tokens numbered from $1$ to $n$, where $n$ is unknown. $k$ tokens are drawn from the pile  at random without replacement(i.e. the numbers that we get from tokens are unique). Say the number written on the tokens are $a_1,\  \dots, a_k$ what is the best estimation for $n$ that you can give.
I remember our teacher said that if the tokens were drawn with replacement, then the MLE estimation of $n$ would be $\max_i a_i$. But in the other case(drawn without replacement), the number must be reported larger than the maximum with respect to $k$(i.e. for smaller $k$-s we would report $c\max$ rather than $\max$ where $c$ shrinks as $k$ grows). But now that I check MLE for this case (i.e. the $n$ that maximizes $\frac{\binom{m-1}{k-1}}{\binom{n}{k}}$) is also $\max_i a_i$. Am I doing it wrong? Or can someone give a mathematical way of explaining the constant $c$ which where $c\max$ is reported?(The intuition is fine)