text:
Q: What can be best appropriate HBase schema for RDBMS table I am just beginner to HBase. I want to migrate RDBMS table to HBase.
Table schema in RDBMS is somewhat like this :
Field            Type              Collation          Null    Key     Default  Extra             Privileges                       Comment
---------------  ----------------  -----------------  ------  ------  -------  ------------  --  -------------------------------  -------
id               int(16) unsigned  (NULL)             NO      PRI     (NULL)       auto_increment  select,insert,update,references
user_id          varchar(64)       latin1_swedish_ci  NO      MUL     (NULL)                   select,insert,update,references
type_id          int(11)           (NULL)             NO              (NULL)                   select,insert,update,references
application_id   int(16) unsigned  (NULL)             YES     MUL     (NULL)                   select,insert,update,references
title            varchar(128)      latin1_swedish_ci  YES             (NULL)                   select,insert,update,references
body             text              latin1_swedish_ci  YES             (NULL)                   select,insert,update,references
posted_time      datetime          (NULL)             YES             (NULL)                   select,insert,update,references
template_params  text              latin1_swedish_ci  YES             (NULL)                   select,insert,update,references
count            int(11)           (NULL)             YES             (NULL)                   select,insert,update,references
reference_id     int(16)           (NULL)             YES             (NULL)                   select,insert,update,references
viewer_id        varchar(64)       latin1_swedish_ci  YES             (NULL)                   select,insert,update,references

Here body and templete have json data in varchar format. Now i want to create schema for this table in HBase.
Operation performed on this data :
1. Activity retrival for a user id
2. Activity retrival for a viewer id
3. Activity retrival for particular type_id/particular type_id and user_id.
4. Activity retrival made after t time.

What will be the appropiate schema for this?

A: 4. Activity retrival made after t time.

This will not be so much a problem; HBase stores everything with timestamps, and you can query for all entries after time t.
As for 1, 2 and 3, are you trying to make access fast? If so, I recommend creating three separate tables that will store the data - yes, there is redundancy, but queries will be fast.

*

*Use user_id as row key, and store the rest of the values in the columns

*Use viewer_id as row key, and store rest of the values in the columns

*Use type_id AND user_id as row key, with type_id in front of user_id. This way, you can query by type_id if only that is provided, and by type_id and user_id if both are provided. (Note that you will have to scan here, and not use the regular get().)

You can code this using HappyBase Python library as follows:
con = happybase.Connection()
user = conn.table('user')
viewer = conn.table('viewer')
type_user = conn.table('type_user')

def insert (user_id, viewer_id, type_id):
  user.put (user_id, {'viewer_id': viewer_id, 'type_id': type_id})
  viewer.put (viewer_id, {'user_id': user_id, 'type_id': type_id})
  type_user.put (type_id + user_id, {'viewer_id': viewer_id})

def get_user (user_id):
  return user.row(user_id)

def get_viewer (viewer_id):
  return viewer.row(viewer_id)

def get_type_user (type_id, user_id):
  if user_id == "":
    rowkey = type_id
  else
    rowkey = type_id + user_id
  # Note that we use a scan here to match only type_id if it exists
  return type_user.scan(row_prefix=rowkey)


text:
Q: difftime in R dataframe based on subset I've got this sample dataframe, that keeps track of the time when a lamp is switched on and off.
                  time lamp status
1  2015-01-01 12:18:17    2     ON
2  2015-01-01 13:07:29   28     ON
3  2015-01-01 13:11:50   28    OFF
4  2015-01-01 13:18:28    2    OFF
5  2015-01-01 14:07:29   28     ON
6  2015-01-01 14:11:35   28    OFF
7  2015-01-01 14:18:28    2     ON
5  2015-01-01 14:18:57    2    OFF

What I want to achieve is to add a fourth column, containing the duration of a period where a lamp has been switched on (in seconds).
The desired output:
                  time lamp status duration
1  2015-01-01 12:18:17    2     ON     3611
2  2015-01-01 13:07:29   28     ON      261
3  2015-01-01 13:11:50   28    OFF       NA
4  2015-01-01 13:18:28    2    OFF       NA
5  2015-01-01 14:07:29   28     ON      246
6  2015-01-01 14:11:35   28    OFF       NA
7  2015-01-01 14:18:28    2     ON       29
5  2015-01-01 14:18:57    2    OFF       NA

I already succeeded in doing this with a custom function, involving while and for-loops. BUT...
I'm a beginner in R, and I'm pretty sure this can be done more simple and elegant (using subsets, apply, and/or ....). I just can't figure out how?
Any ideas, of leads in the right direction?

A: This works for me:
library(dplyr)
df <- df %>% mutate(sec=as.numeric(time)) %>% group_by(lamp) %>% mutate(duration=c(diff(sec), NA)) %>% select(-sec)
df$duration[df$status=="OFF"] <- NA
#### 1 2015-01-01 12:18:17     2     ON     3611
#### 2 2015-01-01 13:07:29    28     ON      261
#### 3 2015-01-01 13:11:50    28    OFF       NA

Your data:
df=structure(list(time = structure(c(1420111097, 1420114049, 1420114310,
1420114708, 1420117649, 1420117895, 1420118308, 1420118337), class = c("POSIXct",
"POSIXt"), tzone = ""), lamp = c(2L, 28L, 28L, 2L, 28L, 28L,
2L, 2L), status = structure(c(2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L), .Label = c("OFF",
"ON"), class = "factor"), duration = c(2952, 261, NA, NA, 246,
NA, 29, NA)), .Names = c("time", "lamp", "status", "duration"
), row.names = c(NA, -8L), class = "data.frame")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django m2m_changed signal, post_add is called automatically after post_remove I want to remove user from Tank's moderatos, when user is removed from Tank's users field.
but when i called instance.moderators.remove(*pk_set) it is removed and then added again by post_add signal.
works in this way users.pre_remove > users.post_remove > moderators.pre_remove > moderators.post_remove > moderators.pre_add > moderators.post_add
the last two (pre_add, post_add) are getting called unnecessarily
I am using Django admin page for these operations.
Model :
class Tank(models.Model):
    device = models.OneToOneField(Device, on_delete=models.SET_DEFAULT,
                              related_name="tank", default=1)
    users = models.ManyToManyField(settings.AUTH_USER_MODEL,
                               related_name="tanks", blank=True)
        hidden_for_users = models.ManyToManyField(
    settings.AUTH_USER_MODEL, related_name="hidden_tanks",
        blank=True)
    admins = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                related_name="tanks_of_admin", blank=True)
    moderators = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    related_name="tanks_of_moderator", blank=True)
    name = models.CharField(max_length=40)

Signals :
@receiver(pre_save, sender=Tank)
def set_attr_if_needed(instance, *args, **kwargs):
    # set ttype
    if not instance.ttype:
        obj, _ = Type.objects.get_or_create(name='overhead tank')
        instance.ttype = obj

@receiver(post_save, sender=Tank)
def create_device_offline_notification(instance, created, *args, **kwargs):
    if created:
        Notification.query.fetch_or_create(instance, "device offline")

def __add_users_to_location(instance):
    """ add tank's users to location's users """
    location = instance.locations.filter(
        location_type__name='Apartment').first()
    if location:
        location.users.add(*instance.users.all())

def __copy_addition_to_users(instance, users):
    """ add moderators and admins to users list """
    instance.users.add(*users)

@receiver(m2m_changed, sender=Tank.users.through)
def on_tank_users_change(instance, action,pk_set, **_):
    if action == 'post_add':
        __add_users_to_location(instance=instance)
    elif action == 'post_remove':
        instance.moderators.remove(*pk_set)

@receiver(m2m_changed, sender=Tank.moderators.through)
def on_tank_moderators_change(instance, action,pk_set, **_):
    if action == 'post_add':
        __copy_addition_to_users(users=pk_set, instance=instance)


text:
Q: MySQL: join where not equal to I want to write a query that displays photos that user 5 did not like. Photos and likes are 2 tables joined by Photo_Id / Image_Id.
To display photos that user 5 did like I write:
Select
 wp_photos.Photo_Id
From
 wp_photos inner Join
 wp_photos_likes On wp_photos.Photo_Id = wp_photos_likes.Image_Id
Where
 wp_photos_likes.From_Id = 5
Group By
 wp_photos.Photo_Id

I would like a query that displays all photos that user 5 (From_Id) did not like.
Trying
 Where
  wp_photos_likes.From_Id <> 5

Does not work as other users liked photos that user 5 liked and so returns these as well.
I tried some left joins but with no success.
What's the correct query?

A: You can use a left join antipattern:
select p.photo_id
from wp_photos p
left join wp_photos_likes l
    on p.photo_id = l.image_id and l.from_id = 5
where l.image_id is null

This phrases as: check if each photo was liked by user 5, and filter on thoses who were not.
Another way to solve this is to use a not exists condition with a correlated subquery:
select p.photo_id
from wp_photos p
where not exists (
    select 1
    from wp_photos_likes l
    where p.photo_id = l.image_id and l.from_id = 5
)


text:
Q: meteor google service-configuration restriction to company emails i am building an Meteor App and using these packages for login/accounts:
accounts-base@1.3.6
accounts-password@1.4.2
accounts-google
service-configuration
I set up the service configuration like this:
ServiceConfiguration.configurations.upsert(
    { service: "google" },
    { $set: {
        clientId: "xxx.apps.googleusercontent.com",
        secret: "xxx"
    } }
);

Is it possible to restrict the emails?
If you have a company registered at google and they have their own email adresses like
peter_parker@companyname.com
is it Possible to just allow Login with google with googlemails from @companyname.com?
And if yes, where do i have to configure those?

A: I found the solution i was looking for in another thread
Limit Google Sign-In to .edu accounts in Meteor
_
Nevertheless many thanks


text:
Q: VLC - libvdpau error with intel graphics I am using archlinux trying to connect to an RTSP stream on my local network (local IP camera) and am getting very hit-and-miss performance from VLC. Most of the time the connection runs just fine, but sometimes the connection freezes and I have to close and reopen to resume. Running from the terminal shows the following:
VLC media player 2.2.4 Weatherwax (revision 2.2.3-37-g888b7e89)
[0000000000bbf1f8] dummy interface: using the dummy interface module...
Failed to open VDPAU backend libvdpau_nvidia.so: cannot open shared object file: No such file or directory
Failed to open VDPAU backend libvdpau_nvidia.so: cannot open shared object file: No such file or directory
[00007fa54800c618] avcodec decoder error: more than 5 seconds of late video -> dropping frame (computer too slow ?)
...
...
[00007fa54800c618] avcodec decoder error: more than 5 seconds of late video -> dropping frame (computer too slow ?)

This is obviously a bit off as this is an intel laptop with no nvidia components. I cannot figure out where/why it is looking for nvidia files (or if it is even relevant to the problem)
Running grep -iE 'vdpau|dri driver' ~/.local/share/xorg/Xorg.0.log yields:
[ 99171.065] (II) intel(0): [DRI2]   DRI driver: i965
[ 99171.065] (II) intel(0): [DRI2]   VDPAU driver: va_gl

Running vainfo yields:
libva info: VA-API version 0.39.4
libva info: va_getDriverName() returns 0
libva info: Trying to open /usr/lib/dri/i965_drv_video.so
libva info: Found init function __vaDriverInit_0_39
libva info: va_openDriver() returns 0
vainfo: VA-API version: 0.39 (libva 1.7.3)
vainfo: Driver version: Intel i965 driver for Intel(R) Ivybridge Mobile - 1.7.3
vainfo: Supported profile and entrypoints
  VAProfileMPEG2Simple            : VAEntrypointVLD
  VAProfileMPEG2Simple            : VAEntrypointEncSlice
  VAProfileMPEG2Main              : VAEntrypointVLD
  VAProfileMPEG2Main              : VAEntrypointEncSlice
  VAProfileH264ConstrainedBaseline: VAEntrypointVLD
  VAProfileH264ConstrainedBaseline: VAEntrypointEncSlice
  VAProfileH264Main               : VAEntrypointVLD
  VAProfileH264Main               : VAEntrypointEncSlice
  VAProfileH264High               : VAEntrypointVLD
  VAProfileH264High               : VAEntrypointEncSlice
  VAProfileH264StereoHigh         : VAEntrypointVLD
  VAProfileVC1Simple              : VAEntrypointVLD
  VAProfileVC1Main                : VAEntrypointVLD
  VAProfileVC1Advanced            : VAEntrypointVLD
  VAProfileNone                   : VAEntrypointVideoProc
  VAProfileJPEGBaseline           : VAEntrypointVLD

I've read the relevant arch wiki articles (I believe), but cannot get a stable connection. I have extra/libva, extra/libva-intel-driver, and extra/libva-vdpau-driver installed and this seems like it should do it... what am I missing?

A: I don't have enough reputation to comment.
After making sure your video drivers are up to date, try checking if any of the packages provide the file VLC is complaining about: pacman -Qi libva libva-intel-driver libva-vdpau-driver | grep libvdpau_nvidia.so. As Dmitry commented, make sure VA-API is selected as the hardware accelerated decoding setting, or try setting that to Auto.
Additionally, can you play the same stream with another player, such as mplayer or mpv?


text:
Q: ActionBarSherlock and Another Project's Have Conflicting Support Version 4 This is an error I know how to fix but its getting really annoying and happening every time close and then open eclipse again. I am in the process of making an Android app that uses the Action Sherlock library. I imported Action Sherlock into my workspace and my other project sees it as a library on its build path. However to successfully run my application and not get an error relating to a Jar Mismatch!, I need to uncheck the support version 4 contained from the Order and Export screen in the Action Sherlock project. After this the app runs successfully and works fine. However, if I close Eclipse and then open it, it seems like the build path somehow resets itself!? The support version 4 library that I had previous unchecked in the Action Sherlock project is checked again. Because of this the project won't run.
Is this some kind of a bug in Eclipse? I guess I could always delete the support library in Action Sherlock but I'm afraid to do this as it will break my app. Has anyone ever ran into this problem before or am I the only one?
Any answers or help would be greatly appreciated!

A: You should be able to copy your version of the support library over ActionBarSherlock's without any trouble. Then it won't matter if you check order and export because there won't be any conflicts between the jars.

A: Either delete the supportv4.jar from your project and use the one bundled in ActionBarSherlock, or update the supportv4.jar in ActionbarSherlock and then delete the one in your project. You see, the conflict arises because with ActionBarSherlock comes a version of the supportv4.jar, so your classpath has two versions of the same jar.


text:
Q: Java EE workflow web services There is any practical book or tutorial that explain to use Java EE with workflow and web services, if the reference you post contain the source code of the entire case study, it will be an asset.

A: Have a look into JBoss jBPM project: http://www.jboss.org/jbpm, its BPMN 2.0 compilant and has pretty good documentation


text:
Q: Woocommerce mini-cart ajax apply coupon I have been going in circles with this I have added an apply coupon field to mini-cart.php and am trying to get it to run without refreshing the whole page. Any suggestions would be amazing help.
functions:
function apply_coupon_code(){
    $coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
    WC()->cart->apply_coupon($coupon_code);
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );

Input:
<?php if (empty (WC()->cart->get_coupons())): ?>

<?php if ( wc_coupons_enabled() ) { ?>

        <form class="widget_shopping_cart_content" action="<?php echo $cart_url ?>" method="post">
            <?php } else { ?>
        <form id="apply-promo-code" class="widget_shopping_cart__coupon">
            <?php } ?>
            Promo Code:
                <input id="minicart-coupon" class="input-text" type="text" value="" name="coupon_code"/>
                    <button type="submit" id="minicart-apply-button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply', 'woocommerce' ); ?></button>
                    <?php do_action( 'woocommerce_cart_coupon' ); ?>
                    <?php do_action( 'woocommerce_cart_actions' ); ?>
            </form>
            <?php endif; ?>
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
    <span id="widget-shopping-cart-remove-coupon" class="mini_cart_coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
        Promo Code: <?php echo esc_attr( sanitize_title( $code ) ); ?>

            <?php $remove_url = $cart_url.'?remove_coupon='.$coupon->code; ?>
            <?php wc_cart_totals_coupon_html( $coupon ); ?>

<?php endforeach; ?>

jQuery:
    jQuery(document).on('click', 'button#minicart-apply-button', function() {

        var coupon = jQuery( 'input#minicart-coupon' ).val();
        var button = ( this );
        var data = {
            action: "apply_coupon_code",
            coupon_code: "coupon"
        };

       jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: wc_add_to_cart_params.ajax_url,
        data: data,
        success: function (response) {
                console.log(response);
            },
            error: function (errorThrown) {
                console.log(errorThrown);
            }
        });

    });

A: You can get the new mini cart HTML inside your ajax callback on the server and then return that as a response to the jQuery ajax call then simply replace the whole mini cart HTML on the front-end with the updated HTML.
function apply_coupon_code(){
    $coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
    WC()->cart->apply_coupon($coupon_code);
    ob_start();
    woocommerce_mini_cart();
    $cart_html = ob_get_clean();
    return $cart_html;
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );

The output buffer is used here as woocommerce_mini_cart uses wc_get_template which just echoes out the content. The output buffer will allow you to capture this as a string.
Now you need to tell jQuery that you're expecting HTML back from the server...
jQuery(document).on('click', 'button#minicart-apply-button', function() {
    var coupon = jQuery( 'input#minicart-coupon' ).val();
    var button = ( this );
    var data = {
        action: "apply_coupon_code",
        coupon_code: "coupon"
    };

    jQuery.ajax({
        type: 'POST',
        dataType: 'html',
        url: wc_add_to_cart_params.ajax_url,
        data: data,
        success: function (response) {
                console.log(response);
         },
        error: function (errorThrown) {
                console.log(errorThrown);
        }
    });
});

Now response will have the new HTML for the mini-cart, so you can replace it using jQuery's html() function...
success: function (response) {
    console.log(response);
    jQuery('.mini-cart-wrapper').html(response);
},


text:
Q: Centering TikZ picture horizontally I've got some figures I'd like to use, but since the first one is larger than the second, the second gets placed relative to the lower edge of the first one.
My code:
\begin{figure}[h]
\centering
\begin{tikzpicture}[scale=0.9]
    \draw[->] (0, 0) -- (6, 0) node[right] {$z$};
    \draw[->] (0, 0) -- (0, 6) node[above] {$x$};
    \coordinate (a) at (5, 1);
    \node[fill=red, circle, scale=0.3, label=above:{$s$}] (s) at (5, 5) {};
    \node[fill=red, circle, scale=0.3, label=below:{$e$}] (e) at (1, 1) {};
    \draw (s) -- (e);
    \node[fill=red, circle, scale=0.3, label=above:{$m^*$}] (m*) at (2.293, 3.707) {};
    \node[fill=red, circle, scale=0.3, label=right:{$m$}] (m) at (3, 3) {};
    \draw (m) -- (m*);
    \draw[dashed] (s) -- (a) node[pos=0.5, label=right:{$\Delta x$}] -- (e) node[pos=0.5, label=below:{$\Delta z$}] {};
\end{tikzpicture}
\hspace{10mm}
\begin{tikzpicture}
    \coordinate (ayy) at (4.293, 1);
    \coordinate (mstar) at (4.293, 3.707);
    \coordinate (emm) at (7, 1);
    \node[fill=red, circle, scale=0.3, label=above:{$m^*$}] (m*) at (mstar) {};
    \node[fill=red, circle, scale=0.3, label=right:{$m$}] (m) at (emm) {};
    \node[fill=none, inner sep=0, outer sep=0] (a) at (ayy) {};
    \draw (m) -- (m*) node[pos=0.6, label=right:{$d$}] {};
    \draw[dashed] (a) -- (m*) node[pos=0.5, label=left:{$d\cos\alpha$}] {};
    \draw[dashed] (a) -- (m) node[pos=0.5, label=below:{$d\sin\alpha$}] {};
    \pic[draw, "$\alpha$", angle eccentricity=1.2, angle radius=7mm] {angle=ayy--mstar--emm};
\end{tikzpicture}
\caption{Calculating $m^*$ (Case 1)}
\end{figure}

What I currently have:

What I'd like to get:
:

A: Welcome! There are many ways, out of which I illustrate two:

*

*Use \vcenter. The perhaps simplest way to use it is to put it in math mode.

*Use only one picture and work with scopes.

In the second example, I simplified the code a bit by using polar coordinates, use the parser to parse coordinates, combine paths, and so on.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{angles,quotes}
\begin{document}
\begin{figure}[h]
\centering
$\vcenter{\hbox{\begin{tikzpicture}[scale=0.9]
    \draw[->] (0, 0) -- (6, 0) node[right] {$z$};
    \draw[->] (0, 0) -- (0, 6) node[above] {$x$};
    \coordinate (a) at (5, 1);
    \node[fill=red, circle, scale=0.3, label=above:{$s$}] (s) at (5, 5) {};
    \node[fill=red, circle, scale=0.3, label=below:{$e$}] (e) at (1, 1) {};
    \draw (s) -- (e);
    \node[fill=red, circle, scale=0.3, label=above:{$m^*$}] (m*) at (2.293, 3.707) {};
    \node[fill=red, circle, scale=0.3, label=right:{$m$}] (m) at (3, 3) {};
    \draw (m) -- (m*);
    \draw[dashed] (s) -- (a) node[pos=0.5, label=right:{$\Delta x$}]{}
     -- (e) node[pos=0.5, label=below:{$\Delta z$}] {};
\end{tikzpicture}}}
\hspace{10mm}
\vcenter{\hbox{\begin{tikzpicture}
    \coordinate (ayy) at (4.293, 1);
    \coordinate (mstar) at (4.293, 3.707);
    \coordinate (emm) at (7, 1);
    \node[fill=red, circle, scale=0.3, label=above:{$m^*$}] (m*) at (mstar) {};
    \node[fill=red, circle, scale=0.3, label=right:{$m$}] (m) at (emm) {};
    \node[fill=none, inner sep=0, outer sep=0] (a) at (ayy) {};
    \draw (m) -- (m*) node[pos=0.6, label=right:{$d$}] {};
    \draw[dashed] (a) -- (m*) node[pos=0.5, label=left:{$d\cos\alpha$}] {};
    \draw[dashed] (a) -- (m) node[pos=0.5, label=below:{$d\sin\alpha$}] {};
    \pic[draw, "$\alpha$", angle eccentricity=1.2, angle radius=7mm] {angle=ayy--mstar--emm};
\end{tikzpicture}}}$
\end{figure}

\begin{figure}[h]
\centering
\begin{tikzpicture}[bullet/.style={fill=red, circle, scale=0.3, label=#1}]
  \begin{scope}[scale=0.9]
    \draw[<->] (0, 6) node[above] {$x$} |- (6, 0) node[right] {$z$};
    \coordinate (a) at (5, 1);
    \node[bullet=above:{$s$}] (s) at (5, 5) {};
    \node[bullet=below:{$e$}] (e) at (1, 1) {};
    \draw (s) -- node[fill=red, circle, scale=0.3, label=right:{$m$}] (m){}  (e)
        (m) ++ (135:1)
        node[fill=red, circle, scale=0.3, label=above:{$m^*$}] (m*) {};
    \draw (m) -- (m*);
    \draw[dashed] (s) |- (e) node[pos=0.75,below] {$\Delta z$}
    node[pos=0.25,right](dx){$\Delta x$};
  \end{scope}
  \begin{scope}
    \path (dx)  ++ (3,{-1-1/sqrt(8)})  coordinate (a)
        ++ (0,{2+1/sqrt(2)})
        node[bullet=above:{$m^*$}] (m*) {}
        (a) ++ ({2+1/sqrt(2)},0)
        node[bullet=right:{$m$}] (m){};
    \draw (m) -- (m*);
    \draw[dashed] (m*)  --  node[left] (dc){$d\cos\alpha$} (a)
        -- node[below]{$d\sin\alpha$} (m);
    \pic[draw, "$\alpha$", angle eccentricity=1.2, angle radius=7mm]
    {angle=a--m*--m};
  \end{scope}
\end{tikzpicture}
\end{figure}
\end{document}

BTW, the usual format on this site is to provide complete minimal working examples (MWEs). These are codes that contain everything needed to be compiled, and start typically with \documentclass and end with \end{document}. In your case, I do not know what document class you are using, so I had to guess, and which packages you are loading (beyond those needed to make your snippet run through). You may very well already load something that has tools to solve your problem in another way.

A: Another possibility is align images at selected baseline . For example, with slightly modified code for images, the MWE is:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{angles,
                calc, % new
                quotes}

\begin{document}
    \begin{figure}[h]
    \tikzset{dot/.style = {circle, fill=red, minimum size=3pt, inner sep=0pt}}% new
\begin{tikzpicture}[baseline=(X.center)] % <---
% caxes
    \draw[->] (0,0) -- (6, 0) node[right] {$z$};
    \draw[->] (0,0) -- (0, 6) node[above] {$x$};
% triangle
\node (s) [dot, label=$s$]          at (5,5) {};
\node (e) [dot, label=below:{$e$}]  at (1,1) {};
\draw (s) -- node (m) [dot, label=right:$m$] {} (e);
\node (m*) [dot, label=$m^*$] at ($(m)!10mm!90:(s)$) {};
    \node[fill=red, circle, scale=0.3, label=right:{$m$}] (m) at (3, 3) {};
\draw (m) -- (m*);
\draw[dashed] (e) -| (s) node[pos=0.25, label=below:$\Delta z$] {}
                         node (X) [pos=0.75, label=right:$\Delta x$] {}; % <---
\end{tikzpicture}
    \hfill
\begin{tikzpicture}[baseline=(X.center)] % <---
\node (m*) [dot, label=above:$m^*$] {};
\node (m)  [dot, label=right:$m$]   at (3,-3) {};
\draw (m*) -- node[label=right:$d$] {} (m);
\draw[dashed] (m*) |- (m)   node (X) [pos=0.25, label=left:$d\cos\alpha$] {} % <---
                            coordinate[pos=0.5] (a)  % <---
                            node[pos=0.75, label=below:$d\sin\alpha$] {};
\pic[draw, "$\alpha$", angle eccentricity=1.2, angle radius=7mm] {angle=a--m*--m};
\end{tikzpicture}
\end{figure}
\caption{Calculating $m^*$ (Case 1)}
\end{document}


text:
Q: Intellij IDEA 2020.1 ultimate: Unable to add certificate to bundle jre I'm running into a strangeissue. I have this legacy multi module project and the "mvn clean package" is running successfully both from command line and using the intellij maven extension.
Anyway if I sync the project by using the same maven extension it fails and says that some dependency cannot be resolved and some maven plugin dependency too.....I cannot really understand what I did wrong and why syncing the project fails even if it builds and everything seems ok.
I'm on maven 3.6.3 (tried both my local instance and the bundled one with intellij idea)
jdk is 11 but the whole project is jdk 1.6 specified throught maven compiler plugin config (not my fault the java 1.6)
EDIT:
Forgot to mention. I have no compilation error, the error while doing sync on maven extension is "Could not transfer artifact xxx" from remote company artifactory repository (but it's working when doing mvn clean package from command line, and it's also in my local .m2 of course)
Here is the error I see when doing sync:
    Could not transfer artifact xml-apis:xml-apis:jar:1.3.02 from/to my.company.net (artifactory)
...
Caused by: java.lang.RuntimeException: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

But I already added my company certificat into  File | Settings | Tools | Server Certificates as reported here
And also to java cacert...
Even if I try specific plugin versions it doesn't work at all.
If I run the IDE by using a dedicated JDK (and add the certificate to it's cacert) it works....so basically I'm not able to add a certificate to the bundled jre

A: I fixed it by running the "Importing" with dedicated jdk.
Go to Settings | Build, Execution, Deployment | BuildTools | Maven | Importing/Runner
I will try to figure out if removeing the certificate from java cacert and using the provided UI (File | Settings | Tools | Server Certificates) on Intellij will provide the same outcome.

A: No, just use the built-in IntelliJ-IDEA plugin for trusting custom certs:
https://www.jetbrains.com/help/idea/settings-tools-server-certificates.html


text:
Q: How can I disable internal Airflow errors to be logged via sentry but still se DAG execution errors? I have enabled sentry [1.5.0] with apache airflow [Version 2.2.2] using following configuration in config file.
[sentry]
sentry_on: True
sentry_dsn: [DSN]
sentry_environment: dev

It seems to work just fine for all sort of errors. However Airflow internal errors like Error while health checking kube watcher process. Process died for unknown reasons, broken_pipe,ApiException: too old resource version etc are very frequent (close to 3k errors a day), which eats up my sentry quota very quickly.
While I am not sure how to fix those, I just want to disable those internal errors to be propagated via sentry and only trigger events for DAG execution errors/failures.
Note:The airflow executor I have set is KubernetesExecutor and my airflow is deployed in GKE.
Any help would be appreciated.


text:
Q: in a rebol function which gets a variable as argument, how to retrieve the original variable I'm debugging a script which doesn't behave like I wished;
I'm writing a small debug utility function, which would print the 'word followed by its value.
I wrote this:
debug: func [x] [print rejoin ['x " => " x] wait 0.5 ]

And, in my code, I'd like to call it simply like this:
phrase: "beer is good"
mots: parse phrase " "
debug phrase
    foreach mot mots [
    debug mot
    ;do something...
    ]

and I would dream that it would output on the console something like:
phrase => "beer is good"
mot => "beer"
mot => "is"
mot => "good"

but I can't find a way to retrieve the variable's original name, that is, its name out of the scope of the function.

A: If you look at your 'debug function and compare it to the source of '??, you'll see what you would have needed to do differently:
??: func [
    {Prints a variable name followed by its molded value. (for debugging)}
    'name
][
    print either word? :name [head insert tail form name reduce [": " mold name: get name]] [mold :name]
    :name
]

A: I had not searched enough...
?? variable

does what I needed.
>> ? ??
USAGE:
    ?? 'name

DESCRIPTION:
     Prints a variable name followed by its molded value. (for debugging)
     ?? is a function value.

ARGUMENTS:
     name -- (Type: any)


text:
Q: ONTouch event issues? Touching anywhere on screen the user should go to the next view in iphone application?
How can we implement this?

A: Sure you can Make use of this method of touches
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //Get all the touches.
    NSSet *allTouches = [event allTouches];

    //Number of touches on the screen
    if([allTouches count] > 0)
    {
//Navigate to next screen here likewise you generally do
    }
else
{

}

}

Good Luck!

A: Read UIResponder Class Reference for more details
For now you can implement the

*

*(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

method in your viewController class and load the otherViewController possibly by pushing over NavigationController.


text:
Q: Google reCAPTCHA: how to get only letters as a challenge I am using google reCAPTCHA version 2 in my project. It is working fine. But when I am checking the check box it is showing some set of images always as challenge. But I want to show only alphabets instead of images. How can I do that?

A: As far as I know, currently there is no such configuration available to restrict the different types of image challenges that would be presented to the end user. The only setting available is to choose whether audio / image CAPTCHA needs to be served.
The entire list of available configurations can be found here and you would notice that most of them are cosmetic settings.
There are many discussions in google groups similar to your requirements, but I don't think there is any solution available yet.


text:
Q: Can physicist estimate is it safe to walk/drive on ice? I'm curious about the following: Suppose that I know the the weather forecasts of a given place. How can I compute from that data whether or not it is secure to walk or drive by a car to an island.

A: Friction experiments are really difficult to carry out. You would have to know the material of the road. You'd have to define what is secure and what is not as well...
For instance, dust on the road changes a lot the friction coefficient. So I would answer: don't try to compute how secure it is to walk or drive given some weather forecast because your calculations will contain a lot of error.


text:
Q: Custom plugin with DOM manipulation CKEditor 4.x I am developing one custom plugin for the CKEditor 4.7 which do a simple think take in case user select some stuff it will put it in a div with specific class, else it will put a div with same class just with text like 'Add content here'
I try to use some functions according to CKEditor docs but have something really wrong.
here is the code for the plugin folder name=> customdiv, file=> plugin.js
CKEDITOR.plugins.add('customdiv', {
    icons: 'smile',
    init: function (editor) {

        editor.addCommand( 'customdiv',{
            exec : function( editor ){
                var selection = editor.getSelection();
                if(selection.length>0){
                    selection='
'+selection+'
';
                }else{
                     selection='
Add your text here
';
                }
                return {
                    selection
                };
            }
        });

        editor.ui.addButton( 'Customdiv',
        {
                label : 'Custom div',
                command : 'customdiv',
                toolbar: 'customdiv',
                icon : this.path + 'smile.png'
        });

        if (editor.contextMenu) {

            editor.addMenuGroup('divGroup');
            editor.addMenuItem('customdiv', {
                label: 'Customdiv',
                icon: this.path + 'icons/smile.png',
                command: 'customdiv',
                group: 'divGroup'
            });
            editor.contextMenu.addListener(function (element) {
                if (element.getAscendant('customdiv', true)) {

                }
            });
        }

    }
});

According to some docs it have to return the result good.
Also this is how I call them in my config.js file
CKEDITOR.editorConfig = function (config) {

    config.extraPlugins = 'templates,customdiv';
    config.allowedContent = true;
    config.toolbar = 'Custom';
    config.toolbar_Custom = [
        { name: 'divGroup', items: [ 'Customdiv' ] },

        {name: 'document', items: ['Source', '-', 'Save', 'Preview', '-', 'Newplugin']},
        /* MOre plugins options here */
    ];
};

Note: the official forum was close and moved here :(
UPDATE
I have change the function like this
exec : function( editor ){
          var selection = editor.getSelection();
          if(selection.length>0){
             selection='
'+selection+'
';
             CKEDITOR.instances.editor1.insertHtml( selection );
          }else{
             selection='
Add your text here
';
             CKEDITOR.instances.editor1.insertHtml( selection );
          }
      }

This makes it work for the else part, but still can't get the selected one.
UPDATE 2
After change of the if I can get data if is selected, but when I do insert selected between
 I face a problem.
var selection =   editor.getSelection();

give like result an object, and I funded out a more complex function and I get collected data like this
var selection = editor.getSelection().getNative();
alert(selection);

from this in alert I see the proper selection and not just object,but when I insert it like
CKEDITOR.instances.editor1.insertHtml('
' + selection + '
');

it just put all selected in one line and not adding the div, new div for else case working with this syntax.
UPDATE 3
The problem now  is this function
CKEDITOR.instances.editor1.insertHtml('
' + selection + '
');

it delete all existing HTML tags even if I add just selection without
 I am not sure if this is because of the way I insert data or way I collect data, just in alert when I collect data I see correct space like in the editor.

A:
user select some stuff it will put it in a div with specific class

If you want to check if selection is not empty, please instead of selection.length>0 try using !selection().getRanges()[0].collapsed.
If you need something more advanced you could also try using
!!CKEDITOR.instances.editor1.getSelection().getSelectedText() to see if any text was selected and !!CKEDITOR.instances.editor1.getSelection().getSelectedElement() to see if any element like e.g. image, tabl,e widget or anchor was selected.
EDIT:
If you need selected HTML please use CKEDITOR.instances.editor1.getSelectedHtml().getHtml();
Please also have a look at CKEditor documentation:

*

*https://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-getSelectedHtml

*https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dom_documentFragment.html#method-getHtml

*https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedText

*https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedElement


text:
Q: Learn playing guitar right from the mac? I am eager to learn playing guitar by the help of my MBP.
Is there a software around helping you to play mp3 files of your choice?
P.S: I know nothing about guitars and bought one out of sudden yesterday.

A: You can use GarageBand to learn guitar. If you have iLife 11 with the new version of GarageBand, it comes with basic guitar lessons.

A: Do you run linux on your MBP, too? Perhaps, you can test tuxguitar. It's something like GuitarPro, but open source. You can find tabs all over the web. You can open GuitarPro tabs with tuxguitar. It's is very good to learn guitar. If you run ubuntu, use apt-get to install.

A: You should give Capo a try http://supermegaultragroovy.com/products/Capo/ - it's pretty awesome! Lets you adjust a track's tuning to match your guitar e.g. if the track is dropped tuned and lets you slow a track right down while you practice playing along with it.


text:
Q: How can I use a C++11 to program the Arduino? How can I use C++11 when programming the Arduino?
I would be fine using either the Arduino IDE or another environment. I am most interested in the core language improvements, not things that require standard library changes.

A: As of version 1.6.6, the Arduino IDE enables C++11 by default.
For older versions, read on:
It is very easy to change the flags for any element of the toolchain, including the assembler, compiler, linker or archiver.
Tested on the Arduino IDE version 1.5.7 (released on July 2014),

*

*Locate the platform.txt file,

*

*AVR architecture => {install path}\hardware\arduino\avr\platform.txt

*SAM architecture => {install path}\hardware\arduino\sam\platform.txt

*Inside that file, you can change any flag, for instance,

*

*compiler.c.flags for changing the default compilation flags for C++ files.

*compiler.cpp.flags for changing the default compilation flags for C++ files.

*You can also change any of the "recipes" or compile patters, at the corresponding section of the configuration file, under the title "AVR/SAM compile patterns".

*After making the changes, you must restart the Arduino IDE, at least on version 1.5.7.

For instance,

To enable support for C++11 (C++0x), tested on Arduino IDE versions 1.5.7 and 1.5.8, you will simply add the flag "-std=gnu++11" at the end of the line starting with  compiler.cpp.flags=".

It is expected that C++11 is enabled by default in the near future on the Arduino IDE. However, as of version 1.5.8 (Oct 2014) it is still not the case.

A: Arduino IDE 1.6.6 and newer have C++11 enabled by default (they have the compiler flag "-std=gnu++11" set in the platform.txt file).

A: Firstly, only GCC 4.7 and above (and therefore AVR-GCC 4.7 and above) support C++11. So, check the versions installed with:
gcc --version
avr-gcc --version

If AVR-GCC is 4.7 or higher, then you may be able to use C++11.
The Arduino IDE does not support custom compiler flags. This has been requested, but has not yet been implemented.
So, you are left with having to use other environments or to compile your program directly from the command line.
In case, of compiling directly from the command line using AVR-GCC, you simply need to add an extra compiler flag for enabling C++11 support.
-std=c++11

For specific development environments, most would support editing of the compiler flags from the build options within the IDE. The above mentioned flag needs to be added to the list of flags for each environment.

C++0x was the name of working draft of the C++11 standard. C++0x support is available GCC 4.3 onwards. However, this is strictly experimental support so you cannot reliably expect C++11 features to be present. Here is the complete list of features available with the corresponding version of GCC. The availability of features in AVR-GCC will be the same as what's available in the corresponding GCC version.
The compiler flag for C++0x is:
-std=c++0x

A: Please, note, that there is no easy way to specify additional flags from Arduino IDE or use other IDE (Eclipse, Code::Blocks, etc.) or command line.
As a hack, you can use a small proxy program (should be cross-platform):
//============================================================================
// Name        : gcc-proxy.cpp
// Copyright   : Use as you want
// Description : Based on http://stackoverflow.com/questions/5846934/how-to-pass-a-vector-to-execvp
//============================================================================

#include <unistd.h>

#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

int main(int argc, char *argv[]) {
    vector<string> arguments;
    vector<const char*> aptrs;

    // Additional options, one per line
    ifstream cfg((string(argv[0]) + ".ini").c_str());
    if (cfg.bad())
        cerr << "Could not open ini file (you're using proxy for some reason, er?)" << endl;

    string arg;
    while (cfg) {
        getline(cfg, arg);
        if(arg == "\r" || arg == "\n")
            continue;
        arguments.push_back(arg);
    }

    for (const string& arg : arguments)
        aptrs.push_back(arg.c_str());

    for (int i = 1; i < argc; ++i)
        aptrs.push_back(argv[i]);

    // Add null pointer at the end, execvp expects NULL as last element
    aptrs.push_back(nullptr);

    // Pass the vector's internal array to execvp
    const char **command = &aptrs[0];

    return execvp(command[0], command);
}

*

*Compile the program.

*Rename the original avr-g++.exe to avr-g++.orig.exe (or any other name).

*Create avr-g++.ini file where the first line is FULL path to the original program (e.g. D:\Arduino\hardware\tools\avr\bin\avr-g++.orig.exe) and add additional parameters, one per line, as desired.

You're done!
Example avr-g++.ini:
D:\Arduino\hardware\tools\avr\bin\avr-g++.orig.exe
-std=c++0x

A: I use Ino and this worked:
ino build -cppflags="-std=c++0x"

This generated a hex file at least 15k in size (that's with optimizations turned on), compared to about 5k for the standard build, which is a consideration for a poor little ATmega328. It might be okay for one of the microcontrollers with a lot more program space.

A: If you need more control and a better IDE, I recommend using Sloeber Plugin for Eclipse or the Sloeber IDE itself.
Creating more complicated code is much easier using this IDE. It also allows to add flags to the compiler (C, C++ and linker). So to customize the compile, just right click on project and select Properties. In the Properties window, select Arduino → Compiler Option. This way you can add options to your build.


text:
Q: How to clean up this strange PHP code? this script outputs the birthdays as headlines and the customer(s) below.
So the output is "grouped" by the date of birth.
echo "
";

foreach(pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty)) as $row)
    {
        if(!isset($birthday) or $birthday != $row['birthday'])
            {
                unset($drawline);
                echo "
";
                echo "

".$row['birthday']."

";
            }

        if(isset($drawline)){echo "
";}

        echo $row['customer']."
";

        $drawline = 1;

        $birthday = $row['birthday'];
    }

echo "
";

'birthday' is a DATE-field in the database.
Between the customers there's always a line (hr), but not after the last customer of a d.o.b.
Example output:

1986-10-08

Don Foo

Joe Bar

1988-03-18

Jane Fonda

Elvis Burns

Is it possible to remove the
 and
 outside the foreach()?
It produces always an empty

.

A: I've decided that it's too much hassle on the programmer's mind to see what's happening here, so here is much cleaner version of your code.
<?php
$people = pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty));
if (!empty($people)) {
// Find out people with the same birthday and group them.
$birthdays = [];
foreach ($people as $man) {
    $birthday = $man['birthday'];
        if (empty($birthdays[$birthday])) {
            $birthdays[$birthday] = [];
        }
        $birthdays[$birthday][] = $man['customer'];
    }
// Now let's output everything!
?>

<?php foreach ($birthdays as $birthday => $customers): ?>

<?= $birthday ?>

        <?= implode('

', $customers) ?>

<?php endforeach;?>

<?php } // endif (!empty($people)) ?>

Main point of this solution - very simple to understand, uses somewhat templating (you could create one for this little snippet), easy to debug and modify. And yes, it does not output the empty

 anymore!


text:
Q: iPad Custom Font is there a way to load an own Font with the iPad SDK? I cannot find a useful example of what file-type the font has to be or how the LIB of the iPad is called.
Can you provide further informations?

A: Here is a very simple description what you have to do.

A: UIAppFonts (Array - iPhone OS) specifies any application-provided fonts that should be made available through the normal mechanisms. Each item in the array is a string containing the name of a font file (including filename extension) that is located in the application's bundle. The system loads the specified fonts and makes them available for use by the application when that application is run.
http://developer.apple.com/iphone/library/documentation/General/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html#//apple_ref/doc/uid/TP40009252-SW18
Ahead is a note from iPad Human Interface Guidelines
Note that fonts of type .ttf or .otf work on iPad; traditional Mac OS fonts (that is, Classic font suitcases) do not work on iPad.


text:
Q: How to fix flask.cli.NoAppException when running flask server I am currently taking CS50's Web Programming with Python and JavaScript class. I am trying to run a flask server however I am getting flask.cli.NoAppException error. I am trying to connect to a postGRES SQL database on heroku.

*

*Running Mac OX Mojave version 10.14.4 and using bash command line

*Able to connect to Adminer tool for project

*Able to connect to heroku and View Credentials to obtain URI for flask
environment

*Confirmed all required packages are installed with pip3 install -r v
requirements.txt

*Tried using home-brew to update SSL

*Tried Uninstalling psycopg2 library and installing psycopg2-binary library
with pip

import os

from flask import Flask, session
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

app = Flask(__name__)

# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set!!!")

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))

@app.route("/")
def index():
    return "Project 1: TODO"

Bash Command Prompt:
Stephens-MacBook-Pro:Project1 stephen$ export FLASK_APP=application.py
Stephens-MacBook-Pro:Project1 stephen$ export FLASK_DEBUG=1
Stephens-MacBook-Pro:Project1 stephen$ export DATABASE_URL="postgres://qipeqvvmvvcoqf:1c6aaa3504a58aa2b9be46b85d79a05159f5ccb1f64e3e27070a024a02c3b83e@ec2-174-129-208-118.compute-1.amazonaws.com:5432/d3lrnl0okcg99k"
Stephens-MacBook-Pro:Project1 stephen$ flask run
 * Serving Flask app "application.py" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 334-645-143

When I open http://127.0.0.1:5000/ I should see the text "Project 1: TODO"!
Error Screenshot

A: this happens usually when one or more packages are corrupted. try updating all packages using pip
use the following command
pip install -I --ignore-installed -r requirements.txt


text:
Q: class objects as data members and header file includes I'm currently putting together what I've learned of C++ by writing a small text adventure - just trying to get the basic class interrelations down so I can have the player move through a few rooms at the moment. I'm getting an 'expected unqualified id before '}' error in my room.h file when I compile.  I think it may have something to do with a Room class member which is a vector of Exit object pointers, but I'm not sure.  I'd appreciate a quick scan of the code just to let me know If I'm missing something obvious but important. Sorry if this gets complicated.  I'll try to be brief and to the point.
I'm not sure what you all may need to see (codewise) and I don't want to throw up the whole code so...Let me outline how I have things set up, to start off with.:
1) I have a cpp file, called from main(), which instantiates 21 new rooms on the heap
2) Followed by another cpp file which instantiates new Exit objects on the heap, pushes them onto a vector, and calls a Room.set() function to pass the vector of Exit pointers to the Room class as one of its data members.  Each exit in The vector will also have a pointer to one of the new Rooms created on the Heap.
The file to instantiate new rooms looks like this:
#include "RoomsInit.h"
#include "Room.h"

void InstantiateRooms()
{
    string roomName1 = "On a deserted beach";
    string roomDescr1 = "You are standing on a deserted beach. To the east, a "
                       "crystal blue ocean\n dances in the morning sun. To the "
                       "west is a dense jungle, and somewhere\n far off, you can "
                       "hear the singing of a strange bird. The white, sandy \n"
                       "beach runs out of sight to the north and south.\n\n\n";

    Room* p_deserted_beach = new Room(roomName1, roomDescr1);

* Only the roomName and roomDescr is passed to the constructor at this point...and there are 20 more rooms like this in the file.
The Exit instantiate file looks like this:
#include "exitsInit.h"
#include "exit.h"
#include "room.h"
#include "RoomsInit.h"

void InstantiateExits()
{

    vector<Exit*> exitVec;

    Exit* p_north1 = new Exit("north", p_on_the_beach_north, true, false);
    Exit* p_south1 = new Exit("south", p_on_the_beach_south1, true, false);
    Exit* p_east1 = new Exit("east", p_in_the_ocean, true, false);
    Exit* p_west1 = new Exit("west", p_in_the_jungle, true, false);
    exitVec.push_back(p_north1);
    exitVec.push_back(p_south1);
    exitVec.push_back(p_east1);
    exitVec.push_back(p_west1);

    (*p_deserted_beach).SetExitVec(exitVec);
    exitVec.clear();

The exitVec is created and sent to the Room class via the set function to become one of it's data members...There are 20 more sets of these in this file)one for each room).
My Room class header file, where I'm getting the compiler error, at the moment, looks like this:
#ifndef ROOM_H_INCLUDED
#define ROOM_H_INCLUDED

#include <iostream>
#include <string>
#include <vector>
class Exit;

using namespace std;

class Room
{
    private:
        string m_roomName;
        string m_roomDescr;
        string m_specDescr;
        bool m_isSpecDescr;
        vector<Exit*> m_exitVec;

    public:
        Room(string roomName, string roomDescr, string specDescr = "",
             bool isSpecDescr = false);

        string GetRoomName(); const
        string GetRoomDes(); const
        bool GetRoomSpecBool(); const
        string GetRoomSpec(); const

        void SetExitVec(vector<Exit*> exitVec);
        vector<Exit*> GetExitVec(); const

};

#endif // ROOM_H_INCLUDED

    -----------         with the corresponding cpp file:   --------------

#include "room.h"

Room::Room(string roomName, string roomDescr,
           string specDescr, bool isSpecDescr) :
       m_roomName(roomName), m_roomDescr(roomDescr),
       m_specDescr(specDescr), m_isSpecDescr(isSpecDescr) {}

string Room::GetRoomName() const
{
    return m_roomName;
}

string Room::GetRoomDes() const
{
    return m_roomDescr;
}

bool Room::GetRoomSpecBool() const
{
    return m_isSpecDescr;
}

string Room::GetRoomSpec() const
{
    return m_specDescr;
}

void Room::SetExitVec(vector<Exit*> exitVec)
{
    m_exitVec = exitVec;
}

vector<Exit*> Room::GetExitVec() const
{
    return m_exitVec;
}

---------The Exit class header is this:
#ifndef EXIT_H_INCLUDED
#define EXIT_H_INCLUDED

#include <iostream>
#include <string>
#include <vector>
class Room;   // For using a class pointer as a data member

using namespace std;

class Exit
{
    private:
        string m_exitName;  // east, west, etc
        Room* mp_exitTo;
        bool m_isExit;
        bool m_isExitHidden;
        bool m_isExitPhrase;
        string m_exitPhrase;

    public:
        Exit();
        Exit(string exitName, Room* pExit, bool isExit, bool isExitHidden,
             bool isExitPhrase = false, string exitPhrase = "");

        string GetExitName(); const
        Room* GetExitTo(); const
        void SetIsExitTrue();
        void SetIsExitFalse();
        bool GetIsExit(); const
        void SetIsExitHiddenTrue();
        void SetIsExitHiddenFalse();
        bool GetIsExitHidden(); const
        bool GetIsExitPhrase(); const
        string GetExitPhrase(); const

};

#endif // EXIT_H_INCLUDED

-------------and its cpp file:
#include "room.h"
#include "exit.h"
#include "RoomsInit.h"

Exit::Exit() :
           mp_exitTo(NULL), m_isExit(false), m_isExitHidden(false) {}

Exit::Exit(string exitName, Room* pExit, bool isExit, bool isExitHidden,
           bool isExitPhrase, string exitPhrase) :
           m_exitName(exitName), mp_exitTo(pExit), m_isExit(isExit),
           m_isExitHidden(isExitHidden), m_isExitPhrase(isExitPhrase),
           m_exitPhrase(exitPhrase)  {}

string Exit::GetExitName() const
{
    return m_exitName;
}

Room* Exit::GetExitTo() const
{
    return mp_exitTo;
}

void Exit::SetIsExitTrue()
{
    m_isExit = true;
}

void Exit::SetIsExitFalse()
{
    m_isExit = false;
}

bool Exit::GetIsExit() const
{
    return m_isExit;
}

void Exit::SetIsExitHiddenTrue();
{
    m_isExitHidden = true;
}

void Exit::SetIsExitHiddenFalse();
{
    m_isExitHidden = false;
}

bool Exit::GetIsExitHidden() const
{
    return m_isExitHidden;
}

bool Exit::GetIsExitPhrase(); const
{
    return m_isExitPhrase;
}

string Exit::GetExitPhrase() const
{
    return m_exitPhrase;
}

I'm also getting 21 warnings stating that the rooms I've created on the Heap are unused variables - not sure what that means.  I feel like I'm missing something about the #includes relationships that is crucial, but I just can't see what it is...I've only been programming for about 8 months and most of the examples I've come across in books or online are somewhat less complex than what I'm doing right now. And so, I'd really appreciate any advice or comments y'all who are more experienced might have.  Thanks.  -  Mark

A: In room.h
   string GetRoomName(); const
    string GetRoomDes(); const
    bool GetRoomSpecBool(); const
    string GetRoomSpec(); const

    void SetExitVec(vector<Exit*> exitVec);
    vector<Exit*> GetExitVec(); const

should be
   string GetRoomName() const;
    string GetRoomDes() const;
    bool GetRoomSpecBool() const;
    string GetRoomSpec() const;

    void SetExitVec(vector<Exit*> exitVec);
    vector<Exit*> GetExitVec() const;

You got your semi-colons in the wrong place.


text:
Q: Create 'Export As CSV' Button in Django on HTML Webpage I currently have a working Django application that has a view that outputs a dataframe and is rendered onto a HTML page. Now, I am trying to create a button on this HTML page that allows the user to download the rendered table to their local downloads folder.
How is this done? I am yet to figure it out after doing lots of research trying to get a table from views to HTML to downloaded as CSV.
Python code in views.py
results_html = results.to_html(index=False)
return render(request, 'output.html', {'results_html': results_html})

my current home.html code
<html lang="en-US">
   <body>
      <table>{{results_html|safe}}</table>
   </body>
</html>

I have looked into this and would like more clarification about where to type each thing. I am brand new to Django and still trying to figure out how each file interacts.


text:
Q: How to manage users and resources in a multiple server environment?
Possible Duplicate:
A system for distributing SSH public keys

Need help managing developer authentication on our system.  We have multiple CentOS servers (database, Web, Redis, etc.), and it is important to be able to control access to them in a centralized, (hopefully) simple manner.  What we use right now is the authorized_keys file, where we copy the key data from the keys our developers have generated.  This, however, is not so scalable and flexible, since we need to update several servers whenever someone enters / leaves the team.
One possibility we have available is to have a centralized file that gets copied to every server, before doing an sshd restart.  I am interested, however, in finding out if there is a better pattern or alternative way of doing this, before I invest the time implementing that.
What is the usual pattern for authenticating several users, particularly in a multi-server environment?  Bonus points for a solution that also lets us define some sort of role, to encapsulate access (i.e. front-end developers may not need to access the database servers, as a very contrived example).
Thanks very much!

A: I'll preface by saying that I don't administer a lot of Linux machines. Nearly all of my Customers have Active Directory, and I have had good success using pam_krb5 to authenticate SSH users against AD using Kerberos. Presumably you could deploy your own Kerberos infrastructure (in lieu of Active Directory) to accomplish something similar.


text:
Q: How do you map a Series to a dictionary? I have created a series from part of a database with the .value_counts() function.
Series1 = Jim      25
          Albert   36
          Sam      52
          Fiona    65

Now I'd like to map it to a dictionary i.e.
dic = {'Jim':    25,
       'Albert': 36,
       'Sam':    52,
       'Fiona':  65
       }

A: You can use the built in .to_dict() method on your Series.
Series1.to_dict()


text:
Q: Give me an example of why IP tries to route on a spanning tree I've been watching a talk given by Van Jacobson in which he casually claims that IP tries to route on a spanning tree, as not doing so results in loops which can quickly bring down a network.  He then goes on to say that one of the disadvantages here is lost capacity, because you end up removing some edges from your connectivity graph which represents idle links.
Intellectually, I understand the concept of a spanning tree and that when you add any edge to a spanning tree you create a cycle.  However, I'd still really like to see an example of how this plays out in practice with IP, in the context of the routing state that would develop at each node/lead to looping data.  Can anyone provide a small isolated example to clarify my understanding?

A: I think you are confusing a couple of things, let's see...

*

*Spanning-tree oriented network architecture is a property of the link layer and the link broadcast domain. More specifically, it often comes up in the context of Ethernet.

*An Ethernet segment must topologically be a tree, for otherwise you would immediately create broadcast cascades that would kill the medium. The problem at hand is that if you have several switches and connect them with lots of cables, you may have loops in your segment. A dedicated switching protocol such as STP can be used to disable ports such that only a tree-shaped topology remains open, and on loss of connectivity it can reopen one of the blocked ports. Thus by combining a redundant, loop-containing wiring with a spanning tree protocol one can achieve a level of physical redundancy.

*The theoretical capacity loss refers to the fact that the layout I described above is forced to shut off some ports and thus isn't using all available wires. But that isn't a disadvantage per se, just a limitation of the architecture. Ethernet was never designed as a reliable network (in the spirit of SDH/SONET), but rather as a cheap enterprise-size medium.

A: First, IP does not use a spanning tree.  And Van Jacobsen knows this very well, so there's some disconnect here.
Modern IP routing use the Shortest Path First algorithm, which computes a sink tree from each node in the network to every other node within the domain.  Every link gets used.  Yes, it's true that every sink tree will discard some of the links from graph, but that doesn't imply that the capacity is wasted, it's just used for other traffic.
A more sophisticated routing architecture would be load-sensitive and adjust to make use of that capacity, but the technology is not there to do that yet.  Previous attempts have resulted in oscillating networks and no one has applied control theory to routing yet.


text:
Q: Stub for a function in Nodejs not executing This is a call to a library function,
this.db.update(contactsCollection, ...query);

And this is the stub I wrote.
updateStub = sandbox.stub(preferencesController.db, 'update').resolves({ modifiedCount: 1 });

The stub executes successfully if I remove the spread (...) operator. But in the current scenario, it throws the following error - "found non-callable @@iterator"
Is there a different way to stub a function with variable number of arguments?


text:
Q: Is there a top to the map, and how do you know you've reached it? Is there at some point where you will hit some kind of roof on the map, making you unable to go higher?
If I was to stack boxes upon boxes to go higher and higher, would at some point I be stopped by an invisible force?
Or simpler, if I was to glitch and always go up, would at some point be stopped?
Also, if there's a top, how high is it?

A: There is in fact a top to the map.  People have used the magnesis flying trick and I would assume the Octoballoon flying trick to reach the top.
There are a number of videos on youtube showing these clever use of game mechanics.


text:
Q: Android AlarmManager: is there a way to cancell ALL the alarms set? I am building an app that set 2 alarms for each day of the week (at a certain hour and minute), the alarms repeat week after week forever.
Now the point is: if the user changes the alarms, I will need cancel the previously set alarms.
Is there a way to simply cancel all the alarms set by my application ?

A: I had same problem for cancelling alarms, and solved it. What you should do is simply do -

*

*When you create alarms, save request code of PendingIntent object (to shared preference).

*At later, when you want to cancel the alarm, create the same PendingIntent  with the same request code (obviously from shared preference).

*Call cancel() of AlarmManager and pass the PendingIntent object in it, and alarm will be cancelled.
private void cancelAlarm(int requestCode) {

AlarmManager alarmManager2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getApplicationContext(),requestCode,new Intent(this, MyBroadCastReceiver.class),0);
alarmManager2.cancel(pendingIntent2);

Toast.makeText(getApplicationContext(), "Alarm Cancelled - "+ requestCode, Toast.LENGTH_LONG).show();

}

A: if you are canceling previous alarms then in PendingIntent your flag should be PendingIntent.FLAG_CANCEL_CURRENT. It will prevent generating a new PendingIntent if it is already created. And make sure that before setting in alarm just cancel that same PendingIntent and after that set your alarm. You should try like this:
AlarmManager 2AlarmsInWeekAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService/getActivity(context, int, intent, PendingIntent.FLAG_CANCEL_CURRENT);

2AlarmsInWeekAlarmManager.cancel(pendingIntent);

and then you may use set or setRepeating method.
In your case it should be
2AlarmsInWeekAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, "timeInMillis", "repetitionTimeInMillis", pendingintent);

This guarantees that before setting an alarm will cancel all previously alarm with the same PendingIntent.
Hope you got this!

A: I think you could get an eye on : AlarmManager.Cancel
And on that Question/Answer: Android: Get all PendingIntents set with AlarmManager
As stated in there you can't ask to the AlarmManager to tell you what PendingIntent are in it. But I think you can make some PendingIntent similar to the one you want to cancel ;).


text:
Q: How to search for words with Sublime Text Package Control I installed Package Control for Sublime Text 3. Now I'm trying to install various other plugins but find the search function hard to handle because of a strange behaviour:
Instead of finding items that contain the word I enter, it finds items that contain the letters I enter in the order that I enter them. Like that, I get way too many hits, most of them irrelevant.
Is there a setting to fix this, or to search for words instead of letters?
Thank you!

A: That's how the command palette search works. As far as I know, there's no way to make it look for exact matches. The best advice I could offer is to continue typing the package name. Alternatively, if you know the names of all the packages you want, you can simply modify the Package Control.sublime-settings file in your User folder. Then restart the editor. I believe it will grab all of the packages that you want.


text:
Q: Rearrange numbers in the min and max form Given the following input
[1,2,3,4,5,6,7]

We are suppose to sort the numbers so that they are sorted as following
[7,1,6,2,5,3,4]

So i figured i can basically create a new list and use two pointers one starting at left most index and the other starting at right most index. Since the list is already sorted the right pointer gives me the max value and left gives me the min value. So i basically keep on adding values of max and min and update the left pointer to move right and the right pointer to move left. Following is my solution.
def maxMin(lst):
    result = []
    left = 0
    right = len(lst) - 1
    while left < right:
        result.append(lst[right])
        result.append(lst[left])
        left += 1
        right -= 1
    if len(lst) % 2 != 0:
        result.append(lst[left])
    return result

While this solution works apparently this uses extra space and there is a possible way to come up with a solution that uses only constant space. I came across this video on youtube but i had no idea how the author came up with the solution. To me understanding the arrival at solution is more important than the actual solution. I would love if someone can shed some light.

A: The extra space complained of is because you create a second list to hold the result. With a small amount of data that is an entirely reasonable way to go about it. But if your list had thousands of entries instead of a handful, then making a copy might not be feasible. In that case you might need to move the elements of the list in place.
We start by observing that the list is sorted and the elements in the last half of the list get moved to earlier in the list, at even-numbered positions (0, 2, 4). So, first calculate how many elements have to be shifted to earlier in the list. Then, for each of the elements to be shifted, calculate its new position (0, 2, 4) and move it there.
The first element to be shifted is at the end of the list. After it has been moved to an earlier point, the next element to be shifted is now at the end of the list. So the item to be moved is always the last in the list, and that can be extracted using pop().
Like this:
a = [1,2,3,4,5,6,7]
shifts = len(a)//2
for i in range(shifts):
    print(f"shifting {a[-1]} to position {i*2}")
    a.insert(i*2,a.pop())
print (a)

Output from the last print() call is [7, 1, 6, 2, 5, 3, 4]. The print() call inside the loop is simply there to show you what is happening.
This alternative way of doing it trades execution time for space. Every time you insert an element in a list, other than at the end, all of the subsequent elements have to be moved to the right to make room. That does a lot of processing behind your back, even though it is a single line of code.

A: There is a sort in place strategy that minimizes memory movements (I believe inserting in a list reallocates it internally).  It is based on a naive sort algorithm that swaps the value at each position with the subsequent position having the lowest value.  With a small adjustment to the logic, we can make the sort decide that each position will alternatively swap the lowest and highest value depending on whether the position is odd or even.
This sort-in place will perform N swaps and N*(N-1)/2 comparisons so the memory overhead will be minimal and there will be no reallocation.
def updownSort(a):
    for i in range(len(a)-1):         # for each position except the last one
        p=i                           # identify the swapping position (p)
        for j in range(i+1,len(a)):        # only look in remaining positions
            if bool(i&1) == (a[p]>a[j]):   # alternate seeking the largest and smallest value
                p = j
        a[p],a[i] = a[i],a[p]              # make the swap with the index that was found

a =  [1,2,3,4,5,6,7]

updownSort(a)
print(a)
# [7, 1, 6, 2, 5, 3, 4]

Note that any other "sort in place" algorithm (e.g. bubble sort) could be adapted in the same fashion as long as the comparisons can take into account the positions being compared in addition to the values.


text:
Q: How to combine estimated confidence intervals I have sampled a set of expert on their 90% CI for a set of questions. How can I combine their answers? How confident can I be in the result?
|---------------------------------------|
|     Question 1                        |
|---------------------------------------|
|         | Lower bound  | Upper bound  |
|         | (95% chance  | (95% chance  |
|         |  value is    |  value is    |
| Expert  |  higher)     |  lower)      |
|---------|--------------|--------------|
|  A      | 130          |  627         |
|  B      | 202          |  584         |
|  C      | 186          |  648         |

Ideally, I'd like to understand what my lower and upper bounds are likely to be and how confident I should be in these bounds.

A: This might be easier if you commit to taking a Bayesian approach (which you pretty already have). There is a rich literature on methods to elicit and combine distributions for use as subjective priors. See a few examples linked below to get you started:
https://projecteuclid.org/download/pdfview_1/euclid.ba/1346158771
https://www.sciencedirect.com/science/article/pii/S1364815213002533


text:
Q: Getting the value of an invisible column on row bound in a GridView I have an ASP.NET GridView control in a Web Form. For the sake of simplicity, I will say that this GridView is defined as follows:
<asp:GridView ID="myGridView" runat="server" AutoGenerateColumns="false"
  AllowPaging="true" AllowSorting="true" PageSize="50"
  OnRowDataBound="myGridView_RowBound" DataKeyNames="ID"
  OnLoad="myGridView_Load" OnPageIndexChanging="myGridView_PageIndexChanging"
  OnSorting="myGridView_Sorting">

  <Columns>
    <asp:BoundField DataField="ID" Visible="false" />
    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
    <asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
  </Columns>
</asp:GridView>

When each of these rows is bound (a.k.a. during the "myGridView_RowBound" event), I want to get the ID, Name, and Age values. My problem is, I cannot figure out how to get the "ID" value. The reason why is because it is in an invisible field. Can someone tell me how to get the value

A: You can either hide the cell after the data is bound (onrowcreated) or deal with the binding to hide the column.
Check this article for more info.

A: On your row data bound event you can get access to the ID via the bound data item. There is no need to interact with the columns.
For example in the row data bound event you might have.
void myGridView_RowBound(Object sender, GridViewRowEventArgs e)
{

    if(e.Row.RowType == DataControlRowType.DataRow)
    {

        var item = e.Row.DataItem as T;
        // where T is your item type

        if (item != null) {
           var id = item.ID;
        }

     }

}


text:
Q: Wordpress constantly running out of memory My Wordpress installation on a shared hoster is constantly running out of memory:
The error pops up at seemingly random, for example when uploading photos or sometimes without doing anything just browsing the Admin area.
It is a very fresh installation (with little content and traffic), I receive this error no matter which Theme and which plugins I use.
I already added these lines to my config:
.htaccess
php_value memory_limit 128M

wp_config.php
define('WP_MEMORY_LIMIT', '128M');
define( 'WP_MAX_MEMORY_LIMIT', '256M' );

My PHP Limit seems sufficient:
PHP Memory Limit:
memory_limit    512M    512M

HOWEVER after all this my memory monitor plugin still says:
WordPress Memory Limit: 40M

Do I have to do anything else to apply these changes?

A: Try
memory_limit = 128M
in php.ini. Your syntax may be wrong.
You can run a function called phpinfo to see what kind of memory allocation you really have. Make a plain text file and call it phpinfo.php and put just this line in it:
<?php phpinfo(); ?>
then put the file in the root of your server, and then go to that file with your web browser, i.e. mydomain.com/phpinfo.php
You'l see all the php info you need; scroll down for memory settings. If you get an error, that means your web hosting company won't allow phpinfo to run for security reasons.
But that will tell you what the real memory settings are and if your host is being honest. If they are, ask them how to bump memory for your account. If you only see a memory limit of 40 megs, than you're not able to change it due to their restrictions.


text:
Q: mod_rewrite - Rules don't work together, but work fine on their own Thanks in advance.
What I am trying to do is rewrite anything with the word "assets" and simply tack on the /projects/ to the beginning. Then rewrite everything else to my index.php file.
So,
/phantom-hearts/assets/pdf/cabbot-story.pdf
/allyson-darke/assets/jpg/image1.jpg
becomes
/projects/phantom-hearts/assets/pdf/cabbot-story.pdf
/projects/allyson-darke/assets/jpg/image1.jpg
Then, rewrite everything else to my index.php file.
Here is my .htaccess file
Code:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#rewrite project assets
RewriteCond %{REQUEST_URI} !/assets$
RewriteRule (.*)/assets(.*) projects/$1/assets$2 [L]

#rewrite everything else
RewriteRule .*          index.php/$0    [PT,L,NC]

Both of these rules work fine on their own and this file works in a few htaccess online testers I've tried, but when I try them on my localhost, I get Internal Server Errors.
Any ideas? What am I missing? Thanks a lot.

A: You can use:
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#rewrite project assets
RewriteCond %{REQUEST_URI} !/assets
RewriteRule (.*)/assets(.*) projects/$1/assets$2 [L]

#rewrite everything else
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L,NC]


text:
Q: Why am I getting an infinite loop? My output prints positive or negative repeatedly. Why am I getting an infinite loop? I used the following:
include iostream
using namespace std;

int main()
{
    int num;

    cout<<"enter number"<<endl;
    cin>>num;

    while(num!=0)
    {
        if(num>0)
            cout<<"positive"<<endl;
        else
            cout<<"negative"<<endl;
    }

    return 0;
}

A: Because you have while(num!=0) and there's nothing that may alter its value in the loop.

A: The value of num doesn't change in the body of the loop.

A: You should change the value of num inside the loop, because the condition of the while-loop will never become false.

A: You need to read the value while in the loop too. If you don't then num won't change and will remain forever the same and hence you either get an infinite loop or nothing (for num==0)
{int num;

cout<<"enter number"<<endl;
cin>>num;

while(num!=0)
{
    cout<<"enter number"<<endl;
    cin>>num;

    if(num>0)
        cout<<"positive"<<endl;
    else
        cout<<"negative"<<endl;
}
return 0; }

A: This is because of the logic of your code. You first read a number from standard input and then construct a while loop based on a condition that the number not equals 0. So if the value of num supplied via a standard input is not equal to 0 you program will repeat the body of the loop again and again.
In this code the while loop itself is not needed. If just wanted to print a message to user based on whether the num is positive/negative, you could just leave the if / else part and get rid of the while loop like this:
    using namespace std;
    int main() {

    int num;

    cout<<"enter number"<<endl;
    cin>>num;

    while(num!=0)
    {
        if(num>0)
            cout<<"positive"<<endl;
        else
            cout<<"negative"<<endl;
    }

    return 0;
}

Another possiblity would be the user opportunity to enter the num multiple times and break the while loop on certain condition like this:
using namespace std;
int main() {

int num;

do {
cout<<"enter number"<<endl;
cin>>num;
   if(num>0)
        cout<<"positive"<<endl;
    else if(num < 0)
        cout<<"negative"<<endl;
} while(num!=0);

return 0;

}
Here the loop will finish if the num equals to 0. You could also explicitly break out of the loop with break statement based on some condition.

A: Based on madflame991's answere here is an improved version :)
include iostream
using namespace std;

int main()
{
    int num;

    do
    {
        cout<<"enter number"<<endl;
        cin>>num;

        if(num>0)
            cout<<"positive"<<endl;
        else
            cout<<"negative"<<endl;
    }while(num!=0);

    return 0;
}


text:
Q: Read bookmarks in outlook MSG file with C# My goal is to somehow be able to read bookmarks in an outlook .msg file, then replace them with a different text. I want to do this with C#.
I know how to access the body and change the text, but was wondering if there was a way to access directly the list of all the bookmarks and its location so that i can easily replace them, instead going through the whole body text, splitting it up, etc etc...
edit: this is how a bookmark window looks like from this window one can assign bookmarks, but it should be possible to obtain this list via c#.

Any relevant info is appreciated.
Thanks in advance.

A: Since Outlook most often uses Word as it's body editor - you need to add a project reference to Microsoft.Office.Interop.Word.dll and then access to the Outlook Inspector's WordEditor during the Inspector.Activate event. Once you have access to the Word.Document - it's trivial to load up the Bookmarks and access/modify their values.
Outlook.Inspector inspector = Globals.ThisAddIn.Application.ActiveInspector();
((Outlook.InspectorEvents_10_Event)inspector).Activate += () =>
{   // validation to ensure we are using Word Editor
    if (inspector.EditorType == Outlook.OlEditorType.olEditorWord && inspector.IsWordMail())
    {
        Word.Document wordDoc = inspector.WordEditor as Word.Document;
        if (wordDoc != null)
        {
            var bookmarks = wordDoc.Bookmarks;
            foreach (Word.Bookmark item in bookmarks)
            {
                string name = item.Name; // bookmark name
                Word.Range bookmarkRange = item.Range; // bookmark range
                string bookmarkText = bookmarkRange.Text; // bookmark text
                item.Select(); // triggers bookmark selection
            }
        }
    }
};


text:
Q: Why does cv.glmnet give me different coefficient estimates even if I specify the same lambda? library(glmnet)
library(MASS)

set.seed(1)
x <- mvrnorm(n = 200, mu = c(0, 0, 0), Sigma = diag(3))
y <- rnorm(200, 4, 2)

mod1 <- cv.glmnet(x = x, y = y, lambda = c(0, 0.1), alpha = 1, standardize = FALSE)
mod2 <- cv.glmnet(x = x, y = y, lambda = NULL, alpha = 1, standardize = FALSE)
> coef(mod1, s = 0)
4 x 1 sparse Matrix of class "dgCMatrix"
                     s1
(Intercept)  3.79180178
V1          -0.08206827
V2          -0.01223013
V3           0.16707533
> coef(mod2, s = 0)
4 x 1 sparse Matrix of class "dgCMatrix"
                     s1
(Intercept)  3.79182932
V1          -0.08145740
V2          -0.01161146
V3           0.16631192

I'm running 2 LASSO models, mod1 and mod2. The only difference in the function call is that I set lambda = c(0, 0.1) for the first model, and lambda = NULL for the second. Next, I extract the coefficient estimates and noticed that the coefficients are slightly different between the two models, even though I specifically specified s=0.
Perhaps the cross-validation is leading to the small discrepancy in the estimates. So I tried just the plain glmnet function, without any cross validation.
mod3 <- glmnet(x = x, y = y, lambda = c(0, 0.1), alpha = 1, standardize = FALSE)
mod4 <- glmnet(x = x, y = y, lambda = NULL, alpha = 1, standardize = FALSE)
> coef(mod3, s = 0)
4 x 1 sparse Matrix of class "dgCMatrix"
                     s1
(Intercept)  3.79180178
V1          -0.08206827
V2          -0.01223013
V3           0.16707533
> coef(mod4, s = 0)
4 x 1 sparse Matrix of class "dgCMatrix"
                     s1
(Intercept)  3.79182932
V1          -0.08145740
V2          -0.01161146
V3           0.16631192

However, there's still a discrepancy in the coefficient estimates even though I specifically set s=0 when extracting the coefficient estimates through coef(mod3, s = 0) and coef(mod4, s = 0).


text:
Q: Golang return nil I am trying to wrap my head around Golang's types and interfaces but am struggling a bit to do so.  Anyways, a common pattern that I see is func Whatever() (thing string, err error).  I get how all of that works, but the one thing I am confused on is why it is ok to return "thing", nil.  The specific instance that I am looking at is in revel here-
func (c *GorpController) Begin() revel.Result {
    txn, err := Dbm.Begin()
    if err != nil {
        panic(err)
    }
    c.Txn = txn
    return nil
}

revel.Result is an interface with this signature-
type Result interface {
    Apply(req *Request, resp *Response)
}

Anyways, I am just curious how returning nil satisfies the compiler in that occasion.  Is there a resource that I can be pointed to for that?

A: This is similar to returning a nil error: see "Why is my nil error value not equal to nil? "

Under the covers, interfaces are implemented as two elements, a type and a value.
The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).
An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type.
If we store a pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil).
Such an interface value will therefore be non-nil even when the pointer inside is nil.

Here nil is the zero-value of the interface revel.Result.


text:
Q: SQL to search many to many relationship with acts_as_tsearch I'm using the acts_as_tsearch plugin for rails to do full text searching with Postgresql.
They give an example of multi table search here:
http://code.google.com/p/acts-as-tsearch/wiki/ActsAsTsearchMethod
But that only does a one-to-many relationship.  I'm trying to get it to also search a many-to-many relationship (has_and_belongs_to_many or habtm) for tags on a page.  But my SQL isn't advanced enough.
Here is what I've got so far:
  acts_as_tsearch :vectors => {
    :fields => {
      "a" => {:columns => ["pages.name"], :weight => 1.0},
      "b" => {:columns => ["pages.description"], :weight => 0.2},
      "c" => {:columns => ["tags.name"], :weight => 0.2}
    },
    :tables => {
      :tags => {
        :from => "tags INNER JOIN taggings ON tags.id = taggings.tag_id",
        :where => "((taggings.taggable_type = 'Page') AND (taggings.taggable_id = ???.id) AND ((taggings.context = 'tags')))"
      }
    }
  }

I'm not sure how to reference the page id (where I put the ???).
Thanks for your help!

A: Well, the SQL behind this would be:
select
    p.name,
    p.description,
    t.name
from
    pages p
    inner join taggings ts on
        p.page_id = ts.taggable_id
        and ts.taggable_type = 'Page'
        and ts.context = 'tags'
    inner join tags t on
        ts.tag_id = t.tag_id

So, your Ruby would look like:
acts_as_tsearch :vectors => {
  :fields => {
    "a" => {:columns => ["p.name"], :weight => 1.0},
    "b" => {:columns => ["p.description"], :weight => 0.2},
    "c" => {:columns => ["t.name"], :weight => 0.2}
  },
  :tables => {
    :tags => {
      :from => "pages p
        inner join taggings ts on
            p.page_id = ts.taggable_id
            and ts.taggable_type = 'Page'
            and ts.context = 'tags'
        inner join tags t on
            ts.tag_id = t.tag_id"
    }
  }
}

This is the standard way to get through a many-to-many table--just start at one table, join the mapping, and then join the other table. Voila! Many-to-many results!


text:
Q: How do i parse the deezer api in android i am trying to change my api from last.fm to deezer and it has been a hurdle for me. please help. below is my code and endpoints.
LAST.fm endpoint : http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=c3bbdcbc61af20f159e92612a56c4122&artist=ynw%20melly&track=suicidal&format=json
Deezer endpoint : http://api.deezer.com/search?q=Alan%20Walker%20-%20Darkside
JAVA CODE
static String parsingImageSong(String data) {
    if (!TextUtils.isEmpty(data)) {
        try {
            JSONObject mJsonObject = new JSONObject(data);
            if (mJsonObject.opt("track") != null) {
                JSONObject mJsTracks = mJsonObject.getJSONObject("track");
                if (mJsTracks.opt("album") != null) {
                    JSONObject mJsAlbum = mJsTracks.getJSONObject("album");
                    if (mJsAlbum.opt("image") != null) {
                        JSONArray mJsImgs = mJsAlbum.getJSONArray("image");
                        if (mJsImgs.length() > 0) {
                            for (int j = 0; j < mJsImgs.length(); j++) {
                                JSONObject mJsImg = mJsImgs.getJSONObject(j);
                                String sizeImg = mJsImg.getString("size");
                                if (sizeImg.equalsIgnoreCase("extralarge")) {
                                    return mJsImg.getString("#text").replace("300x300","3000x3000");
                                }
                            }

                        }

                    }
                }

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return null;
}

}


text:
Q: jquery replace div content with jsp file content i am trying to replace div content with jsp file content, but i get "Uncaught SyntaxError: Unexpected token ILLEGAL" error.
if the jsp file has one line it's working fine, but this issue happened when the jsp had multi lines.
test.jsp file:
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

123

dashboard.jsp file:

    dashboard

A: Try this code. i have use load function in jquery.
html page

        Existing content.

        Existing content.

try.jsp page(i don't know jsp so i just wrote below line in jsp file)
hi this is try