Q:

Get currentuserinfo firstname and lastname

I am trying to insert the user firstname and last name into the database whilst processing a woocommerce order. I have managed to get two empty fields into the database where I need them however i am struggling to get the users first name and last name to post. Below is the code i have so far, would someone be able to point me in the right direction?
// add user firstname
    if ( ! $order_data['user_firstname'] ) {
        if ( is_user_logged_in() ) {
            $order_data['user_firstname'] = get_currentuserinfo($current_user->user_firstname);
        } else {
            $order_data['user_firstname'] = 0;
        }
    }

    // add user surname
    if ( ! $order_data['user_surname'] ) {
        if ( is_user_logged_in() ) {
            $order_data['user_surname'] = get_currentuserinfo($current_user->user_lastname);
        } else {
            $order_data['user_surname'] = 0;
        }
    }

This is the complete contents of the file. Everything works apart from populating first name and last name
/**
* Main model class for all bookings, this handles all the data
*/
class WC_Booking {

    /** @public int */
    public $id;

    /** @public string */
    public $booking_date;

    /** @public string */
    public $start;

    /** @public string */
    public $end;

    /** @public bool */
    public $all_day;

    /** @public string */
    public $modified_date;

    /** @public object */
    public $post;

    /** @public int */
    public $product_id;

    /** @public object */
    public $product;

    /** @public int */
    public $order_id;

    /** @public object */
    public $order;

    /** @public int */
    public $customer_id;

    /** @public string */
    public $status;

    /** @public array - contains all post meta values for this booking */
    public $custom_fields;

    /** @public bool */
    public $populated;

    /** @private array - used to temporarily hold order data for new bookings */
    private $order_data;

    /**
     * Constructor, possibly sets up with post or id belonging to existing booking
     * or supplied with an array to construct a new booking
     * @param int/array/obj $booking_data
     */
    public function __construct( $booking_data = false ) {
        $populated = false;

        if ( is_array( $booking_data ) ) {
            $this->order_data = $booking_data;
            $populated = false;
        } else if ( is_int( intval( $booking_data ) ) && 0 < $booking_data ) {
            $populated = $this->populate_data( $booking_data );
        } else if ( is_object( $booking_data ) && isset( $booking_data->ID ) ) {
            $this->post = $booking_data;
            $populated = $this->populate_data( $booking_data->ID );
        }

        $this->populated = $populated;
    }

    /**
     * Actual create for the new booking belonging to an order
     * @param string Status for new order
     */
    public function create( $status = 'unpaid' ) {
        $this->new_booking( $status, $this->order_data );
        $this->schedule_events();
    }

    /**
     * Schedule events for this booking
     */
    public function schedule_events() {
        switch ( get_post_status( $this->id ) ) {
            case "paid" :
                if ( $this->start ) {
                    wp_schedule_single_event( strtotime( '-' . absint( apply_filters( 'woocommerce_bookings_remind_before_days', 1 ) ) . ' day', $this->start ), 'wc-booking-reminder', array( $this->id ) );
                }
                if ( $this->end ) {
                    wp_schedule_single_event( $this->end, 'wc-booking-complete', array( $this->id ) );
                }
            break;
            default :
                wp_clear_scheduled_hook( 'wc-booking-reminder', array( $this->id ) );
                wp_clear_scheduled_hook( 'wc-booking-complete', array( $this->id ) );
            break;
        }
    }

    /**
     * Makes the new booking belonging to an order
     * @param string $status The status for this new booking
     * @param array $order_data Array with all the new order data
     */
    private function new_booking( $status, $order_data ) {
        global $wpdb;

        $order_data = wp_parse_args( $order_data, array(
            'user_id'           => 0,
            'resource_id'       => '',
            'product_id'        => '',
            'order_item_id'     => '',
            'persons'           => array(),
            'cost'              => '',
            'start_date'        => '',
            'end_date'          => '',
            'all_day'           => 0,
            'parent_id'         => 0,
        ) );

        // Get parent data
        if ( $order_data['parent_id'] ) {
            if ( ! $order_data['order_item_id'] )
                $order_data['order_item_id'] = get_post_meta( $order_data['parent_id'], '_booking_order_item_id', true );

            if ( ! $order_data['user_id'] )
                $order_data['user_id'] = get_post_meta( $order_data['parent_id'], '_booking_customer_id', true );
        }

        // Get order ID from order item
        if ( $order_data['order_item_id'] )
            $order_id = $wpdb->get_var( $wpdb->prepare( "SELECT order_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_id = %d", $order_data['order_item_id'] ) );
        else
            $order_id = 0;

        $booking_data = array(
            'post_type'   => 'wc_booking',
            'post_title'  => sprintf( __( 'Booking – %s', 'woocommerce-bookings' ), strftime( _x( '%b %d, %Y @ %I:%M %p', 'Booking date parsed by strftime', 'woocommerce-bookings' ) ) ),
            'post_status' => $status,
            'ping_status' => 'closed',
            'post_parent' => $order_id
        );

        $this->id = wp_insert_post( $booking_data );

        // Setup the required data for the current user
        if ( ! $order_data['user_id'] ) {
            if ( is_user_logged_in() ) {
                $order_data['user_id'] = get_current_user_id();
            } else {
                $order_data['user_id'] = 0;
            }
        }

    $user_info = wp_get_current_user();

if ( is_user_logged_in() ) {
    $order_data['user_firstname'] = $user_info->user_firstname;
    // add user surname
    $order_data['user_surname'] = $user_info->user_lastname;
}

        // Convert booking start and end to requried format
        if ( is_numeric( $order_data['start_date'] ) ) {
            // Convert timestamp
            $order_data['start_date'] = date( 'YmdHis', $order_data['start_date'] );
            $order_data['end_date']   = date( 'YmdHis', $order_data['end_date'] );
        } else {
            $order_data['start_date'] = date( 'YmdHis', strtotime( $order_data['start_date'] ) );
            $order_data['end_date']   = date( 'YmdHis', strtotime( $order_data['end_date'] ) );
        }

        $meta_args = array(
            '_booking_order_item_id' => $order_data['order_item_id'],
            '_booking_product_id'    => $order_data['product_id'],
            '_booking_resource_id'   => $order_data['resource_id'],
            '_booking_persons'       => $order_data['persons'],
            '_booking_cost'          => $order_data['cost'],
            '_booking_start'         => $order_data['start_date'],
            '_booking_end'           => $order_data['end_date'],
            '_booking_all_day'       => intval( $order_data['all_day'] ),
            '_booking_parent_id'     => $order_data['parent_id'],
            '_booking_customer_id'   => $order_data['user_id'],
            // hp extras
            '_booking_customer_firstname'   => $order_data['user_firstname'],
            '_booking_customer_surname'   => $order_data['user_surname'],
        );

        foreach ( $meta_args as $key => $value ) {
            update_post_meta( $this->id, $key, $value );
        }

        do_action( 'woocommerce_new_booking', $this->id );
    }

    /**
     * Populate the data with the id of the booking provided
     * Will query for the post belonging to this booking and store it
     * @param int $booking_id
     */
    public function populate_data( $booking_id ) {
        if ( ! isset( $this->post ) ) {
            $post = get_post( $booking_id );
        }

        if ( is_object( $post ) ) {
            // We have the post object belonging to this booking, now let's populate
            $this->id            = $post->ID;
            $this->booking_date  = $post->post_date;
            $this->modified_date = $post->post_modified;
            $this->customer_id   = $post->post_author;
            $this->custom_fields = get_post_meta( $this->id );
            $this->status        = $post->post_status;
            $this->order_id      = $post->post_parent;

            // Define the data we're going to load: Key => Default value
            $load_data = array(
                'product_id'  => '',
                'resource_id' => '',
                'persons'     => array(),
                'cost'        => '',
                'start'       => '',
                'customer_id' => '',
                'end'         => '',
                'all_day'     => 0,
                'parent_id'   => 0,
                'user_firstname' => '',
                'user_surname' => '',

            );

            // Load the data from the custom fields (with prefix for this plugin)
            $meta_prefix = '_booking_';

            foreach ( $load_data as $key => $default ) {
                if ( isset( $this->custom_fields[ $meta_prefix . $key ][0] ) && $this->custom_fields[ $meta_prefix . $key ][0] !== '' ) {
                    $this->$key = maybe_unserialize( $this->custom_fields[ $meta_prefix . $key ][0] );
                } else {
                    $this->$key = $default;
                }
            }

            // Start and end date converted to timestamp
            $this->start = strtotime( $this->start );
            $this->end   = strtotime( $this->end );

            // Save the post object itself for future reference
            $this->post = $post;
            return true;
        }

        return false;
    }

    /**
     * Will change the booking status once the order is paid for
     * @return bool
     */
    public function paid() {
        $current_status = $this->status;

        if ( $this->populated && in_array( $current_status, array( 'unpaid', 'confirmed' ) ) ) {
            $this->update_status( 'paid' );
            return true;
        }

        return false;
    }

    /**
     * Set the new status for this booking
     * @param string $status
     * @return bool
     */
    public function update_status( $status ) {
        $current_status   = $this->get_status( true );
        $allowed_statuses = array( 'unpaid', 'pending', 'confirmed', 'paid', 'cancelled', 'complete' );

        if ( $this->populated ) {
            if ( in_array( $status, $allowed_statuses ) ) {
                wp_update_post( array( 'ID' => $this->id, 'post_status' => $status ) );

                // Reschedule cron
                $this->schedule_events();

                // Trigger actions
                do_action( 'woocommerce_booking_' . $current_status . '_to_' . $status, $this->id );
                do_action( 'woocommerce_booking_' . $status, $this->id );

                return true;
            }
        }

        return false;
    }

    /**
     * Returns the status of this booking
     * @param Bool to ask for pretty status name (if false)
     * @return String of the booking status
     */
    public function get_status( $raw = true ) {
        if ( $this->populated ) {
            if ( $raw ) {
                return $this->status;
            } else {
                $status_object = get_post_status_object( $this->status );
                return $status_object->label;
            }
        }

        return false;
    }

    /**
     * Returns the id of this booking
     * @return Id of the booking or false if booking is not populated
     */
    public function get_id() {
        if ( $this->populated ) {
            return $this->id;
        }

        return false;
    }

    /**
     * Get the product ID for the booking
     * @return int or false if booking is not populated
     */
    public function get_product_id() {
        if ( $this->populated ) {
            return $this->product_id;
        }

        return false;
    }

    /**
     * Returns the object of the order corresponding to this booking
     * @return Product object or false if booking is not populated
     */
    public function get_product() {
        if ( ! isset( $this->product ) || empty( $this->product ) ) {
            if ( $this->populated && $this->product_id ) {
                $this->product = get_product( $this->product_id );
            } else {
                return false;
            }
        }

        return $this->product;
    }

    /**
     * Returns the object of the order corresponding to this booking
     * @return Order object or false if booking is not populated
     */
    public function get_order() {
        if ( empty( $this->order ) ) {
            if ( $this->populated && ! empty( $this->order_id ) && 'shop_order' === get_post_type( $this->order_id ) ) {
                $this->order = new WC_Order( $this->order_id );
            } else {
                return false;
            }
        }

        return $this->order;
    }

    /**
     * Return if all day event
     * @return boolean
     */
    public function is_all_day() {
        if ( $this->populated ) {
            if ( $this->all_day ) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * See if this booking is booked on said date
     * @return boolean
     */
    public function is_booked_on_day( $block_start, $block_end ) {
        if ( $this->populated ) {
            $loop_date        = $this->start;
            $multiday_booking = date( 'Y-m-d', $this->start ) < date( 'Y-m-d', $this->end );

            if ( $multiday_booking ) {
                if ( date( 'YmdHi', $block_end ) > date( 'YmdHi', $this->start ) || date( 'YmdHi', $block_start ) < date( 'YmdHi', $this->end ) ) {
                    return true;
                }
                return false;
            }

            while ( $loop_date <= $this->end ) {
                if ( date( 'Y-m-d', $loop_date ) === date( 'Y-m-d', $block_start ) ) {
                    return true;
                }
                $loop_date = strtotime( "+1 day", $loop_date );
            }
        }
        return false;
    }

    /**
     * Returns booking start date
     * @return string Date formatted via date_i18n
     */
    public function get_start_date( $date_format = null, $time_format = null ) {
        if ( $this->populated && ! empty( $this->start ) ) {
            if ( is_null( $date_format ) ) {
                $date_format = apply_filters( 'woocommerce_bookings_date_format', 'M jS Y' );
            }
            if ( is_null( $time_format ) ) {
                $time_format = apply_filters( 'woocommerce_bookings_time_format', ', g:ia' );
            }
            if ( $this->is_all_day() ) {
                return date_i18n( $date_format, $this->start );
            } else {
                return date_i18n( $date_format . $time_format, $this->start );
            }
        }

        return false;
    }

    /**
     * Returns booking end date
     * @return string Date formatted via date_i18n
     */
    public function get_end_date( $date_format = null, $time_format = null ) {
        if ( $this->populated && ! empty( $this->end ) ) {
            if ( is_null( $date_format ) ) {
                $date_format = apply_filters( 'woocommerce_bookings_date_format', 'M jS Y' );
            }
            if ( is_null( $time_format ) ) {
                $time_format = apply_filters( 'woocommerce_bookings_time_format', ', g:ia' );
            }
            if ( $this->is_all_day() ) {
                return date_i18n( $date_format, $this->end );
            } else {
                return date_i18n( $date_format . $time_format, $this->end );
            }
        }

        return false;
    }

    /**
     * Returns information about the customer of this order
     * @return array containing customer information
     */
    public function get_customer() {
        if ( $this->populated ) {
            $order = $this->get_order();

            if ( $order )
                return (object) array(
                    'name'    => trim( $order->billing_first_name . ' ' . $order->billing_last_name ),
                    'email'   => $order->billing_email,
                    'user_id' => $order->customer_user,
                );
            elseif ( $this->customer_id ) {
                $user = get_user_by( 'id', $this->customer_id );

                return (object) array(
                    'name'    => $user->display_name,
                    'email'   => $user->user_email,
                    'user_id' => $this->customer_id
                );
            }
        }

        return false;
    }

    /**
     * Returns if persons are enabled/needed for the booking product
     * @return boolean
     */
    public function has_persons() {
        return $this->get_product()->has_persons();
    }

    /**
     * Returns if resources are enabled/needed for the booking product
     * @return boolean
     */
    public function has_resources() {
        return $this->get_product()->has_resources();
    }

    /**
     * Return a array with the booking persons.
     * @return array
     */
    public function get_persons() {
        return (array) $this->persons;
    }

    /**
     * Return the amount of persons for this booking.
     * @return int
     */
    public function get_persons_total() {
        return array_sum( $this->get_persons() );
    }

    /**
     * Get the resource id
     * @return int
     */
    public function get_resource_id() {
        return absint( $this->resource_id );
    }

    /**
     * Get the resource/type for this booking if applicable.
     * @return bool|object WP_Post
     */
    public function get_resource() {
        $resource_id = $this->get_resource_id();

        if ( ! $resource_id || ! $this->get_product() )
            return false;

        return $this->get_product()->get_resource( $resource_id );
    }
}

A:

You are using get_currentuserinfo in a wrong way because you are passing parameters that this functions doesn't accept and you expect that the functions return directly what you want. get_currentuserinfo doesn't accept any parameter, returns a WP User object and require the global $current_user var.
Anyway, I prefer to use wp_get_current_user() in order to avoid working directly with globals:
$user_info = wp_get_current_user();

if ( ! $order_data['user_firstname'] ) {
    if ( is_user_logged_in() ) {
        $order_data['user_firstname'] = $user_info->user_firstname;
    } else {
        $order_data['user_firstname'] = 0;
    }
}

// add user surname
if ( ! $order_data['user_surname'] ) {
    if ( is_user_logged_in() ) {
        $order_data['user_surname'] = $user_info->user_lastname;
    } else {
        $order_data['user_surname'] = 0;
    }
}

And in your code, you are populating the array $order_data with default values for each key. After that, you check, for example, if ( ! $order_data['user_surname'] ); because $order_data['user_surname'] was filled with default values, all the code inside that if statement won't be executed. You should leave the code in this way (default values was already set, so it will modified only for logged in users):
if ( is_user_logged_in() ) {

    $user_info = wp_get_current_user();

    $order_data['user_firstname'] = $user_info->user_firstname;
    // add user surname
    $order_data['user_surname'] = $user_info->user_lastname;

}

You still say that the oly thing is not working is the name and last name. But you can verify yourself that it is working:
if ( is_user_logged_in() ) {

    $user_info = wp_get_current_user();

    $order_data['user_firstname'] = $user_info->user_firstname;
    // add user surname
    $order_data['user_surname'] = $user_info->user_lastname;

}
var_dump($order_data);

You will see how de dump data inludes the name and lastname if you are logged in. Please, debug the $order_data.


Q:

Write a function with default column name inputs in dplyr::mutate()

I am trying to write a function to calculate a new column in a data frame.  I want the function to have default column names as inputs, and to be able to be called from within dplyr::mutate().
Here's a simplified example, where I am using a column called age to calculated a rounded age.
library(dplyr)
# function to round age WITH DEFAULT vector/column to round
round_age <- function(age = age) {
  round(age)
}

# create dummy data
data = data.frame(age = c(50.1, 60.5))

# try to use default age column - ERROR
data %>%
  mutate(
    age_round = round_age()
  )
#> Error in mutate_impl(.data, dots): Evaluation error: non-numeric argument to mathematical function.

# specify age column to round - NO ERROR
data %>%
  mutate(
    age_round = round_age(age = age)
  )
#>    age pat_age age_round
#> 1 50.1    50.1        50
#> 2 60.5    60.5        60

I want to be able to call the function from within dplyr::mutate without specifying the data frame. Any ideas? All tips greatly appreciated!
Thank you!
Daniel

A:

We can write a function called round_x() that wraps around mutate() and has age as a default argument:
library(dplyr)

round_x <- function(.data, x = age) {
  x <- enquo(x)
  var_name <- paste0("round_", quo_name(x))
  mutate(.data, !!var_name := round(!!x))
}

If we call this function with no arguments:
data %>% round_x()
#   age round_age
#1 50.1        50
#2 60.5        60

We could pass other arguments if we wanted to:
data.frame(data, weight = c(180.5, 200.6)) %>% round_x(weight)
#   age weight round_weight
#1 50.1  180.5          180
#2 60.5  200.6          201


Q:

Get the data of particular area with given miles

I want to calculate the Listings that is near to  city with given miles. Suppose I have one area xyzArea and in this area i have particular latitude and longitude also and in some distance of 1 miles there is 5 more listings. I want to get that 5 listings. when user click on 1 miles. can anyone help me how to achieve this functionality. Any helpful link must commented. I am using laravel 5.2 framework Thanks in advance :)

A:

SELECT
    id,
    (
        6371 *
        acos(
            cos( radians( :lat ) ) *
            cos( radians( lat ) ) *
            cos(
                radians( long ) - radians( :long )
            ) +
            sin(radians(:lat)) *
            sin(radians(lat))
        )
    ) distance
FROM
    location
HAVING
    distance < :distance
ORDER BY
    distance
LIMIT
    25
Hope that helps you
Thanks


Q:

cannot connect to database sql server on another pc from java app

I'm new to java and cannot connect to database sql server on another pc
I tried
public class ConnectDB {

        public Connection connect() {
            Connection cn = null;

            try{
                Class.forName("net.sourceforge.jtds.jdbc.Driver");

                cn = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.1/HR;instance=MSSQLSERVER", "sa", "pass");

                //cn = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.1/HR:1433;instance=MSSQLSERVER", "sa", "pass");
                //cn = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.1;instance=MSSQLSERVER;databaseName=HR", "sa", "pass");

            }catch(ClassNotFoundException | SQLException e){

                System.out.println("Error: " + e.getMessage() );

            } return cn;
        }
    }

and got Network error IOException: Connection timed out: connect
TCP/IP is enabled and when i ping on cmd no late occur
please anyone can help me.

A:

Did you open the remote access on your database?
http://www.sophos.com/fr-fr/support/knowledgebase/118473.aspx


Q:

Get codepoint for a matched character

I want to replace the characters in the range from U+00C0 to U+02AF by their codepoint  with \u… e.g. á -> \u00E1. Is there any sed function for getting the codepoint number for a matched character?

A:

There's no such function in sed. Perl to the rescue:
perl -i~ -CD -pe 's/([\x{c0}-\x{2af}])/sprintf "\\u%04X", ord $1/ge' file.txt

(Works for the input in UTF-8.)
Explanation:

-i~ tells Perl to replace the file in place, leaving a backup.
-CD  tells Perl to assume UTF-8 on input and output.
-p tells perl to process the input line by line, like sed.
s///g is global substitution, like in sed.
the /e option means the replacement should be evaluated, i.e. it's not a string but code whose returned value is used to replace the matching part. The code here takes the ord of the char, i.e. its code, and uses printf to convert it to hex.


Q:

node.js game CPU usage

My friend and I are making a node.js game, and we have been testing CPU. After profiling, it was determined that this process called zlib is sucking most of the CPU/RAM.
3 clients connected to a game is fine, but when 12~13 players are connected it uses 58% where zlib is using about 30% of this CPU.

inclusive      self           name
ticks   total  ticks   total
64775   58.5%  64775   58.5%  /lib/x86_64-linux-gnu/libc-2.19.so
25001   22.6%    224    0.2%  LazyCompile: *callback zlib.js:409
//this one is a different zlib
7435    6.7%     82    0.1%  LazyCompile: ~callback zlib.js:409

Is there any way to decrease the CPU usage from this? Or is there a reason why it is increasing so much?
I have done some reading and I am told it is from socket.io, so here is our section of socket sending most of the data:
for (var i = 0; i < users.length; i++) {
    if (u.room == users[i].room && users[i].x + users[i].radius >= u.x - u.screenWidth / 2 - 20 && users[i].x - users[i].radius <= u.x + u.screenWidth / 2 + 20 && users[i].y + users[i].radius >= u.y - u.screenHeight / 2 - 20 && users[i].y - users[i].radius <= u.y + u.screenHeight / 2 + 20) {
        if (users[i].id == u.id) {
            visiblePlayers.push({
                x: users[i].x,
                y: users[i].y,
                angle: users[i].angle,
                hue: users[i].hue,
                radius: users[i].radius,
                squeeze: users[i].squeeze,
                name: users[i].name,
                dead: users[i].dead,
                isPlayer: true,
                kills: users[i].kills
            });
        } else {
            visiblePlayers.push({
                x: users[i].x,
                y: users[i].y,
                angle: users[i].angle,
                hue: users[i].hue,
                radius: users[i].radius,
                squeeze: users[i].squeeze,
                name: users[i].name,
                dead: users[i].dead
            });
        }
        // SEND DYING INFO: (FOR OFFLINE ANIMATION):
        if (users[i].dying) {
            visiblePlayers[visiblePlayers.length - 1].dying = true;
        }
    }
}
var visibleEnergy = [];
for (var i = 0; i < energies.length; i++) {
    if (u.firstSend || (energies[i].updated && energies[i].room == u.room)) {
        var anim = energies[i].animate;
        if (u.firstSend)
            anim = true;
        visibleEnergy.push({
            x: energies[i].x,
            y: energies[i].y,
            radius: energies[i].radius,
            index: i,
            animate: anim,
            hue: energies[i].hue,
            room: energies[i].room
        });
    }
}

// SEND PLAYER UPDATES TO CLIENTS:
sockets[u.id].emit('serverTellPlayerMove', visiblePlayers,
    visibleEnergy);

A:

As I wrote in a comment, changing the code here won't change zlib usage, as that's something that's happening at a lower level. Still, I wanted to review the code. However, as TastyLemons rightfully notes in a comment, if you can simply send less stuff all the time, it'll help. But with that much CPU usage for zlib, I'm guessing there's something wonky in the node/zlib/server configuration.
For the first loop (users loop):

That is a very long and complex if condition! And it's filled with magic numbers, as well as numbers that I assume you don't need to calculate over and over again.
The object you're building is mostly the same in both the inner branches, so it'd be easier to build the common part first, and then only add the parts that differ.
There are other small changes that would make things simpler, like setting the dying boolean in the object before pushing it to the array.
You can make good use of the map and filter array methods

For the condition, you're checking if the user is in the same room, and in view of the u user (Sidenote: u is not a terribly descriptive label, and it doesn't help that you sometimes use player and other times use user to refer to the same kind of entity).
I'd make that a method, for instance on the User prototype, if you have such a thing:
User.prototype.canSee = function (otherUser) {
  // initial check
  if(this.room !== otherUser.room) {
    return false;
  }

  // x and y distances between user and other's "radius"
  var dx = Math.abs(otherUser.x - this.x) - otherUser.radius,
      dy = Math.abs(otherUser.y - this.y) - otherUser.radius;

  return dx <= this.xViewDistance && dx <= this.yViewDistance;
};

(if you don't have a User prototype, you can change the function to be a plain function that takes two arguments.)
I'm assuming here, that the *ViewDistance values are already calculated, since I imagine they don't really change (or at least don't change all the time). So if the screenWidth doesn't change much, you could calculate a screenHalfWidth and keep it around, so you don't always have to divide by 2 to get the same result. And the 20 needs to be a needs constant (I know JS doesn't have constants; I mean a variable you treat as constant). Something like SCREEN_WIDTH_MARGIN and maybe a similar thing for height.
So xViewDistance might be defined as user.screenHalfWidth - SCREEN_WIDTH_MARGIN, which itself is a value that probably won't change all the time, and can thus be stored.
Point is, you end up with code, where:

your magic numbers are labelled so you know what they mean
your magic numbers are defined in exactly 1 place, so you only need to hunt down the same number in 23 different places if it needs to change
calculations are done once, and the results stored, rather than recalculated constantly despite not having changed.

For building the objects I'd again suggest a method on the User prototype (though again, it can also be a function that just takes an argument). Something like:
User.prototype.getInfo = function (isPlayer) {
  var info = {
    x: this.x,
    y: this.y,
    angle: this.angle,
    hue: this.hue,
    radius: this.radius,
    squeeze: this.squeeze,
    name: this.name,
    dead: this.dead,
    dying: this.dying
  };

  if(isPlayer) {
    info.isPlayer = true;
    info.kills = this.kills;
  }

  return info;
};

Putting it together, you might get:
var visibleUsers = users.filter(function (user) {
  return user.id === currentUser.id || currentUser.canSee(user);
}).map(function (user) {
  return user.getInfo(user.id === currentUser.id);
});

That's everyone's info, including the current user/the player, ready to be sent.
For the energies, the story's similar: Add some methods/functions to do the heavy lifting, and use filter/map to iterate the array. Only trick is that if firstSend is true, we could really skip the filter function, but I've left it pretty much as-is:
var visibleEnergies = energies.filter(function (energy) {
  return currentUser.firstSend || (energy.updated && energy.room === currentUser.room);
}).map(function (energy) {
  var info = energy.getInfo();
  info.anim = info.anim || currentUser.firstSend; // override anim if necessary
  return info;
});


Q:

IF EXISTS block

I have 2 tables UserSession and Sale.
Table User has 4 columns, namely UserID, UserSessionID, SessionOpenDate and SessionCloseDate.
Table Sale has 2 columns, which are price, cost, userID and CompletedDate.
When a user logs in, a new row is created in the User table, where the user's login timestamp will be saved in the SessionOpenDate and a new UserSessionID will be assigned to the session. When the user logs off, the log off timestamp will be be saved in SessionCloseDate.
When the user is still logged in, the user can make some sale and the sale information is saved in the Sale table. The timestamp when the sale is finalized in saved in CompletedDate column.
For some reason, I need to get the all sales done in a certain UserSessionID where the CompletedDate must be within the SessionOpenDate and SessionCloseDate. However, if the user has not logged off yet, which means that the value in SessionCloseDate is null, the CompletedDate  should be between SessionOpenDate and now.
Here's my query:
SELECT SUM(s.cost) AS Cost, SUM(s.price) AS Price
FROM Sale AS s
  INNER JOIN UserSession AS u
  ON s.userID = u.userID
WHERE
  (s.CompletedDate >=
    ( SELECT SessionOpenDate
      FROM UserSession
      WHERE (UserSessionID = u.UserSessionID)
)
  )
  AND
  (s.CompletedDate <
    (
      IF EXISTS
       (
         SELECT SessionCloseDate AS closeTime
         FROM UserSession AS UserSessionTemp
         WHERE (UserSessionID = u.UserSessionID)
       )
       BEGIN
         SET closeTime = SELECT CURRENT_TIMESTAMP
       END
    )
  )
  AND u.UserSessionID IN (1)

However, Sql Server says Incorrect syntax near the keyword 'IF'. and Incorrect syntax near ')'.
Can anyone tell me what went wrong with my IF block?
Thanks

A:

You can't use an IF block inside a SELECT statement. Also, I don't know what you're really trying to accomplish with SET, since closeTime is not a variable/parameter.
You can use IIF in SQL Server 2012 (syntactical sugar for CASE WHEN <condition> THEN <true_value> ELSE <false_value> END - use this syntax for earlier versions):
IIF(EXISTS
   (
     SELECT SessionCloseDate AS closeTime
     FROM UserSession AS UserSessionTemp
     WHERE (UserSessionID = u.UserSessionID)
   ), (
     SELECT SessionCloseDate AS closeTime
     FROM UserSession AS UserSessionTemp
     WHERE (UserSessionID = u.UserSessionID)
   ),
     CURRENT_TIMESTAMP
)

Honestly, without getting too complicated, here's what I would do instead:
SELECT SUM(s.cost) AS Cost, SUM(s.price) AS Price
FROM userSession AS u
INNER JOIN Sale AS s ON u.userID = s.userID
WHERE u.UserSessionID = @UserSessionId
AND s.CompletedDate >= u.SessionOpenDate
AND (u.SessionCloseDate IS NULL OR s.CompletedDate < u.SessionCloseDate)

Or,
SELECT SUM(s.cost) AS Cost, SUM(s.price) AS Price
FROM userSession AS u
INNER JOIN Sale AS s ON u.userID = s.userID
WHERE u.UserSessionID = @UserSessionId
AND s.CompletedDate BETWEEN u.SessionOpenDate
                    AND COALESCE(u.SessionCloseDate, '12/31/9999 23:59:59.9999')


Q:

SQL - delete row if another table exists

I'm trying to delete a row from a table if another table doesn't exist. I've tried using the following statement
 IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'user3project3'))
 BEGIN
     DELETE FROM user1table WHERE id=3
 END

However I get the following error:
 Unrecognized statement type. (near "IF" at position 0)

I'm using phpMyAdmin with XAMPP, if that matters.
Thanks a lot in advance!

A:

The IF statement is only allowed in programming blocks, which in practice means in stored procedures, functions, and triggers.
You could express this logic in a single query:
DELETE FROM user1table
    WHERE id = 3 AND
          NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'user3project3');

That said, you have a very questionable data model if you are storing a separate table for each user.


Q:

Java generics & incompatible types using

abstract class AbsClass {}

class MyAbs extends AbsClass {}

class MyClass<S extends AbsClass> {
    S getObj() {
        return new MyAbs();
    }
}

Getting compiler issue:

Error:(33, 16) java: incompatible types: MyAbs cannot be converted to S

What is the correct way to do this?
Edit:
I was hoping to be able to intialize MyClass{MyAbs} then call getObj() which would return me a MyAbs object. With Andy's answer, I would have to cast the AbsClass to MyAbs or MySecondAbs which was what I was trying to avoid

A:

Andy has described how to fix the problem, I'll try to explain why.
S is not guaranteed to be assignable to MyAbs, only to AbsClass, and each instance will specify a subclass of AbsClass.
Consider:
class MyOtherAbs extends AbsClass {}

MyClass myClass = new MyClass<MyOtherAbsClass>{};

This would conflict with what you have.
UPDATE:
Based on your comments it looks like you want to achieve the above.  The challenge is what if MyOtherAbs has a constructor with arguments?  Or is implemented as a Singleton (i.e. a private constructor and static getInstance()).  In short, there is no guaranteed unified way you can construct these.  Further, due to type erasure, at runtime, the concept of S is gone, so you cannot do something like:
return new S();

You basically have two alternatives, one is to use subclassing:
public interface AbsClassFactory<S extends AbsClass>{ //takes the place of MyClass
    public S getInstance();
}

MyAbsFactory implements AbsClassFactory<MyAbs>{
    public MyAbs getInstance(){
        return new MyAbs(); //or however MyAbs is instantiated
    }
}

The other option is reflection:
class MyClass {
    public <S extends AbsClass> S getObj(Class<S> clazz) throws InstantiationException, IllegalAccessException {
        return clazz.newInstance();
    }
}

Note that the second assumes there is a no arg constructor available and will throw a runtime exception if one is not.

A:

S extends MyAbs, not the other way around. any object of type S can be cast into MyAbs, but MyAbs cannot be cast into it's derived classes.
Please explain what you are trying to achieve.


Q:

Why is this true for any x and y where x and y are whole numbers?

$x,y,z ∈ Z$
$∀x∀y∃z((x < z) ⇒ (x ≥ y))$
We know that to prove it wrong, we just have to find a counterexample. That means we have to find $T⇒F$. If we have: $x=2$. Sure, there exists a z that is larger than x. But why is it given that x also then is larger than or equals to y? Can't we just set $z=5, y=1$ and have a counterexample?

A:

your proposition is equivalent to
$\forall (x,y)\in \mathbb Z^2$ there exists $z\in \mathbb Z$ such that
$x\geq z$ or $x\geq y$.
It is always true if we take $z=x-1$.


Q:

How to calculate exchange rate with python script

A bank has the following exchange rates: 83.5 ($ to tzsh), 86.8 (tzsh to $). A customer wants to repeatedly exchange 1,000 dollars back and forth from dollars to shillings and vice versa. Develop a simple program (in any language) to show after how many exchanges the customer ends up with zero.
I am new at Python and I am sure there is something wrong with my code:
x=0
y=1000
while x<1000:
    x=(83.5*y)/86.8
    print x
    y=x

A:

The problem is it only approaches but never actually reaches 0. So, you might want to either set it less than 1 or check when it's really really close to 0 depending on your requirement.
balance = 1000
transactions = 0

while balance > 1:
    shillings = balance * 83.5
    balance = shillings / 86.8
    transactions += 1
print(transactions, balance)

Output:
179 0.9701710363275966

So on transaction number 179, the balance becomes less than $1.
If you want to count conversion from $ to shillings and back as two transactions, instead of transactions += 1, use transactions += 2

A:

My answer is going to deviate from Ashish's answer because he considers the exchange from $ to tzsh and tzsh to $ as 1 transaction, while my approach considers $-to-tzsh and tzsh-to-$ as separate transactions:
i = 0
currency = 1000
while currency > 1:
    if i % 2 == 0:  # if converting from $ to tzsh
        currency = 83.5 * currency
    else:  # if converting from tzsh to $
        currency = currency / 86.8
    i += 1
print(i)

Result:
358


Q:

jQuery.html() returns invalid IMG

Possible Duplicates:
Jquery html() and self closing tags
Is it expected that jQuery $('span').html() turns XHTML br tag to html syntax?

I have a document like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

I want to retrive html for some nodes to do something. But I see one problem with IMG.
$('#content').html();

This returns invalid XHTML

jQuery version is 1.4.2.

A:

This is a duplicate, but none of the answers in the original question gives an actual  workaround. (Probably rightly so. I can't but agree with what @Cletus says in his - as always excellent - answer.)
But if you're stuck with XHTML: there is a jQuery plugin providing a innerXHTML() function (poorly maintained though, last updated 2007, and never made it from Beta) and a JavaScript tool named innerXHTML that promises to do what you need. If you need this, that may be your best bet.

A:

innerHTML/html() won't give you an XHTML serialisation unless you've actually served the page as XHTML, under the application/xhtml+xml media type. (And that doesn't work on IE<9.) If you are serving your page as text/html, then your self-closing tags are nothing but ignored clutter to the browser when it's parsing your source into a DOM. You cannot expect to get the same format HTML out of the DOM serialised from that as you put in.
In fact in some cases in IE innerHTML won't even give you a valid HTML serialisation: it omits quotes around attr in some cases where it shouldn't. In short, you cannot rely on innerHTML giving you any particular format of markup. It might re-order attributes, it might HTML-escape different characters, it might normalise attribute values, it might change whitespace. So doing string operations on the html() return value is a non-starter. All you can rely on is that you can assign the serialised markup back to the innerHTML of another element and the browser will be able to parse it.
What's your purpose in trying to retrieve XHTML? You may be able to achieve more using normal DOM-style manipulations.
ETA re comment:
Then XHTML validity is the least of your worries. It doesn't matter if the HTML isn't well-formed, you will still be able to write it back to html(). But:
What you can't reliably do with the html() is tell what sentences are in text content and what are in attribute values. For example  is markup and if you start putting s inside the title attribute, you're obviously going to have difficulties.
This is a text-processing task, so you should do it on text nodes, not markup. This is a bit tricky and jQuery doesn't give you any special tools to do it. But see the findText function from this answer and you could use it like:
// Split each text node into things that look like sentences and wrap
// each in a span.
//
var element= $('#content')[0];
findText(element, /.*?[.?!]\s+?/g, function(node, match) {
    var wrap= document.createElement('span');
    node.splitText(match.index+match[0].length);
    wrap.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(span, node.nextSibling);
});

A:

.html() doesn't return the HTML or XHTML markup that was provided to make the nodes, it returns the browser's internal representation of the relevant nodes.  This internal representation is not XHTML compliant and is not made to be--it's technically an internal implementation detail.
You can throw any HTML or XHTML at a browser and it will parse it into an internal DOM.  The internal DOM does not differ if the original source was crappy HTML, good HTML, or perfect XHTML.  The resulting DOM for equivalent source documents will be the same, but generating a new HTML document from that will not necessarily be exactly the same as the source.


Q:

Azure ML deploy locally: tarfile.ReadError: file could not be opened successfully

I am trying to deploy(local) using this line:
local_service = Model.deploy(ws, "test", [model], inference_config, deployment_config)

Then I get this output in the terminal:
tarfile.ReadError: file could not be opened successfully

Screenshot of the output

A:

There was a bug with the retry logic when files were being uploaded. That bug has since been fixed, so updating your SDK should fix the issue.
Similar post: Registering and downloading a fastText .bin model fails with Azure Machine Learning Service


Q:

concatenate key value pairs from python dictionary

I have a dictionary in python. The keys and the values are both strings. In fact the keys are some kind of flag (like -f) and the values are the options (e.g. an int like 20). What I want to do is to create a string with all the keys and values.
The dictionary could look something like this:
{'-f': 20, '-d': 30} and what I would like is something like this:
"-f 20 -d 30"
I think this should be any easy task, but I couldn't find a solution until now...

A:

Here's one approach using a list comprehension:
d = {'-f': 20, '-d': 30}
' '.join([i for k,v in d.items() for i in [k, str(v)]])
# '-f 20 -d 30'

Which is equivalent to:
out = []
for k,v in d.items():
    for i in [k, str(v)]:
        out.append(i)

' '.join(out)
# '-f 20 -d 30'


Q:

Issues Applying css styles conditionally to a twitter-bootstrap table

I have a table containing a list of products.  Below the table I have a text field where a barcode is entered, if the barcode is found the matching row in the table should be highlighted.  i've read through many similar scenarios and as far as I can tell i'm doing everything as I should.  I can see in the  google dev console that the barcode I enter matches the only product currently in my table however for some reason the css doesn't get applied...  Any idea what i'm doing wrong here?/how I can go about fixing it?
my css:
.found {
    background-color: green;
}

my html table and input field:

         Description
         Price
         Qty
         Barcode

            {{item?.ProductDetail_Name}}
            {{item?.Amount}}
            {{item?.Qty}}
            {{item?.Barcode}}

   <form role="form" [formGroup]="spotCheckForm" (ngSubmit)="spotCheck(spotCheckForm.value.itemBarcode)">
        <input class="form-control" type="tel" placeholder="Enter item barcode" [formControl]="spotCheckForm.controls['itemBarcode']">
        <button class="btn btn-block" [disabled]="!spotCheckForm.controls['itemBarcode'].valid && busy"> Search</button>
    </form>

//my ts component function that sets spotCheckBarcode
spotCheck(itemBarcode: number) {
    let found: boolean = false;
     for (var i: number = 0; i < this.ticket.items.length; i++) {
        if (itemBarcode === this.ticket.items[i].Barcode) {
            console.log('found!');
            found = true;
            this.spotCheckBarcode = itemBarcode;
        }
    }
    if (found == false) {
        console.log(`found in if statement: ${found}`);
        this.showError("Item not found on ticket");
    }
}

A:

your class is not applied to td. you need to be bit more specific with css for table here.
.found td { background-color: green; }


Q:

Fragment cannot be converted

i want to create an instance of my fragment in parent activity but it show this error :
Error:(16, 81) error: incompatible types: Fragment cannot be converted to TextFragment
my code:
TextFragment frag =(TextFragment)getFragmentManager().findFragmentById(R.id.textFragment);

TextFragment code:
public class TextFragment extends Fragment{

private long workoutId;

public TextFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_text, container, false);
}

public void setWorkoutId(long workoutId) {
    this.workoutId = workoutId;
}

}

A:

i solve it.
in my TextFragment i import android.support.v4.app.Fragment and in my MainActivity
import android.app.Fragment If both must be the same.


Q:

How can I set a field to be kept as plain while Finatra is parsing a request into a case class?

I have a controller handling a route like 'POST /doit', the json body is automatically parsed into a case class using Finatra built in tools (Jackson, etc), something like this:
class MyController extends Controller {
  post("/doit") { request: MyRequest =>
    // something
  }
}

case class MyRequest(
  id: String,
  custom: String
)

Here are some valid requests:
{ "id": "my id", "custom": "my custom" }

{ "id": "my id", "custom": "{'x': 'y'}" }

As you can see, 'custom' field can be a JSON which can't be deserialized because Jackson expect it to be a POJO instead of a String, I tried wrapping this JSON with quotes but they are ignored and the field is handled as JSON.
How can I let Jackson library to know that this field should be kept plain?
I had read and the best solution I came up with is to write a custom deserializer, in this case, I have not idea how to integrate with Finatra.

A:

As "Ryan O'Neill" pointed out in Finatra Google Group, there are examples for writing a custom deserializer in ExampleCaseClasses.scala.
I'm copying the following code from previous scala source:
import com.fasterxml.jackson.databind.annotation.JsonDeserialize

case class CaseClassWithCustomDecimalFormat(
  @JsonDeserialize(using = classOf[MyBigDecimalDeserializer])
  myBigDecimal: BigDecimal,
  @JsonDeserialize(using = classOf[MyBigDecimalDeserializer])
optMyBigDecimal: Option[BigDecimal])

class MyBigDecimalDeserializer extends JsonDeserializer[BigDecimal] {
  override def deserialize(jp: JsonParser, ctxt: DeserializationContext): BigDecimal = {
    val jsonNode: ValueNode = jp.getCodec.readTree(jp)
    BigDecimal(jsonNode.asText).setScale(2, RoundingMode.HALF_UP)
  }

  override def getEmptyValue: BigDecimal = BigDecimal(0)
}

Thanks Ryan.


Q:

How to delete a file with size 0

I'm working on a project that deals with files and I had difficult time trying to delete a file. Luckily, it was working and it still works for me.
The problem I had was I was trying to delete a file that is empty:
file.length()==0

So I solved my problem but I'm still left with a question.
file.length() returns 0 in both cases

The size is actually zero
The file does not exist in the path

So How am i supposed to eliminate the files that have 0 size in my file explorer. I have too many files with size 0 and I want to erase them from my /files/.
Yes, I tried selecting on the file and clicking on red X several times, but I guess eclipse does not read file with 0 size. With AVD, I could make a new AVD and launch it with formatted setting, but in real life, you can't just buy a new phone to get rid of files with size 0.
Help me how to do this on ECLIPSE please
Thank you

A:

Start adb consol and write follwing command

adb shell
  su
  $rm /yourpath/to/yourfilename

delete your o size file.


Q:

Angular - How to define animation parameters default values?

I am working with Angular animations, and to improve my animation, I need to use parameters. To do so, I did as this answer suggested, with interpolation.
Here is what I have for the state :
state('position', style({ transform: 'translateX({{translate_X}}) translateY({{translate_Y}}) skewX({{skew_X}}) skewY({{skew_Y}})' }))

component.html

And here is the error I didn't manage to solve :

ERROR Error: The animation trigger "move" has failed to build due to
  the following errors:
   - state("position", ...) must define default values for all the following style substitutions: translate_X, translate_Y, skew_X,
  skew_Y
      at InjectableAnimationEngine.AnimationEngine.registerTrigger (...)

So where and how should we define Angular animation parameters default values ?

A:

I'm not sure if it's too late, but the as the console says, you must add a default value for the animation and you can do it by adding
{params: {your_variable_name: 'default_value'}}

in you animation state, like this:
state('in', style({height: '{{maxHeight}}px',}), {params: {maxHeight: '0'}})

Hope it helps!


Q:

EntityReference attribute is not always completely populated

Here's a LINQ to CRM query:
Contact crmContact = xrm.ContactSet.Where(x => x.ContactId == contactId).SingleOrDefault();

I've got an attribute, an EntityReference, as such:
crmContact.assigned_clinic;

As you know, an EntityReference contains these attributes:
- Id (the Guid of the entity that it refers to)
- LogicalName (what type of entity does this reference references to)
- Name (the 'Name' attribute of the entity that's being refered to)

For some reasons I cannot put my finger on, in certain circumstances, the LogicalName and Name attributes are populated correctly, sometimes, they are empty strings.
Any ideas to force a complete retrieval of that data ?

A:

Well, that was not long. I thought SingleOrDefault() retrieved everything, but apparently, you need to call ToList() for that to happen. I changed the query to:
Contact crmContact = xrm.ContactSet.Where(x => x.ContactId == contactId).ToList().SingleOrDefault();

And now all EntityReference attributes are being populated correctly. Sometimes I was doing so, sometimes not which explains the "not always completely populated" mystery.


Q:

Make a div inside a div scrollable on x-axis

I am trying to achieve what the following image suggest:

It's a view with, as you can guess, a list of Magic: The Gathering card sets. I'm trying to display them as shown, but I'm having huge troubles doing so. I need to make a
 inside a
 with a scroll bar in the x axis.
Here's part of my view:

                Type one ability per line:

                @Html.TextAreaFor(_item => _item.mTextAbilities, new { @id = "cardAbilities" })

                        @Html.CheckBoxFor(_item => _item.mAllCardSets)

                        All

                    @{
                        for (int i = 0; i < Model.mListCardSets.Count; i++)
                        {
                            if (i == 0)
                            {
                                @Html.Raw("
")
                            }
                            else if (i % 6 == 0)
                            {
                                @Html.Raw("

")
                            }
                            else if(i == Model.mListCardSets.Count -1)
                            {
                                @Html.Raw("
")
                            }

                                @Html.HiddenFor(_item => _item.mListCardSets[i].Name)
                                @Html.HiddenFor(_item => _item.mListCardSets[i].Code)
                                @Html.CheckBoxFor(_item => _item.mListCardSets[i].IsChecked, new { @class = "checkGroup4", @id = Model.mListCardSets[i].Name })
                                @Html.DisplayFor(_item => _item.mListCardSets[i].Name)
                                @Html.Image("~\\Images\\CardSetRarity\\" + Model.mListCardSets[i].Code + "_R.jpeg", Model.mListCardSets[i].Name, new { @title = Model.mListCardSets[i].Name })

                        }
                    }

And the related css classes:
.formStyle {
    -ms-border-radius: 10px;
    border-radius: 10px;
    padding: 5px;
    background-color: white;
    border: 4px solid darkgrey;
    margin: 5px;
    overflow: hidden;
}

.inline-block {
    max-height: 30%;
    min-height: 30%;
    height: 30%;
    width: 100%;
    display: inline-block;
}

.cardColumn {
    display: table-cell;
    width: 30%;
    padding: 5px;
    position: relative;
}

.wideColumn {
    overflow: auto;
    width: 60%;
    display: table-cell;
}

.blackBorder {
    border: 2px solid black;
}

.scrollX {
    overflow-y: hidden;
    overflow: auto;
}

.row {
    height: 40px;
    line-height: 40px;
}

.columnText {
    max-width: 30%;
    -moz-min-width: 30%;
    -ms-min-width: 30%;
    -o-min-width: 30%;
    -webkit-min-width: 30%;
    min-width: 30%;
}

.columnValue {
    width: 70%;
}

So far I have not succeeded and any help would be appreciated.
Here's a render of how it comes:

A:

TRY overflow-x: scroll; on the div you want element inside it to be scrolling.


Q:

use operator as constructor in prolog

I'm writing a function called leagalCourse, it takes just one parameter, a course list. A course like, for example, john+mary+94 would represent a project done by John and Mary with a mark of 94.

It should be true if the course data is “legal”, which means that it  must not have a project with the same name twice such as john+john+70.
There also must not be two projects in the list containing the same pair of students. So if there’s a project harry+ron+82 in the list, it would be illegal for the list also to contain harry+ron+90 or ron+harry+63.

There is a sample output:
?- legalCourse([one+two+3,four+five+6,one+six+7]).
true.

?- legalCourse([one+two+3,four+four+6,one+six+7]).
false.

?- legalCourse([one+two+3,four+five+6,one+two+7]).
false.

?- legalCourse([one+two+3,two+one+6,one+six+7]).
false.

This is what I tried:
legalCourse([]).
legalCourse(X) :-
        diffName(X).
legalCourse([Project|M]):-
        diffName(Project),
        not(samePair([Project|M])),
        legalCourse(M).

diffName(Name1+Name2+_) :-
        Name1 \= Name2.

/*can not have duplicated group*/
samePair([Name1+Name2+_|More]) :-
        append([[head],tail,More]),
        member(Name1,[head]),
        member(Name2,[head]).

The function partially worked before I added the samePair predicate.

A:

I think this works, you need to switch the vars and check both are different in check_no_dups/1.
legalCourse(List):-
 maplist(triple_double,List,ListDouble),
 check_no_dups(ListDouble).

check_no_dups([]).
check_no_dups([H|T]):-
   H =X+Y,
   maplist(dif(H),T),
   H2 =Y+X,
   maplist(dif(H2),T),
   check_no_dups(T).

triple_double(X+Y+_Z,X+Y):-dif(X,Y).


Q:

Easy way to get NUMBERFMT populated with defaults?

I'm using the Windows API GetNumberFormatEx to format some numbers for display with the appropriate localization choices for the current user (e.g., to make sure they have the right separators in the right places).  This is trivial when you want exactly the user default.
But in some cases I sometimes have to override the number of digits after the radix separator.  That requires providing a NUMBERFMT structure.  What I'd like to do is to call an API that returns the NUMBERFMT populated with the appropriate defaults for the user, and then override just the fields I need to change.  But there doesn't seem to be an API to get the defaults.
Currently, I'm calling GetLocaleInfoEx over and over and then translating that data into the form NUMBERFMT requires.
NUMBERFMT fmt = {0};
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT,
                  LOCALE_IDIGITS | LOCALE_RETURN_NUMBER,
                  reinterpret_cast<LPWSTR>(&fmt.NumDigits),
                  sizeof(fmt.NumDigits)/sizeof(WCHAR));
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT,
                  LOCALE_ILZERO | LOCALE_RETURN_NUMBER,
                  reinterpret_cast<LPWSTR>(&fmt.LeadingZero),
                  sizeof(fmt.LeadingZero)/sizeof(WCHAR));
WCHAR szGrouping[32] = L"";
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SGROUPING, szGrouping,
                  ARRAYSIZE(szGrouping));
if (::lstrcmp(szGrouping, L"3;0") == 0 ||
    ::lstrcmp(szGrouping, L"3") == 0
) {
    fmt.Grouping = 3;
} else if (::lstrcmp(szGrouping, L"3;2;0") == 0) {
    fmt.Grouping = 32;
} else {
    assert(false);  // unexpected grouping string
}
WCHAR szDecimal[16] = L"";
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SDECIMAL, szDecimal,
                  ARRAYSIZE(szDecimal));
fmt.lpDecimalSep = szDecimal;
WCHAR szThousand[16] = L"";
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_STHOUSAND, szThousand,
                  ARRAYSIZE(szThousand));
fmt.lpThousandSep = szThousand;
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT,
                  LOCALE_INEGNUMBER | LOCALE_RETURN_NUMBER,
                  reinterpret_cast<LPWSTR>(&fmt.NegativeOrder),
                  sizeof(fmt.NegativeOrder)/sizeof(WCHAR));

Isn't there an API that already does this?

A:

I just wrote some code to do this last week.  Alas, there does not seem to be a GetDefaultNumberFormat(LCID lcid, NUMBERFMT* fmt) function; you will have to write it yourself as you've already started.  On a side note, the grouping string has a well-defined format that can be easily parsed; your current code is wrong for "3" (should be 30) and obviously will fail on more exotic groupings (though this is probably not much of a concern, really).


Q:

React js Material-UI responsive table

I am building a web application in react js and I'm using the material-ui components library. I'm using the table component and it looks good on desktop but I want it to adjust and look good also on mobile browser. Is material-ui supports such thing? How can I do it? Example of the current situation:
PC\Mobile:

Source code:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const styles = theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'auto',
  },
  table: {
    minWidth: 700,
  },
});

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const data = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

function SimpleTable(props) {
  const { classes } = props;

  return (
    <Paper className={classes.root}>

        <TableHead>
          <TableRow>
            <TableCell>Dessert (100g serving)</TableCell>
            <TableCell numeric>Calories</TableCell>
            <TableCell numeric>Fat (g)</TableCell>
            <TableCell numeric>Carbs (g)</TableCell>
            <TableCell numeric>Protein (g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map(n => {
            return (
              <TableRow key={n.id}>
                <TableCell component="th" scope="row">
                  {n.name}
                </TableCell>
                <TableCell numeric>{n.calories}</TableCell>
                <TableCell numeric>{n.fat}</TableCell>
                <TableCell numeric>{n.carbs}</TableCell>
                <TableCell numeric>{n.protein}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>

    </Paper>
  );
}

SimpleTable.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SimpleTable);

A:

For Material-UI tables padding-right and padding-left of every table cell should be changed,
you can have code in Codesandbox
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const styles = theme => ({
  root: {
    display: 'flex',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'hide',
  },
  table: {
    minWidth: 340,
  },
  tableCell: {
    paddingRight: 4,
    paddingLeft: 5
  }
});

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const data = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

function SimpleTable(props) {
  const { classes } = props;

  return (
    <Paper className={classes.root}>

        <TableHead>
          <TableRow>
            <TableCell className={classes.tableCell}>Dessert (100g serving)</TableCell>
            <TableCell numeric className={classes.tableCell}>Calories</TableCell>
            <TableCell numeric className={classes.tableCell}>Fat (g)</TableCell>
            <TableCell numeric className={classes.tableCell}>Carbs (g)</TableCell>
            <TableCell numeric className={classes.tableCell}>Protein (g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map(n => {
            return (
              <TableRow key={n.id}>
                <TableCell component="th" scope="row" className={classes.TableCell}>
                  {n.name}
                </TableCell>
                <TableCell numeric className={classes.tableCell}>{n.calories}</TableCell>
                <TableCell numeric className={classes.tableCell}>{n.fat}</TableCell>
                <TableCell numeric className={classes.tableCell}>{n.carbs}</TableCell>
                <TableCell numeric className={classes.tableCell}>{n.protein}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>

    </Paper>
  );
}

SimpleTable.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SimpleTable);

To make it responsive you need to use Grid system in the first place, For example this is grid system for full-page:
 <Grid item xs={12}>

  </Grid>


Q:

undefined local variable or method `number_to_delimited'

I'm using rails 4.2.5.
And in rails API (for v4.2.5.2) I see this helper:
number_to_delimited(number, options = {})

Formats a number with grouped thousands using delimiter (e.g., 12,324). You can customize the format in the options hash.

http://api.rubyonrails.org/classes/ActiveSupport/NumberHelper.html#method-i-number_to_delimited
But when I using this help in my views, it throws an error:
undefined methodnumber_to_delimited' for #<#:0x0000000b091b30>`
Other helpers, such like number_to_currency， all works well. What's wrong with me?

A:

Try to call ActiveSupport::NumberHelper instead.
ActiveSupport::NumberHelper.number_to_delimited(12345678)
 => "12,345,678"

Or you could do also with this:
include ActiveSupport::NumberHelper
number_to_delimited(12345678)
 => "12,345,678"

UPDATE:
I see you said in comment above that you're using haml code and you can do it like:
= ActiveSupport::NumberHelper.number_to_delimited(12345678)

Or
- include ActiveSupport::NumberHelper
= number_to_delimited(12345678)


Q:

How to get GAL from outlook on the web

Is there any way to pull data from something like a GAL(global address list) in outlook on the web?
An example would be to be able to search for a contact and then taking their data from the server to be stored to local variables.
Only Use the [outlook.office.com] website
it going to run in node.js
Is there any other way to use create new app registrations in the Azure Management Portal?

A:

You will have to use Exchange Web Services to search the GAL, as I don't think the People REST API can search it:
FindPeople operation:
https://msdn.microsoft.com/en-us/library/office/jj191039(v=exchg.150).aspx


Q:

Tilda: no contrast between active and inactive tabs

This topic is very close to what was suggested in Gnome-terminal tabs: no contrast between active and inactive tabs.
I'm using Ubuntu 14.04 and although the gtk.css configuration works fine with default gnome terminal, it does not apply to my tilda terminal.
Does anyone know how to get the same effect on tilda ?

A:

You could use following configuration placed in ~/.config/tilda/style.css file:
GtkWindow#Main {
    #background-color: rgba(0, 0, 0, 0);
    background-color: #000000;
}

GtkWindow#Main .notebook {
    padding: 0px;
}

GtkWindow#Main .notebook tab GtkLabel {
    padding-left: 15px;
    padding-right: 15px;
    color: #505050;
}

GtkWindow#Main .notebook tab {
    background-color: #101010;
}

GtkWindow#Main .notebook tab:active {
    #background-color: rgba(0, 0, 0, 0.85);
    background-color: #181818;
}


Q:

QGIS 3.4 Modeler: Select a band of a raster layer for processing

As model input data I select a raster stack with three bands. The first processing tool just needs specific bands of this stack which I like to select in the input dialog.
I create a 'Raster Layer' input that lets me select the layer. Then, I also create a 'Raster Band' input that has the 'Raster Layer' input as parent. In the GUI that is displayed as a drop-down menu and I can choose between the bands.
However, the model always takes the first band of the raster layer, no matter which band I select. The processes following the layer/band selection are connected to the selection of the layer, because there is no possibility of selecting the bands (see screenshot):

How can I make the processing tools to use a specific band of a layer?

A:

I solved it. It seems, that not all tools can work with a band selection as input. The used GDAL "Clip raster by extent" tool was not able to deal with that.
I then inserted the GDAL "Rearrange bands" tool before the clipping tool. That tool is able to choose a specific band based on the input selection and to forward it to the next tool.


Q:

Как динамично определять class_name для связи has_many, используя одинаковые таблицы разных engines

Здравствуйте, подскажите как определить связь, в зависимости от атрибута модели?
У модели User есть атрибут pay_currency, который может быть 'real' или 'bitcoin'. Есть 2 engines(Tbitcoin, Tstripe) у каждого из которых есть одинаковая таблица payment.
Необходимо найти способ, как создавая payment от юзера, направлять в нужный engine автоматически.
# Пример создания payments
User.create(pay_currency: 'real').payments.create # => Tstripe::Payments

Примерный код, для задумки
class User < ActiveRecord::Base

  has_many :payments, ~> { where "pay_currency = 'real'" } , class_name: Tstripe::Payment, foreign_key: :uid
  has_many :payments, ~> { where "pay_currency = 'bitcoin'" } ,class_name: Tbitcoin::Payment, foreign_key: :uid
end

В какое направление думать для реализации такой динамики?

A:

Во-первых, сделайте этим ассоциациям разные имена, а то они наложатся друг на друга и будет знатный ба-бах:
has_many :stripe_payments, class_name: Tstripe::Payment,
                           foreign_key: :uid
has_many :bitcoin_payments, class_name: Tbitcoin::Payment,
                            foreign_key: :uid

А потом просто сделайте выбор одной из двух ассоциаций. Есть целая куча способов.

Можно сделать в User метод, принимающий способ оплаты и возвращающий одну из двух ассоциаций (надо ловить случаи, когда получен несуществующий способ).
Можно сделать "создавалку платежей", одним из параметров которой является способ оплаты, и она внутри будет выбирать ассоциацию.
Можно просто разместить их в разных контроллерах и ссылаться не на "общие" payments, а только на конкретные.
Выбирайте любой.


Q:

Pandas pivot table using custom conditions on the dataframe

I want to make a pivot table based on custom conditions in the dataframe:
The dataframe looks like this:
>>> df = pd.DataFrame({"Area": ["A", "A", "B", "A", "C", "A", "D", "A"],
                       "City" : ["X", "Y", "Z", "P", "Q", "R", "S", "X"],
                       "Condition" : ["Good", "Bad", "Good", "Good", "Good", "Bad", "Good", "Good"],
                       "Population" : [100,150,50,200,170,390,80,100]
                       "Pincode" : ["X1", "Y1", "Z1", "P1", "Q1", "R1", "S1", "X2"] })
>>> df
  Area City Condition   Population Pincode
 0    A    X      Good   100       X1
 1    A    Y       Bad   150       Y1
 2    B    Z      Good   50        Z1
 3    A    P      Good   200       P1
 4    C    Q      Good   170       Q1
 5    A    R       Bad   390       R1
 6    D    S      Good   80        S1
 7    A    X      Good   100       X2

Now I want to pivot the dataframe df in a manner such that I can see the unique count of cities against each area along with the corresponding count of "Good" cities and also the population of the area.
I expect an output like this:
Area  city_count  good_city_count   Population
A        4        2                 940
B        1        1                 50
C        1        1                 170
D        1        1                 80
All      7        5                 1240

I can give a dictionary to the aggfunc parameter but this doesn't give me the city count split between the good cities.
>>> city_count = df.pivot_table(index=["Area"],
                                values=["City", "Population"],
                                aggfunc={"City": lambda x: len(x.unique()),
                                         "Population": "sum"},
                                margins=True)

    Area    City    Population
0   A       4       940
1   B       1       50
2   C       1       170
3   D       1       80
4   All     7       1240

I can merge two different pivot tables - one with the count of cities and the other with the population but this is not scalable for a large dataset with a big aggfunc dictionary.

A:

Another method without using pivot_table. Use np.where with groupby+agg:
df['Condition'] = np.where(df['Condition']=='Good', df['City'], np.nan)
df = df.groupby('Area').agg({'City':'nunique', 'Condition':'nunique', 'Population':'sum'})\
                       .rename(columns={'City':'city_count', 'Condition':'good_city_count'})
df.loc['All',:] = df.sum()
df = df.astype(int).reset_index()

print(df)
  Area  city_count  good_city_count  Population
0    A           4                2         940
1    B           1                1          50
2    C           1                1         170
3    D           1                1          80
4  All           7                5        1240


Q:

XSS Me Warnings - real XSS issues?

I've been using the free Firefox extension XSS Me from Security Compass to test for XSS problems. However, using what I understand to be safe filtering, XSS me still reports warnings. Are these accurate warnings or spurious?
Using the code below as a testcase:
<form method="post" action="">
<input type="text" name="param" value="<?php echo htmlentities($_POST['param'])?>">
<input type="submit">
</form>
<?php echo htmlentities($_POST['param'])?>

I run some nasties by hand but none of them are executed in the browser, and using Charles debugging proxy I can see that the response is encoded as expected.
However, XSS Me reports a number of warnings, as if it can see the unencoded string in the HTML source:
alt text http://img696.imageshack.us/img696/8850/xss.png
Looking in Charles at the same time, I can see the strings are encoded and should be safe e.g. <IMG SRC="jav ascript:document.vulnerable=true;">

Is there a vulnerability I haven't fixed?
Are these rogue warning messages?
And if so, is another Firefox extension (Firebug?) conflicting with XSS Me?

A:

I work at Security Compass and am the lead developer for the Exploit Me tools.
You're right that XSS Me is reporting a warning because these attack strings seem (to XSS Me) to have come back from the server completely unencoded. Another parser/JavaScript engine (like IE 6/7/8, Safari, or Chrome) might execute this code even though Firefox's parser and JavaScript engine don't.
XSS Me submits two requests:

One request where we detect exploitation using FireFox's JavaScript engine, which we call "errors"
A second request where we detect exploitation by simply grepping for the attack string in the HTML response page

The warning you're getting is caused by this second request.
I can help you get to the root cause of this issue if you can do the following:

Use packet sniffing software (i.e. Wireshark http://www.wireshark.org/) to detect the attack string rather than Charles. Sometimes proxies have a way of modifying or otherwise altering requests
In Firefox, can you go to tools->addons and disable all the extensions except XSS Me? That way you can be sure no other extension is changing the response (or request) before it gets to XSS Me.
View the source of the response page in Firefox to see if the unencoded string appears

If you'd like to send me an email (tom@securitycompass.com) with those results I'd be happy to help figure this out. If it's a bug in XSS Me (which I certainly hope not) then I can patch it and get a new build out.
Thanks,
Tom


Q:

What is that gooey stuff from okra?

When cooking okra in a bit of water, the water becomes gooey.  What does the okra release that makes the water slimy?  Would the goo have other culinary uses (as an additive to thicken sauces or improve the texture of ice-creams)?

A:

The slime is called mucilage. It is around the seeds on the inside of the pod. It is made of protein and carbohydrates including fiber.
The mucilage is (as you alluded in your question) used for thickening gumbos and similar stews. Besides this, I've only ever seen it referred to as an annoyance and avoided by leaving the pod whole or dry cooking like frying.
I imagine there could be some creative halloween uses of mucilage but those would be off topic for this site. :)
EDIT
I was embarrassed that this answer was the accepted answer. I don't like answers that are (as mine was) "no that isn't possible because I've never heard of it." I was hoping someone else would shatter my world with some amazing new use of okra slime.
My curiosity piqued I used some of my copious free time while code compiled to do some more research.
I was able to find a couple of non traditional okra recipes that seemed interesting- such as candied okra slices or using the seeds from pickled okra as a caviar-like dish. But none of them took advantage of the mucilage- they all avoided it.
Carbohydrate based mucilage is used in ice cream and for other reasons. I found the following study about food health that did experiments with replacing milk fat with specifically okra mucilage (they refer to it as "okra gum")
Okra gum is acceptable milk-fat ingredient substitute in dessert
Two pertinent quotes:
"Although not currently produced by food manufacturers, previous studies produced fat-free chocolate bar cookies with acceptable sensory characteristics using okra gum as a fat ingredient substitute."
"Specifically, color and smell of frozen dairy desserts containing okra gum replacement for milk fat did not significantly differ from the control product. Texture, flavor, aftertaste, and overall acceptability ratings also averaged five or higher (neutral to like) for all products."
The study was about replacing milk fat where I think it would be more interesting as an enhancer as you asked in your question.
It seems perfectly reasonable that okra mucilage could find a place in more modern recipes.
But I couldn't find anyone doing it.

A:

While researching okra for an article (I'm a freelance writer) I came across this page by seridipity and thought I'd share what I've found (so far) in my quest: The mucilage in okra is a desired trait in West African (and, by extension, Brazilian, Caribbean and southeastern U.S.) cuisine. Baobab leaves also produce mucilage when cooked. It is used as a thickening agent in soups, stews and some stuffed okra pod dishes (also in South and Southeast Asia).
The only other use I've found is as a hair conditioner, which is a traditional Indian treatment that has become into some use in the United States.
There's some investigation into using it industrially as a low-friction lubricant.
Bryan Johnson


Q:

elementary Inequality.

Prove: $$ \Big|\int_1^\sqrt{3} \! \frac{\sin(x)}{e^x(x^2 +1)} \, \mathrm{d} x \Big| \leq \frac{\pi}{12e}$$
Approach: we know:
$$ \Big|\int_1^\sqrt{3} \! \frac{\sin(x)}{e^x(x^2 +1)} \, \mathrm{d} x \Big| \leq \int_1^\sqrt{3} \! \frac{|\sin(x)|}{e^x(x^2 +1)} \, \mathrm{d} x \leq \int_1^\sqrt{3} \! \frac{1}{e^x(x^2 +1)} \, \mathrm{d} x$$ Since $|\sin(x)|$ is bounded by 1 for every $x$. Can we keep estimating this integral, or should we just solve the last integral?
thanks.

A:

Use the fact $ 1<x<\sqrt{3} \implies e<e^x<e^{\sqrt{3}}$ and $|sin(x)|\leq 1$
$$\Big|\int_1^\sqrt{3} \! \frac{\sin(x)}{e^x(x^2 +1)} \, \mathrm{d} x \Big|\leq \int_1^\sqrt{3} \! \frac{1}{e(x^2 +1)} \, \mathrm{d} x  \leq \frac{\pi}{12e}$$


Q:

HttpTransportSE .call() method has no action

I'm trying to make an Android App that gets the weather based off a zipcode you enter, and that also displays the time in EST and GMT format. I am using webservices (WSDLs) and have the code written to access it, the code is below:
public void sendMessage(View view)
{
    SOAP_ACTION = "http://ws.cdyne.com/WeatherWS/GetCityWeatherByZIP";
    NAMESPACE = "http://ws.cdyne.com/WeatherWS/";
    METHOD_NAME = "GetCityWeatherByZIP";
    URL = "http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl";

    txtZIP = (EditText) findViewById(R.id.zipcode);
    temp = (TextView) findViewById(R.id.displayTemp);
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo property = new PropertyInfo();
    {
        property.name = "zipcode";
        property.setNamespace(NAMESPACE);
        property.type = PropertyInfo.STRING_CLASS;
        property.setValue(txtZIP.getText().toString());
    }

    request.addProperty(property);

    //request.addProperty("zipcode", txtZIP.getText().toString());

    Toast.makeText(getApplicationContext(), "btnZIP pressed", Toast.LENGTH_LONG).show();
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
    envelope.setOutputSoapObject(request);
    envelope.implicitTypes = true;
    envelope.dotNet = true;
    HttpTransportSE androidHTTP = new HttpTransportSE(URL, 600);

    try {
        Toast.makeText(getApplicationContext(), "In try statement", Toast.LENGTH_LONG).show();

        androidHTTP.call(SOAP_ACTION, envelope);

        // SoapPrimitive resp = (SoapPrimitive) envelope.getResponse();
        SoapObject result = (SoapObject) envelope.bodyIn;

        if(result != null)
        {
            Toast.makeText(getApplicationContext(), "In IF statement", Toast.LENGTH_LONG).show();
            //temp.append("in IF statement, result not null");
        } else {
            Toast.makeText(getApplicationContext(), "In ELSE statement", Toast.LENGTH_LONG).show();
            //temp.append("in IF statement, result IS null");
        }

    } catch (HttpResponseException e) {
        Toast.makeText(getApplicationContext(), "No Response", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    } catch (XmlPullParserException e){
        Toast.makeText(getApplicationContext(), "XML Pull exe", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Now, my problem is that with the androidHTTP.call(SOAP_ACTION, envelope); method, nothing is happening. I have Toast methods to show what is being executed, and the furthest I get is into the try block, but never into the if statement.
I have tried looking around seeing what might be the cause and a solution, but I can't seem to find anything for this specific problem. I've extended the time-out for the server to 600 and even made the implicitType to true, but nothing is working. I know I am using SoapEnvelope.VER10 for this method, but I have two other methods where I used VER11 and VER12 and there's no change. If anyone might have an idea as to what might be going on, I'd really appreciate the help. Also, the AndroidManifest.xml has the necessary uses-permission line to access the internet.

A:

!!!! WORKING CONFIRMED !!!
main
public class MainActivity extends Activity{

public static String rslt,thread;
SoapMiddleMan c;

EditText txtZIP;
TextView weather;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    txtZIP = (EditText)findViewById(R.id.zipCode);
    weather = (TextView)findViewById(R.id.weather);

  }

public void sendMessage(View view)
{
    try{
            // condition for keeping the main thread asleep
            thread = "START";

            // create a new webservice caller thread
            c = new SoapMiddleMan();

            // join the new thread, start it and then select what webservice you want to access
            c.join();c.setZip(txtZIP.getText().toString()); c.start();

            // keep this thread asleep while the service thread is running
            while(thread=="START")
            {
                try
                    {
                        Thread.sleep(10);
                    }
                catch(Exception e)
                    {
                        rslt="Failed2";
                    }
            }
        }

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

    weather.setText(rslt);
}
}

middleman
public class SoapMiddleMan extends Thread {

private String zip;
private SoapSenderClass cs;

public void run(){

    try{
         cs=new SoapSenderClass();
         String resp=cs.getWeather(zip);
         MainActivity.rslt=resp; //public string in calling activity
         System.out.println("reached 2 \n");
        }catch(Exception ex)

        {
            MainActivity.rslt=ex.toString();
        }

        MainActivity.thread = "done";
    }

public void setZip(String searchZip)
{
    zip = searchZip;
}

}

Caller
public class SoapSenderClass{

String SOAP_ACTION = "http://ws.cdyne.com/WeatherWS/GetCityWeatherByZIP";
String NAMESPACE = "http://ws.cdyne.com/WeatherWS/";
String METHOD_NAME = "GetCityWeatherByZIP";
String URL = "http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl";

public String getWeather(String zipcode)
{
    try{
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

    envelope.dotNet = true;

    PropertyInfo property = new PropertyInfo();

    property.setName("ZIP");
    property.setType(String.class);
    property.setValue(zipcode);
    request.addProperty(property);

    envelope.setOutputSoapObject(request);

    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    androidHttpTransport.call(SOAP_ACTION, envelope);

    SoapObject response = (SoapObject)envelope.getResponse();

    String resultValue = response.toString();

    return resultValue;

}
catch (Exception e) {
    e.printStackTrace();
    return "Failed to get ID";
}

}
}

I have simplified your caller code and I changed the name of the addproperty to ZIP which is what it looks like the input is called in the WSDL.  Removed the brackets for the property calls removed Namespace which isnt needed as far as I can tell.


Q:

C++: Data structure for efficient insertion and retrieval of custom data

I'm having a situation in C++ (on Windows) where I need to keep a set of pair of int: pair where start values are unique (we need not be concerned with this).
The operations required are:

insert pair
retrieve pair X: this should return the pair Y where Y's start < X's start < X's end < Y's end. If Y doesn't exist, return false.

The basic solution is to simply keep a set of pairs. For retrieval, we'll iterate sequentially through the set to check. This is O(n).
I'm looking for a better solution. I currently see 2 candidate data structures:

Sorted vector
STL's set (internally implemented as binary search tree?)

Sorted Vector:
Pros: can customize the binary search to support the retrieval operation. This is O(logn)
Cons: how to efficiently insert a new pair to maintain the sorted order. How to avoid a re-sorting cost of O(nlogn)?
Set:
Pros: Easy insertion using the standard insert method. This is O(1)?
Cons: How to avoid the sequential search? How to do better than O(n)?
Thanks for your advice.
I'm also open to any other structures that can efficiently (1st criterion is speed; 2nd is memory) support the 2 operations mentioned above.

A:

It isn't clear whether the ranges can overlap, but if they can't, then this should work.  I've included a complete example with tests.
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <map>

struct RangeContainer {
  typedef std::map<int,int> RangeMap;
  typedef std::pair<int,int> Range;

  void insert(const Range &range)
  {
    range_map.insert(range);
  }

  Range find(const Range &x) const
  {
    RangeMap::const_iterator iter = range_map.upper_bound(x.second);
    if (iter==range_map.begin()) {
      return invalidRange();
    }
    --iter;
    Range y = *iter;
    if (y.first<x.first && x.second<y.second) {
      return y;
    }

    return invalidRange();
  }

  static Range invalidRange()
  {
    return Range(INT_MAX,INT_MIN);
  }

  RangeMap range_map;
};

static void test1()
{
  RangeContainer c;
  typedef RangeContainer::Range Range;
  c.insert(Range(1,10));
  c.insert(Range(20,30));
  assert(c.find(Range(-5,-4))==c.invalidRange());
  assert(c.find(Range(1,10))==c.invalidRange());
  assert(c.find(Range(2,9))==Range(1,10));
  assert(c.find(Range(2,10))==c.invalidRange());
  assert(c.find(Range(11,19))==c.invalidRange());
  assert(c.find(Range(21,29))==Range(20,30));
  assert(c.find(Range(20,29))==c.invalidRange());
  assert(c.find(Range(21,30))==c.invalidRange());
  assert(c.find(Range(35,40))==c.invalidRange());
}

int main(int argc,char **argv)
{
  test1();
  return EXIT_SUCCESS;
}


Q:

Magento - get cart items for a given product id

I try to get the cart items for a given product;
I have tried this code :
$product = Mage::getModel('catalog/product')
    ->setStoreId(Mage::app()->getStore()->getId())
    ->load('2784');

$quote = Mage::getSingleton('checkout/cart')->getQuote();
$cartItems = $quote->getItemByProduct($product);
foreach ($cartItems as $item) {
    echo $item->getId()."<br/>";
}

but it don't gives anything.
How can I modify my code to use "getItemByProduct" in the right form ?
Thanks for help.

A:

getItemByProduct() returns the first matching Mage_Sales_Model_Quote_Item so there is no need for an extra loop.
$item = $quote->getItemByProduct($product);
if ($item !== false) echo $item->getId();


Q:

What does a Kenku's speech sound like?

Introduced in Volo's Guide to Monsters, Kenku can only speak by imitating sounds they've heard — they're unable to speak with their own voices (p. 110):

Although unable to speak in their own voices, kenku can perfectly mimic any sound they hear [...] [K]enku cannot create new sounds and can communicate only by using sounds they have heard.

What does it sound like when talking with a kenku?
Does the quote above mean that each mimicked piece of speech they use sound exactly as they heard it, including the original speaker's voice? Do they only use entire whole phrases they've heard, or do they piece together sentences from different sounds they've heard in different phrases? If the latter, is each word going to be using a different voice?

Related: Is it possible for a Kenku to speak a language fluently through mimicry?

A:

The fun way to do this, as well as the obvious interpretation of the rules, would be to have them imitate phrases perfectly, sounding like the original speaker, but using them in approximately the sense they originally heard them. So their voices can change completely from sentence to sentence - one being a dwarf they heard speaking yesterday, the next sentence being a small elf child they heard ten years ago, and the third being something you said to them three months ago.
They understand what phrases and sentences mean, but if they can't break down phrases into words and use the words individually, they're still fairly limited by their curse. They would sound a bit like Dilbert's pointy-haired boss, who tends to come out with phrases and clichés that belong in a subtly different conversation.
This would be an interesting challenge for a player who was usually verbally adroit. Precedents for even more extreme versions exist in the Librarian from Terry Pratchett's Discworld series who manages to get by with just one word, "Oook", and Mr Punch in the classic Punch & Judy show, most of whose lines are "That's the way to do it!"
The main problem with playing a Kenku this way would be avoiding humour in serious moments of the game.

A:

Chris Perkins talked about this on Twitter a while back, and I like his approach (I'm still looking for the Tweet).  The gist is that between sounds, captured phrases and gestures.  He goes on to say that the player who actually makes the noises would likely not survive the night as the other players would likely drag him out back...  So, he presented something like:

My character clicks the sound of coins rubbing together and then makes a tearing sound as looks at his empty hand first, and then the one holding a dagger and makes a gesture of drawing the dagger across his throat.

A:

Given that a Kenku can understand languages but cannot produce new sounds there would be a lot of oddities with their speech, it would almost be as though they are communicating with a tape recorder. A normal speaker can alter their pitch and volume to make their sentences flow where a Kenku could not. A Kenku's speech might vary unexpectedly in pitch and volume from word to word due to piecing together a lifetime of hearing words different ways. Unable to alter pitch, their sentences would lack proper emotion and emphasis. Unable to alter volume, a Kenku would not be able to whisper or yell their exact thought either.
The related question's answers mention the "spark of creativity." A term which I find very subjective. Though if they do in fact lack creativity, this would mean their speech would be very plain and literal, not using metaphors, similes, idioms, etc... The lack of creativity might also mean they just simply prefer to say phrases in the exact tone and volume exactly as they heard them, but I would not rule out them talking in their own extremely odd way if necessary.


Q:

Getting medications before Covered California coverage begins?

I have a friend who takes several medications for mental health. She lost her health insurance coverage in December but signed up for a healthcare plan through Covered California during open enrollment; her new plan takes effect on February 1st.
She doesn't have enough medication to last the next 11 days and I'm trying to help her figure out what she can do to bridge that gap. Missing a week or more of several of the medications would be a big deal.
I'm sure she's not the only person who has run into this type of issue and I'm wondering if there is any system in place for people in her situation to get a few days of medication to tide her over until her plan officially starts. She runs out of one medication on Monday, but since it's the weekend now we haven't been able to get through to anyone who could help us with this by phone.
What options are available for patients who need psychiatric medication refills right before their insurance coverage starts?

A:

The big problem regarding lack of insurance is that the patient has to pay list price for the medicine.
Some doctors have access to samples. They are usually used to start a  patient out with a dose or two before the prescription can be filled. They are also used when testing a patients reaction to the new medicine or to see if it is effective as a previous medicine.
Approach the current doctor to see what can be done. They can sometimes give the patient a couple of doses for free. They may also be able to change the prescription to a generic, or to an option that has a coupon to bring the cost of a small supply down to a more reasonable number.
Bringing the paperwork showing that the patient is waiting for the 1st of February may help prove the situation, and make it seem that they are no doctor shopping.
Note: Cynics would say the samples/coupons are used by the drug company to make sure the doctor writes prescriptions for their drug.