text:
Q: Remove slug from custom post type post URLs It seems that all web resources based on the subject of removing a custom post type slug ie
yourdomain.com/CPT-SLUG/post-name

are now very outdated solutions often referencing pre WP version 3.5 installs. A common one is to:
'rewrite'   => array( 'slug' => false, 'with_front' => false ),

within your register_post_type function. This no longer works and is misleading. So I ask the community in Q4 2020...
What are the modern and efficient ways to remove the Post Type Slug from a Custom Post Type post's URL from within the rewrite argument or anywhere else?
UPDATE:
There seems to be several ways to force this to work with regex. Specifically the answer from Jan Beck should you be consistently willing to monitor content creation to ensure no conflicting page/post names are created.... However I'm convinced that this is a major weakness in WP core where it should be handled for us. Both as an option/hook when creating a CPT or an advanced set of options for permalinks. Please support the track ticket.
Footnote: Please support this trac ticket by watching/promoting it: https://core.trac.wordpress.org/ticket/34136#ticket

A: The following code will work, but you just have to keep in mind that conflicts can happen easily if the slug for your custom post type is the same as a page or post's slug...
First, we will remove the slug from the permalink:
function na_remove_slug( $post_link, $post, $leavename ) {

    if ( 'events' != $post->post_type || 'publish' != $post->post_status ) {
        return $post_link;
    }

    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

    return $post_link;
}
add_filter( 'post_type_link', 'na_remove_slug', 10, 3 );

Just removing the slug isn't enough. Right now, you'll get a 404 page because WordPress only expects posts and pages to behave this way. You'll also need to add the following:
function na_parse_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }

    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'post', 'events', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'na_parse_request' );

Just change "events" to your custom post type and you're good to go. You may need to refresh your permalinks.

A: In response to my previous answer:
you could of course set the rewrite parameter to false when registering a new post type and handle the rewrite rules yourself like so
<?php
function wpsx203951_custom_init() {

    $post_type = 'event';
    $args = (object) array(
        'public'      => true,
        'label'       => 'Events',
        'rewrite'     => false, // always set this to false
        'has_archive' => true
    );
    register_post_type( $post_type, $args );

    // these are your actual rewrite arguments
    $args->rewrite = array(
        'slug' => 'calendar'
    );

    // everything what follows is from the register_post_type function
    if ( is_admin() || '' != get_option( 'permalink_structure' ) ) {

        if ( ! is_array( $args->rewrite ) )
            $args->rewrite = array();
        if ( empty( $args->rewrite['slug'] ) )
            $args->rewrite['slug'] = $post_type;
        if ( ! isset( $args->rewrite['with_front'] ) )
            $args->rewrite['with_front'] = true;
        if ( ! isset( $args->rewrite['pages'] ) )
            $args->rewrite['pages'] = true;
        if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
            $args->rewrite['feeds'] = (bool) $args->has_archive;
        if ( ! isset( $args->rewrite['ep_mask'] ) ) {
            if ( isset( $args->permalink_epmask ) )
                $args->rewrite['ep_mask'] = $args->permalink_epmask;
            else
                $args->rewrite['ep_mask'] = EP_PERMALINK;
        }

        if ( $args->hierarchical )
            add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
        else
            add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );

        if ( $args->has_archive ) {
            $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
            if ( $args->rewrite['with_front'] )
                $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
            else
                $archive_slug = $wp_rewrite->root . $archive_slug;

            add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
            if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
                $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
                add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
                add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
            }
            if ( $args->rewrite['pages'] )
                add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
        }

        $permastruct_args = $args->rewrite;
        $permastruct_args['feed'] = $permastruct_args['feeds'];
        add_permastruct( $post_type, "%$post_type%", $permastruct_args );
    }
}
add_action( 'init', 'wpsx203951_custom_init' );

You can see the add_permastruct call now doesn't include the slug anymore.
I tested two scenarios:

*

*When I created a page with the slug "calendar" that page is overwritten by the post type archive which also uses the "calendar" slug.

*When I created a page with the slug "my-event" and an event (CPT) with the slug "my-event", the custom post type is displayed.

*Any other pages do not work either. If you look at the picture above it becomes clear why: the custom post type rule will always match against a page slug. Because WordPress has no way of identifying if it's a page or a custom post type that does not exist, it will return 404. That's why you need a slug to identify either the page or CPT.
A possible solution would be to intercept the error and look for a page that might exist similar to this answer.

A: Background
Even after looking around everywhere, I couldn't find a proper solution for removing CPT slug from permalinks that actually works and is consistent with how WordPress actually parses requests. As it seems, everyone else looking for the same solution is in the same boat as me.
As it turns out, this is actually a two-part solution.

*

*Remove CPT slug from permalinks

*Instruct WordPress on how to find posts from the new permalinks

The first part is quite straightforward and many existing answers already have it right. This is what it looks like:
// remove cpt slug from permalinks
function remove_cpt_slug( $post_link, $post, $leavename ) {

    if ( $post->post_type != 'custom_post_type' ) {
        return $post_link;
    } else {
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
        return $post_link;
    }
}
add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );

Now, the second part is where things get ugly. After solving the first part, your CPT permalinks don't have CPT slugs anymore. But, now, the problem is WordPress doesn't know how to find your posts from those new permalinks because all it knows is CPT permalinks have CPT slugs. So, without a CPT slug in the permalink, it can't find your post. That's why when you make a request for your posts at this point, it throws a 404 not found error.
So, all you need to do now is instruct WordPress on how to find your posts using the new permalinks. But this is the part where existing answers don't do very well. Let's take a look at a few of those answers for example:
The below function works pretty well but it will only work if your permalink structure is set to Post name.
function parse_request_remove_cpt_slug( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }

    if ( ! empty( $query->query['name'] ) ) {
        global $wpdb;
        $cpt = $wpdb->get_var("SELECT post_type FROM $wpdb->posts WHERE post_name = '{$query->query['name']}'");

        // Add CPT to the list of post types WP will include when it queries based on the post name.
        $query->set( 'post_type', $cpt );
    }
}
add_action( 'pre_get_posts', 'parse_request_remove_cpt_slug' );

The below function works well for your custom post type regardless of the permalink structure however it will throw an error on all other post types.
function rewrite_rule_remove_cpt_slug() {

    add_rewrite_rule(
        '(.?.+?)(?:/([0-9]+))?/?$',
        'index.php?custom_post_type=$matches[1]/$matches[2]&post_type=custom_post_type',
        'bottom'
    );
}
add_action( 'init', 'rewrite_rule_remove_cpt_slug', 1, 1 );

There is another answer that is supposed to work as a standalone solution but ends up causing more issues than solutions like throwing errors in your CPT posts as well as on others. This one requires modifying the rewrite argument in your CPT registration as follows:
'rewrite' => array( 'slug' => '/', 'with_front' => false )

So far, all the existing answers I found are like the above ones. Either they work partially or don't work anymore. This is probably because WordPress doesn't give a streamlined way to remove CPT slug from custom post type permalinks and therefore these answers are either based on considering particular scenarios or based on a hacky way.
Answer
Here is what I have come up with while trying to create a solution that works on most if not all scenarios. This will properly remove CPT slug from CPT permalinks as well as instruct WordPress on finding CPT posts from those new permalinks. It doesn't rewrite rules in the database so you won't need to resave your permalink structure. Besides, this solution is consistent with how WordPress actually parses requests to find posts from permalinks which helps make it a more acceptable solution.
Make sure to replace custom_post_type with your own custom post type name. It appears once in every function so two occurrences in total.
// remove cpt slug from permalinks
function remove_cpt_slug( $post_link, $post, $leavename ) {

    if ( $post->post_type != 'custom_post_type' ) {
        return $post_link;
    } else {
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
        return $post_link;
    }
}
add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );

// instruct wordpress on how to find posts from the new permalinks
function parse_request_remove_cpt_slug( $query_vars ) {

    // return if admin dashboard
    if ( is_admin() ) {
        return $query_vars;
    }

    // return if pretty permalink isn't enabled
    if ( ! get_option( 'permalink_structure' ) ) {
        return $query_vars;
    }

    $cpt = 'custom_post_type';

    // store post slug value to a variable
    if ( isset( $query_vars['pagename'] ) ) {
        $slug = $query_vars['pagename'];
    } elseif ( isset( $query_vars['name'] ) ) {
        $slug = $query_vars['name'];
    } else {
        global $wp;

        $path = $wp->request;

        // use url path as slug
        if ( $path && strpos( $path, '/' ) === false ) {
            $slug = $path;
        } else {
            $slug = false;
        }
    }

    if ( $slug ) {
        $post_match = get_page_by_path( $slug, 'OBJECT', $cpt );

        if ( ! is_admin() && $post_match ) {

            // remove any 404 not found error element from the query_vars array because a post match already exists in cpt
            if ( isset( $query_vars['error'] ) && $query_vars['error'] == 404 ) {
                unset( $query_vars['error'] );
            }

            // remove unnecessary elements from the original query_vars array
            unset( $query_vars['pagename'] );

            // add necessary elements in the the query_vars array
            $query_vars['post_type'] = $cpt;
            $query_vars['name'] = $slug;
            $query_vars[$cpt] = $slug; // this constructs the "cpt=>post_slug" element
        }
    }

    return $query_vars;
}
add_filter( 'request', "parse_request_remove_cpt_slug" , 1, 1 );

Considerations:

*

*This solution intentionally leaves out Plain permalink structure from its scope as it isn't one of the pretty permalink structures. So, it will work with all permalink structures apart from the Plain one.

*As WordPress doesn't automatically prevent creating duplicate slugs across different post types, you may find problems accessing posts having the same post slugs because of losing uniqueness in CPT permalinks after removing the CPT slugs. This code doesn't include any functionality to prevent that behavior so you may want to find a separate solution to address that.

*In case there is a duplicate permalink, this code will prioritize your CPT over others and therefore display the post in your CPT when requested.

A: Write following code into the taxonomy registration.
'rewrite' => [
  'slug' => '/',
  'with_front' => false
]

Most important thing that you have to do after code changing
After you've altered your custom post type taxonomy document, try to go to Settings > Permalinks and re-save your settings, else you will get 404 page not found.

A: Looking through the answers here I think there is room for a better solution that combines some things I learned above and adds auto-detection and prevention of duplicate post slugs.
NOTE: Make sure you change 'custom_post_type' for your own CPT name throughout my example below. There are many occurrences, and a 'find/replace' is an easy way to catch them all. All of this code can go in your functions.php or in a plugin.
Step 1: Disable rewrites on your custom post type by setting rewrites to 'false' when you register the post:
register_post_type( 'custom_post_type',
    array(
        'rewrite' => false
    )
);

Step 2: Manually add our custom rewrites to the bottom of the WordPress rewrites for our custom_post_type
function custom_post_type_rewrites() {
    add_rewrite_rule( '[^/]+/attachment/([^/]+)/?$', 'index.php?attachment=$matches[1]', 'bottom');
    add_rewrite_rule( '[^/]+/attachment/([^/]+)/trackback/?$', 'index.php?attachment=$matches[1]&tb=1', 'bottom');
    add_rewrite_rule( '[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$', 'index.php?attachment=$matches[1]&feed=$matches[2]', 'bottom');
    add_rewrite_rule( '[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$', 'index.php?attachment=$matches[1]&feed=$matches[2]', 'bottom');
    add_rewrite_rule( '[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$', 'index.php?attachment=$matches[1]&cpage=$matches[2]', 'bottom');
    add_rewrite_rule( '[^/]+/attachment/([^/]+)/embed/?$', 'index.php?attachment=$matches[1]&embed=true', 'bottom');
    add_rewrite_rule( '([^/]+)/embed/?$', 'index.php?custom_post_type=$matches[1]&embed=true', 'bottom');
    add_rewrite_rule( '([^/]+)/trackback/?$', 'index.php?custom_post_type=$matches[1]&tb=1', 'bottom');
    add_rewrite_rule( '([^/]+)/page/?([0-9]{1,})/?$', 'index.php?custom_post_type=$matches[1]&paged=$matches[2]', 'bottom');
    add_rewrite_rule( '([^/]+)/comment-page-([0-9]{1,})/?$', 'index.php?custom_post_type=$matches[1]&cpage=$matches[2]', 'bottom');
    add_rewrite_rule( '([^/]+)(?:/([0-9]+))?/?$', 'index.php?custom_post_type=$matches[1]', 'bottom');
    add_rewrite_rule( '[^/]+/([^/]+)/?$', 'index.php?attachment=$matches[1]', 'bottom');
    add_rewrite_rule( '[^/]+/([^/]+)/trackback/?$', 'index.php?attachment=$matches[1]&tb=1', 'bottom');
    add_rewrite_rule( '[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$', 'index.php?attachment=$matches[1]&feed=$matches[2]', 'bottom');
    add_rewrite_rule( '[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$', 'index.php?attachment=$matches[1]&feed=$matches[2]', 'bottom');
    add_rewrite_rule( '[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$', 'index.php?attachment=$matches[1]&cpage=$matches[2]', 'bottom');
    add_rewrite_rule( '[^/]+/([^/]+)/embed/?$', 'index.php?attachment=$matches[1]&embed=true', 'bottom');
}
add_action( 'init', 'custom_post_type_rewrites' );

NOTE: Depending on your needs, you may want to modify the above rewrites (disable trackbacks? feeds?, etc). These represent the 'default' types of rewrites that would have been generated if you didn't disable rewrites in step 1
Step 3: Make permalinks to your custom post type 'pretty' again
function custom_post_type_permalinks( $post_link, $post, $leavename ) {
    if ( isset( $post->post_type ) && 'custom_post_type' == $post->post_type ) {
        $post_link = home_url( $post->post_name );
    }

    return $post_link;
}
add_filter( 'post_type_link', 'custom_post_type_permalinks', 10, 3 );

NOTE: You can stop here if you are not worried about your users creating a conflicting (duplicate) post in another post type that will create a situation where only one of them can load when the page is requested.
Step 4: Prevent duplicate post slugs
function prevent_slug_duplicates( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
    $check_post_types = array(
        'post',
        'page',
        'custom_post_type'
    );

    if ( ! in_array( $post_type, $check_post_types ) ) {
        return $slug;
    }

    if ( 'custom_post_type' == $post_type ) {
        // Saving a custom_post_type post, check for duplicates in POST or PAGE post types
        $post_match = get_page_by_path( $slug, 'OBJECT', 'post' );
        $page_match = get_page_by_path( $slug, 'OBJECT', 'page' );

        if ( $post_match || $page_match ) {
            $slug .= '-duplicate';
        }
    } else {
        // Saving a POST or PAGE, check for duplicates in custom_post_type post type
        $custom_post_type_match = get_page_by_path( $slug, 'OBJECT', 'custom_post_type' );

        if ( $custom_post_type_match ) {
            $slug .= '-duplicate';
        }
    }

    return $slug;
}
add_filter( 'wp_unique_post_slug', 'prevent_slug_duplicates', 10, 6 );

NOTE: This will append the string '-duplicate' to the end of any duplicate slugs. This code cannot prevent duplicate slugs if they already exist prior to implementing this solution. Be sure to check for duplicates first.
I would love to hear back from anyone else who gives this a go to see if it worked well for them as well.

A: and we can make some changes to above-mentioned function:
function na_parse_request( $query ) {

if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
    return;
}

if ( ! empty( $query->query['name'] ) ) {
    $query->set( 'post_type', array( 'post', 'events', 'page' ) );
}
}

to:
function na_parse_request( $query ) {

if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
    return;
}

if ( ! empty( $query->query['name'] ) ) {

    global $wpdb;
    $pt = $wpdb->get_var(
        "SELECT post_type FROM `{$wpdb->posts}` " .
        "WHERE post_name = '{$query->query['name']}'"
    );
    $query->set( 'post_type', $pt );
}
}

in order to set right post_type value.

A: For anyone reading this that had trouble with child posts like I did I found the best way was to add your own rewrite rules.
The main issue I was having was that WordPress treats the redirect from pages that are 2 levels (child posts) deep a little differently than it treats 3 levels deep (child of child posts).
That means when I have /post-type/post-name/post-child/ I can use /post-name/post-child and it will redirect me to the one with post-type in front but if I have post-type/post-name/post-child/post-grandchild then I can't use post-name/post-child/post-grandchild.
Taking a look into the rewrite rules it looks like it matches for things other than pagename at the first and second levels (I think the second level matches attachment) and then does something there to redirect you to the proper post. At three levels deep it doesn't work.
First thing you need to do is to remove the post type link from children as well. This logic should happen here if you look at Nate Allen's answer above:
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

Myself I used a mix of different conditionals to check if the post had children and whatnot in order to get to the right permalink. This part isn't too tricky and you'll find examples of people doing it elsewhere.
The next step though is where things change from the given answer. Instead of adding things to the main query (which worked for custom posts and their children but not the further children) I added a rewrite that went to the bottom of the WordPress rules so that if pagename didn't check out and it was about to hit a 404 it would do one last check to see if a page within the custom post type had the same name otherwise it would throw out the 404.
Here is the rewrite rule I used assuming 'event' is the name of your CPT
function rewrite_rules_for_removing_post_type_slug()
{
    add_rewrite_rule(
        '(.?.+?)(?:/([0-9]+))?/?$',
        'index.php?event=$matches[1]/$matches[2]&post_type=event',
        'bottom'
    );
}

add_action('init', 'rewrite_rules_for_removing_post_type_slug', 1, 1);

Hope this helps someone else, I couldn't find anything else that had to do with child of child posts and removing the slug from those.

A: I tried to figure this out not long ago and the short answer from what I know is no. Not from within the rewrite argument at least.
The long explanation becomes apparent if you look at the actual code of register_post_type in wp-includes/post.php line 1454:
add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );

You can see it prefixes $args->rewrite['slug'] to the %$post_type% rewrite tag. One could think "let's just set the slug to null then" until you look a few lines up:
if ( empty( $args->rewrite['slug'] ) )
    $args->rewrite['slug'] = $post_type;

You can see that the function always expects a slug value that is not empty and otherwise uses the post type.

A: Plugin Roundup
It's almost 2020 and a lot of these answers don't work. Here's my own roundup of the current options:

*

*Matt Keys answer seems to be the only one on the right track if you want a custom code solution. None of the plugins I found can do everything listed here, especially the duplicate checking. This approach seems like a really good opportunity for a plugin if anyone wanted to take that on.

*Permalink Manager Lite

*

* Best of the free plugins I tried.

* Gives full control over all Page/Post/CPT complete permalink structure and allows them to be the same. The GUI is by far the most feature-rich.

* Allows full override per-post as well and lets you see what the original/default would be and reset to the default if needed.

* Supports multi-site.

* Does not check for duplicates between post types, which is sad. If a page and a CPT have the same URL, the page loads and the CPT is inaccessible. No warnings or errors, you just have to do your own manual checking for duplicates.

* All taxonomy features are in the PRO version. The upgrade nags are pretty heavy.

*Custom Permalinks

*

* The free version does a lot. Taxonomy permalinks and premium support seem to be the only things withheld from the pro version.

* Allows you to change the full permalink for any individual page/post/CPT.

* Supports multi-site.

* Does not allow you to change the default structure so you your Custom Post Types will still be example.com/cpt-slug/post-title but you can change them individually.

* Does not check for duplicates between post types, which is sad.

*Custom Post Type Permalinks

*

* Allows non-developer users to change the things that are easy to change already with register_post_type

* Does not allow you to change the CPT base slug - only the part that comes after that - so pretty much useless for developers and the issue in this question.

*remove base slug... - dead for several years now... do not use.

A: This worked for me:
 'rewrite' => array('slug' => '/')

A: Had the same problems here and there seems to be no movement on wordpress site. In my particular situation where for single blogposts the structure  /blog/%postname%/ was needed this solution
https://kellenmace.com/remove-custom-post-type-slug-from-permalinks/
ended in a bunch of 404s
But together with this wonderful approach, which is not using the backend permalink strukture for the blogpost it finally works like charme.
https://www.bobz.co/add-blog-prefix-permalink-structure-blog-posts/
Thanks a bunch.

A: For me worked now:
'rewrite' => array(
'slug' => '/',
'with_front' => false
)

Insert inside register_post_type() function.

A: This is what worked for me. Replace podcast with your CPT slug:
add_action('init', function () {
    register_post_type(
        'podcast',
        [
            'rewrite' => false,
        ]
    );
});

add_filter('post_type_link', function ($post_link, $post, $leavename) {
    if (isset($post->post_type) && $post->post_type === 'podcast') {
        $post_link = home_url($post->post_name);
    }

    return $post_link;
}, 10, 3);

add_action('init', function () {
    add_rewrite_rule('(.+?)/?$', 'index.php?podcast=$matches[1]', 'bottom');
});

A: You dont need so much hard-code. Just use lightweight plugin:

*

*Remove Base Slug From Custom Post
It has customizable options.


text:
Q: Free product and direct sum of groups Let $\{G_\alpha\}$ be a collection of groups and $G$ be a group.
Can we interpret $(\oplus_\alpha G_\alpha)\ast G$ in terms of $G_\alpha \ast G$ and $G_\alpha \oplus G$?
Edit : At first glance, I thought that $(\mathbb{Z}\oplus\mathbb{Z})\ast\mathbb{Z}=\mathbb{Z}\ast\mathbb{Z}\ast\mathbb{Z}$.
But, I think that it is not true.

A: Your observation, that $(\mathbb{Z}\oplus \mathbb{Z})*\mathbb{Z}$ is isomorphic to $\mathbb{Z}*\mathbb{Z}*\mathbb{Z}$, is incorrect if by $*$ you mean the free product of groups. (If you mean the coproduct of abelian groups, then that is the same as the direct sum, so you aren't saying much).
To see this, note that in $H=\mathbb{Z}*\mathbb{Z}*\mathbb{Z}$ is the free group of rank $3$ (it is the coproduct of three copies of the free group of rank $1$), and therefore if $w,w'\in H$ commute, then they are both powers of the same element. But in $G=(\mathbb{Z}\oplus\mathbb{Z})*\mathbb{Z}$, the element $(1,0)$ and the element $(0,1)$, considered as elements of the free product, commute, even though there is no element of which they are both powers. So $G$ cannot be isomorphic to $H$.
In general, $\Bigl(\oplus_{\alpha} G_{\alpha}\Bigl)*G$ is a quotient of $\Bigl( *_{\alpha}G_{\alpha}\Bigr)*G$, which is, in turn, a quotient of $*_{\alpha}(G_{\alpha}*G)$. But I think that's about it. The free product of groups does not distribute over the direct sum, nor conversely.
Added. By the way: you had "direct product" in your title, but in your post you had the direct sum. Remember that when the index set is infinite, the direct sum is a proper subgroup of the direct product (and we don't usually use the $\oplus$ symbol except for abelian groups anyway); for arbitrary groups, not necessarily abelian, the subgroup of the direct product consisting of the elements with finite support is called the weak or restricted direct product.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use Linq to get the last order placed yesterday for each customer I have the following two POCO's
public class Customers
{
    public Guid Id { get; set; }
    public string FirstName{ get; set; }
    public string LastName{ get; set; }
}

and
public class Orders
{
    public Guid Id { get; set; }
    public Guid CustomerId { get; set; }
    public string Product { get; set; }
    public DateTime Date { get; set; }
}

Assuming my Data Service returns a List<Customers> and List<Orders>, how would I use Linq to get the last order placed yesterday for each customer?
I want to return Customer.Id, Customer.FirstName, Customer.LastName, Order.Id, Order.Date and Order.Product (as Json from a controller action), so would I need to also create a new POCO to hold results? something like the following:
public class CustomerOrders
{
    public Guid CustomerId {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public Guid OrderId {get;set;}
    public DateTime Date {get;set;}
    public string Product {get;set;}
}

I previously posted a similar question on using Linq to work with lists. I'm still learning Linq and these questions have me somewhat stumped. I'm hoping someone can help.

A: Try this:
var results = customers
    .Select(c =>
        orders
            .Where(o => o.CustomerId == c.Id)
            .Where(o => o.Date.Date == DateTime.Now.AddDays(-1).Date)
            .OrderByDescending(o => o.Date)
            .Select(o => new CustomerOrders()
            {
                Product = o.Product,
                Date = o.Date,
                CustomerId = c.Id,
                LastName = c.LastName,
                FirstName = c.FirstName,
                OrderId = o.Id
            })
            .First())
    .ToList();

Here is another version that handles the case where the customer does not have a corresponding order that meets the criteria:
var results = customers
    .Select(c =>
        orders
            .Where(o => o.CustomerId == c.Id)
            .Where(o => o.Date.Date == DateTime.Now.AddDays(-1).Date)
            .OrderByDescending(o => o.Date)
            .DefaultIfEmpty()
            .Select(o => new CustomerOrders()
            {
                Product = o == null ? default(string) : o.Product,
                Date = o == null ? default(DateTime) : o.Date,
                CustomerId = c.Id,
                LastName = c.LastName,
                FirstName = c.FirstName,
                OrderId = o == null ? default(Guid) : o.Id
            })
            .First())
    .ToList();

A: Probably Something like..
var res = from c in customers
          join o in orders on c.Id equals o.CustomerId
          where o.Id == (orders.Where(x=>x.CustomerId == o.CustomerId).OrderByDescending(x=>x.Id)).First().Id
          && DateTime.Compare(o.Date, DateTime.Now.AddDays(-1)) > 0
          select new CustomerOrders {
              CustomerId = c.Id, FirstName = c.FirstName, LastName = c.LastName,
              OrderId = o.Id, Date = o.Date, Product = o.Product
          };

P.S. I wrote it without compiling, you might get some errors, but I guess you got the point.


text:
Q: Linq searches for recent birthdays (within 15 days) How to use Linq
A table
Field Birthday
Linq searches for recent birthdays (within 15 days)
from a in Employee where a.PositionStatus == true select new{ a.Name,a.Birthday}

A: Try below query
var fromdate = DateTime.Now;
var todate = DateTime.Now.AddDays(15);
 var result =
 (
 from a in Employee
 where a.PositionStuats==true && a.DateOfBirth.Value.Month >= fromdate.Month &&
 a.DateOfBirth.Value.Month <= todate.Month &&
 a.DateOfBirth.Value.Day >= fromdate.Day && a.DateOfBirth.Value.Day <= todate.Day
 select new{ a.Name,a.Birthday}
 ).ToList();

Depending on your entity frame work version you can also replace a.DateOfBirth.Value.Month with a.DateOfBirth.Month.


text:
Q: Why is openshift oc new-app not using the --source-secret I provided? I am starting OS like this:
oc cluster up --public-hostname=julio-oc.10.238.41.233.nip.io

I also have a private github repo, configured with a deployment key, with only a trivial Dockerfile.
I then add the secret as follows:
oc secrets new-sshauth sleep-key-rsa --ssh-privatekey=/home/julio/.ssh/sleep-key_rsa

If I attempt to create the app, it fails:
> oc new-app --source-secret=sleep-key-rsa git@github-isl-01.ca.com:garju09/docker-sleep.git
error: Errors occurred while determining argument types:

git@github-isl-01.ca.com:garju09/docker-sleep.git as a Git repository URL:  Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

But if I add the key to the ssh agent, it now works:
> ssh-add ~/.ssh/sleep-key_rsa
Identity added: /home/julio/.ssh/sleep-key_rsa (/home/julio/.ssh/sleep-key_rsa)

> oc new-app --source-secret=sleep-key-rsa git@github-isl-01.ca.com:garju09/docker-sleep.git
--> Found Docker image 3fa8225 (2 weeks old) from Docker Hub for "centos:centos7"

    * An image stream will be created as "centos:centos7" that will track the source image
    * A Docker build using source code from git@github-isl-01.ca.com:garju09/docker-sleep.git will be created
      * The resulting image will be pushed to image stream "docker-sleep:latest"
      * Every time "centos:centos7" changes a new build will be triggered
      * WARNING: this source repository may require credentials.
                 Create a secret with your git credentials and use 'set build-secret' to assign it to the build config.
    * This image will be deployed in deployment config "docker-sleep"
    * The image does not expose any ports - if you want to load balance or send traffic to this component
      you will need to create a service with 'expose dc/docker-sleep --port=[port]' later
    * WARNING: Image "centos:centos7" runs as the 'root' user which may not be permitted by your cluster administrator

--> Creating resources ...
    imagestream "centos" created
    imagestream "docker-sleep" created
    buildconfig "docker-sleep" created
    deploymentconfig "docker-sleep" created
--> Success
    Build scheduled, use 'oc logs -f bc/docker-sleep' to track its progress.
    Run 'oc status' to view your app.

Why is new-app not using the --source-secret I specified?
UPDATE:
> oc version
oc v3.7.0+7ed6862
kubernetes v1.7.6+a08f5eeb62
features: Basic-Auth GSSAPI Kerberos SPNEGO

Server https://127.0.0.1:8443
openshift v3.7.0+7ed6862
kubernetes v1.7.6+a08f5eeb62

My primary source of information here was the following blog: https://blog.openshift.com/private-git-repositories-part-2a-repository-ssh-keys/
Please note that there is no password on the key and I tried various other permutations, including the following. The only thing that works for project creation is ssh-add. Curiously, once the project is created, I can empty the ssh-agent and OS builds with no problem:
oc secrets new-sshauth sleep-key-rsa --ssh-privatekey=/home/julio/.ssh/sleep-key_rsa
oc secrets link builder sleep-key-rsa
oc new-app --source-secret=sleep-key-rsa https://github-isl-01.ca.com/garju09/docker-sleep.git

But the above does not work because https requires authentication in our deployment.
oc secrets new-sshauth sleep-key-rsa --ssh-privatekey=/home/julio/.ssh/sleep-key_rsa
oc secrets link builder sleep-key-rsa
oc new-app git@github-isl-01.ca.com:garju09/docker-sleep.git

Failed as well.
UPDATE 2:
I created a github repo that replicates the problem and shows the script that I am using: https://github.com/julio-garcia-fc/docker-sleep
If you clone it and have oc 3.7 you should be able to run oc.sh and you can see it fail.

A: You need to say the builder service account can access your secret. See:

*

*https://blog.openshift.com/private-git-repositories-part-2b-repository-ssh-keys/
and all the other blog posts in that series.
The command you need is:
oc secrets link builder sleep-key-rsa


text:
Q: Place 2 PHP generated HTML tables side by side I have generated 2 HTML tables with PHP.  The first table is always ontop of the 2nd table. I can't seem to get them to be side by side.  the 2nd one is always under the first table.
I've also tried adding an html style of float left as well as inline in the html for the tables and it still doesn't come out side by side. Any help would be greatly appreciated!
    //add table for bids and asks
    function build_table($bidarray){
    // start table
    $html = '
';
    // header row
    $html .= '
';
    foreach($bidarray[0] as $key=>$value){
            $html .= '' . htmlspecialchars($key) . '	';
        }
    $html .= '
';

    // data rows
    foreach( $bidarray as $key=>$value){
        $html .= '
';
        foreach($value as $key2=>$value2){
            $html .= '' . htmlspecialchars($value2) . '	';
        }
        $html .= '
';
    }

    // finish table and return it

    $html .= '
';
    return $html;
}

$bidarray = array(
    array('Company'=>'cardsltd', 'Min Qty'=>'5', 'Max Qty'=>'10', '$/box'=>'5.00'),
);

$askarray = array(
    array('Company'=>'comp', 'Min Qty'=>'4', 'Max Qty'=>'9', '$/box'=>'4.00'),
);

echo build_table($bidarray) . build_table($askarray) ;

A: You need to use
s.
Take a

Put two
s in it containing a table each.

   ...

   ...

This will put your tables side by side.
Also, we can change/adjust/manage widths.
49% is just for demo purposes.

A: PHP Code:
//define class for table
$html = '

 ...';

CSS code:
 .half-width
    {
    position: relative;
    width: 100%;
    padding-right: 15px;  /*optional*/
    padding-left: 15px;   /*optional*/
    -ms-flex: 0 0 50%;
    flex: 0 0 50%;
    max-width: 50%;
   }

Also you can add float:right;width:50% for defined class (here class name is half-width)


text:
Q: Any experiment showing the "communication" between entangled particles is superluminal but not simultaneous OR simultaneous? Do the numerous experiments that demonstrate a violation of Bell's inequality also provide any data that the "communication" (I'm using that word for simplicity) between the entangled particles is superluminal but not simultaneous OR that such "communication" is indeed simultaneous?
I've looked at the papers of several of these experiments (e.g., Aspect et al. 1982, Tittel et al. 1998, Salart et al. 2008, Handsteiner et al. 2017, Rosenfeld et al. 2017), and as best as I can tell (I'm not a physicist), they don't present data that address this question (i.e., superluminal but not simultaneous versus simultaneous).  But I would like a second opinion because I'm not an expert. I just enjoy reading and learning about this.  I'm asking what—-if anything—-these (or other?) experiments tell us as relates to my question, not what QM would tell us.

A: No. The experiments do not show superluminal communication. When Alice performs her experiment on particle A, there is no observation or experiment which Bob can perform which will tell him anything about Alice's experiment, or even whether Alice has performed an experiment. Only later, when Alice and Bob get together and compare their results, do they find a correlation which violates Bell's inequality. All this tells them is that there is no classical explanation for the correlation they observe.
This can be understood because the quantum state describes an observer's knowledge of the particle, not the physical state of the particle (as illustrated in Schrodinger's cat and Wigner's friend). If Alice measures particle A, she acquires knowledge of particle B, causing Alice's wave function for particle B to collapse. This has no physical impact on particle B. Bob, who measures particle B, cannot detect Alice's result. Alice's wave function for particle B collapsed, but Bob's did not.
There are differences between quantum probability and classical probability, but the principle is the same. Quantum probability amplitudes (otherwise known as wave functions) allow us to calculate probabilities, where probability is an estimation of likelihood by an observer, not a description of physical reality.


text:
Q: What does the underscore positive sign mean outside a parentheses? I know this might be a simple question but in the equation $\sum(|y_i − w^T x_i − b| − \epsilon)_+$ does the underscore positive sign mean $(|y_i − w^T x_i − b| − \epsilon)>=0$ ?

A: It may mean the "positive part" of the expression.
Generally, one writes $f = f_+-f_-$, where $f_+$ is the positive part of $f$ and $f_-$ is the negative part of $f$. These are the values
$$f_+ = \tfrac12(|f| + f)$$
$$f_- = \tfrac12(|f| - f)$$
Note that these are both nonnegative.
If $f\geq 0$, then $f=f_+$.
If $f\leq0$, then $f = -f_-$.


text:
Q: Reading a CSV file with the getline() function is not working properly I'm working on an app in QT, and I'm kinda new to C++ I/O; I want to read some data from a CSV file that currently has 2 columns and some rows, for example: (1 | 10)  (2 | 20) I just want to store them in an array like this (1,10,2,20); for some, only values from the second column get stored in my array. Here is some code; I've checked many times, but I still can't see what I'm doing wrong:
void readingFiles::openFile(){

ofstream myFile;
myFile.open("/home/Dan/Desktop/mainFile.csv" ,std::ios::app);}

void readingFiles::addReadings(int readings1 , int readings2){

    if(myFile.is_open()){

            myFile<<readings1<<","<<readings2<<"\r";
            myFile.close();

}
}

vector<int> values ;
ifstream iFile;
iFile.open("/home/Dan/Desktop/mainFile.csv");}
string data;

void readingFiles::read(){
  for(int i =0; std::getline(iFile,data, ',') ; i++){
             values.insert(values.end() , atoi(data.c_str()));
             qDebug("vector list is %i" , values[i]);}
}

So, the result I get is that it reads the first row in the first column, then moves to read from the second column, and never goes back to the first (1, 10, 20, 30, 40 etc). Again, what I'm trying to get is (1, 10, 2, 20, 3, 30 etc.).

A: Your problem is that on second call getline is returning 10\n2. Then atoi converts this to 10. So you lose the 2. getline is supposed to discard newlines so I'm not sure why this is happening. It's a bit ugly, but parse 10\n2 in data to pick up anything after \n and add to vector.
I tested this with VC 2013 and that is the behaviour of getline with delimiter. I googled around and it does seem as if it is intended behaviour that getline with delimiter treats newline as a literal character. This works:
string line;
for (int i = 0; std::getline(myFile, line); i++)
{
    stringstream ss(line);
    for (int i = 0; std::getline(ss, data, ','); i++)
    {
        values.insert(values.end(), atoi(data.c_str()));
    }
}
for (int i = 0; i < values.size(); i++)
{
    cout << "vec=" << values[i] << endl;
}


text:
Q: Problems entering information in MySQL database I'm trying to introduce some data info in the DB on production mode but is not working I'm using PDO for the connection to the DB, in my localhost works correctly but in the GoDaddy server isn't.
I'm using MVC, when I submit I send the data by POST and in the controller is like this
when i make a submit i execute this

    $Registro = new ControladorUsuarios();
    $Registro -> ctrRegistroUsuario();

static public function ctrRegistroUsuario(){

    if (isset($_POST["regUsuario"])) {
        if (preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ.]+$/', $_POST["regUsuario"]) &&
          preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $_POST["regEmail"]) &&
          preg_match('/^[a-z0-9][a-z0-9.]+$/', $_POST["regPassword"])) {

          $encriptar = crypt($_POST["regPassword"], '//hash');

          $encriptarEmail = md5($_POST["regEmail"]);

          $datos = array(
            "usuario" => strtolower($_POST["regUsuario"]),
            "email" => strtolower($_POST["regEmail"]),
            "password" => $encriptar,
            "nombre" => strtolower($_POST["regNombre"]),
            "apellidos" => strtolower($_POST["regApellido"]),
            "telefono" => $_POST["regTelefono"],
            "verificacion" => $encriptarEmail
          );

          $tabla = "usuario";

          $respuesta = ModeloUsuarios::mdlRegistroUsuario($tabla, $datos);

          if ($respuesta == "ok") {

            /*===================================================================
            =            HERE I SEND A CONFIRMATION MAIL ACCOUNT           =
            ===================================================================*/

            $envio = $mail->Send();

            if (!$envio) {

              echo'error';

            } else {

              echo 'success';

            }

          }else{

            echo 'error2';

          }

        }
      }

    }

when i make a submit the error goes to error2 and in my model i have this
    public static function mdlRegistroUsuario($tabla, $datos){

      $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (usuario, email, password, nombre, apellidos, telefono, verificacion) VALUES (:usuario, :email, :password, :nombre, :apellidos, :telefono, :verificacion)");

      $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR);

      $stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR);

      $stmt->bindParam(":password", $datos["password"], PDO::PARAM_STR);

      $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR);

      $stmt->bindParam(":apellidos", $datos["apellidos"], PDO::PARAM_STR);

      $stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_STR);

      $stmt->bindParam(":verificacion", $datos["verificacion"], PDO::PARAM_STR);

      if ($stmt->execute()) {
        return "ok";
      } else {
        return errorinfo();
      }

      $stmt->close();

      $stmt = null;

    }

In my error_log appears this errors
    #0 route/Controladores/usuarios.controlador.php(33): ModeloUsuarios::mdlRegistroUsuario('usuario', Array)
    #1 route/registro.php(42): ControladorUsuarios::ctrRegistroUsuario()
    #5 {main}
      thrown in route/Modelos/usuarios.modelo.php on line 31

I really don't know what the problem is hope someone can help me


text:
Q: I want to call rest api in my function app azure using C# I am very new to C# and Azure. I want to call my rest api (I already have a REST API) from an Azure Function app.
I am able to call my API without Azure Function and below is the code. I have to do same in my function app .
var httpWebRequest = (HttpWebRequest)WebRequest.Create("**my url was here**");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers["Authorization"] = "Bearer **token**";

httpWebRequest.Method = "GET";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Please help me write the code for this. The requirement is call REST API in the Azure Function app and consume the returned JSON data.
The actual problem is I want to make Azure Function app which call/consume my REST API and read the JSON data.
Can I use above code in function app in http trigger? How?

A: Create an Azure http trigger function, and then put your code directly into it, you can refer to the following code:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Net;

namespace FunctionRestApi
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("URL");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers["Authorization"] = "Bearer **token**";

            httpWebRequest.Method = "GET";
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 |
             SecurityProtocolType.Tls;

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                log.LogInformation(result);
            }

            return new OkObjectResult("ok");
        }
    }
}

I did a test, and it worked well.


text:
Q: Adding an overlay color on hover to a background image I know this is a super basic concept but I'm going around in circles. I have a background image with text on top. So the image is the parent element. When the user hovers over the image, I want there to be a black gradient that is darker than the initial one I used, so that the image still shows and the text is still clear.
I have tried using z-index, only using background color, removing opacity. Just about everything. When I hover, the h1 and p text gets covered and the hover color is white/grey and not black.
This is the code I'm using for the hover:

.image {
    position: relative;
    width: 100%;
    max-width: 900px;
    margin: auto;
    background: linear-gradient(180deg, rgba(38, 36, 36, 0.47) 0%, rgba(38, 36, 36, 0) 100%), url(/assets/img/pictures/feature.png);
    background-size: cover;
}

.image:hover{
    box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
    background: rgba(0, 0, 0, 0.5);
    opacity: 0.4;
    }

Featured Page

Test

Am I missing something very obvious? Any help would be appreciated.

A: First: Image  is an empty tag. It has not closing tag and also does not need a slash at the end as it is an empty tag.
The easiest solution would be to use an overlay div that spans the entire block and will be displayed during hover. For that, use the same approach as the snippet below.
You add a box with the the attribute and value:
position: absolute; top: 0; bottom: 0; left: 0; right: 0;
Then you hide it with display: none; and using the :hover selector to change it to display: block; during hover.

.image {
  position: relative;
  width: 100%;
  max-width: 900px;
  margin: auto;
  background: linear-gradient(180deg, rgba(38, 36, 36, 0.47) 0%, rgba(38, 36, 36, 0) 100%), url(/assets/img/pictures/feature.png);
  background-size: cover;
}

.image .image-overlay {
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: none;
}

.image:hover .image-overlay {
  display: block;
}

Featured Page

Test


text:
Q: Send file to app with intents using Tasker Using the app "Total Commander" (Link) I can select a .csv file and 'Open with' my selected app, "My Budget Book" (Link - paid app). This opens up the app and promps the user if I want to import the data. I seek to do this, instead from Tasker.
One thing of note, which I find odd, I can't do it from my stock (Samsung S8+) file explorer?
tl;dr I need help recreating an intent for sharing a file to My Budget Book for import.
I contacted the developer of "My Budget Book" and they gave me this:
ImportCsvActivity:
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data
                android:mimeType="text/csv"
                android:pathPattern=".*\\.csv"
                android:scheme="content"
                tools:ignore="AppLinkUrlError"/>
            <data
                android:mimeType="text/csv"
                android:pathPattern=".*\\.CSV"
                android:scheme="content"
                tools:ignore="AppLinkUrlError"/>
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data
                android:host="*"
                android:mimeType="*/*"
                android:pathPattern=".*\\.csv"
                android:scheme="file"/>
            <data
                android:host="*"
                android:mimeType="*/*"
                android:pathPattern=".*\\.CSV"
                android:scheme="file"/>
        </intent-filter>

I have been trying to follow guides online using the Tasker Java actions but so far the most I can do is lauch the app on the 'Import CSV' page, but it doesn't prompt for import.
Using "Intent Intercept" (Link) I get this:
    intent:///storage/emulated/0/My%20Budget%20Book/TaskerImport_1584702040.csv#Intent;scheme=file;type=text/comma-separated-values;launchFlags=0x13100000;end
------------
ACTION: android.intent.action.VIEW
DATA: file:///storage/emulated/0/My%20Budget%20Book/TaskerImport_1584702040.csv
MIME: text/comma-separated-values
URI: intent:///storage/emulated/0/My%20Budget%20Book/TaskerImport_1584702040.csv#Intent;scheme=file;type=text/comma-separated-values;launchFlags=0x13100000;end
FLAGS:
FLAG_RECEIVER_FOREGROUND
FLAG_ACTIVITY_FORWARD_RESULT
FLAG_ACTIVITY_PREVIOUS_IS_TOP
FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY

------------
MATCHING ACTIVITIES:
Excel (com.microsoft.office.excel - com.microsoft.office.excel.excelMainActivity)
anWriter free (com.ansm.anwriter - com.ansm.anwriter.MainActivityFree)
Totalcmd-Editor (com.ghisler.android.TotalCommander - com.ghisler.android.TotalCommander.TCEditActivity)
Sheets (com.google.android.apps.docs.editors.sheets - com.google.android.apps.docs.editors.trix.quicksheet.QuickSheetDocumentOpenerActivityAlias)
CSV import (com.onetwoapps.mh - com.onetwoapps.mh.ImportCsvActivity)
QuickEdit (com.rhmsoft.edit - com.rhmsoft.edit.activity.MainActivity)

My current task:
Intent Testing (13)
    A1: Java Function [ Return:theIntent Class Or Object:Intent Function:new
{Intent} () Param:Intent.ACTION_SEND Param: Param: Param: Param: Param: Param: ]
    A2: Java Function [ Return: Class Or Object:theIntent Function:setAction
{Intent} (String) Param:android.intent.action.VIEW Param: Param: Param: Param: Param: Param: ]
    A3: Java Function [ Return: Class Or Object:theIntent Function:setClassName
{Intent} (String, String) Param:com.onetwoapps.mh Param:com.onetwoapps.mh.ImportCsvActivity Param: Param: Param: Param: Param: ]
    A4: Java Function [ Return: Class Or Object:theIntent Function:addFlags
{Intent} (int) Param:theIntent.FLAG_ACTIVITY_NEW_TASK Param: Param: Param: Param: Param: Param: ]
    A5: Java Function [ Return:parsedurl Class Or Object:Uri Function:parse
{Uri} (String) Param:file:///My Budget Book/TaskerImport_1584702040.csv Param: Param: Param: Param: Param: Param: ]
    A6: Java Function [ Return: Class Or Object:theIntent Function:putExtra
{Intent} (String, Parcelable) Param:android.intent.extra.STREAM Param:parsedurl Param: Param: Param: Param: Param: ]
    A7: Java Function [ Return: Class Or Object:CONTEXT Function:startActivity
{} (Intent) Param:theIntent Param: Param: Param: Param: Param: Param: ]

Edit: I need help recreating the intent for sharing a file, generated by Tasker, to My Budget Book for import.
Any help is greatly appreciated, thank you!

A: Solved using Tasker ADB Wifi action:
am start -a android.intent.action.VIEW -d file://%filepath -t text/comma/separated-values -n come.onetwoapps.mh/.ImportCsvActivity
'Spaces' in file path name need to be converted to '%20'


text:
Q: How to configure the JMS in Wildfly 10?Can not find the JMS menu under subsystem Currently I am writing a JMS sample application which runs on Wildfly 10. But I can not see the menu under which we can create JMS Queue in Subsystem of Admin console in wildfly 10. Please help me to locate the JMS menu in Wildfly 10 admin console.
I did the above things but i got some exception while starting the wildfly 10 server.Below is the exception :
 Failed to process phase INSTALL of subdeployment "JMS1-war.war" of deployment "dfc.ear"
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0092: No message destination with name JMS1-ejb.jar#jms/testingQ for binding java:module/env/jms/testingQ"},
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.deployment.unit."dfc.ear".deploymentCompleteService is missing [jboss.deployment.subunit."dfc.ear"."JMS1-ejb.jar".deploymentCompleteService, jboss.deployment.subunit."dfc.ear"."JMS1-war.war".deploymentCompleteService]",
        "jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean.HandleDelegate is missing [jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean]",
        "jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean.ValidatorFactory is missing [jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean]",
        "jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean.InstanceName is missing [jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean]",
        "jboss.deployment.subunit."dfc.ear"."JMS1-ejb.jar".INSTALL is missing [jboss.deployment.subunit."dfc.ear"."JMS1-war.war".deploymentCompleteService]",
        "jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean.InAppClientContainer is missing [jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean]",
        "jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean.ORB is missing [jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean]",
        "jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean.Validator is missing [jboss.naming.context.java.comp.dfc.JMS1-ejb.MDBBean]"

My wildfly standalone-full.xmlconfiguration is below:
<subsystem xmlns="urn:jboss:domain:messaging-activemq:1.0">
            <server name="default">
                <security-setting name="#">
                    <role name="guest" send="true" consume="true" create-non-durable-queue="true" delete-non-durable-queue="true"/>
                </security-setting>
                <address-setting name="#" dead-letter-address="jms.queue.DLQ" expiry-address="jms.queue.ExpiryQueue" max-size-bytes="10485760" page-size-bytes="2097152" message-counter-history-day-limit="10"/>
                <http-connector name="http-connector" socket-binding="http" endpoint="http-acceptor"/>
                <http-connector name="http-connector-throughput" socket-binding="http" endpoint="http-acceptor-throughput">
                    <param name="batch-delay" value="50"/>
                </http-connector>
                <in-vm-connector name="in-vm" server-id="0"/>
                <http-acceptor name="http-acceptor" http-listener="default"/>
                <http-acceptor name="http-acceptor-throughput" http-listener="default">
                    <param name="batch-delay" value="50"/>
                    <param name="direct-deliver" value="false"/>
                </http-acceptor>
                <in-vm-acceptor name="in-vm" server-id="0"/>
                <jms-queue name="ExpiryQueue" entries="java:/jms/queue/ExpiryQueue"/>
                <jms-queue name="DLQ" entries="java:/jms/queue/DLQ"/>
                <jms-queue name="testingQ">
                 <entry name="jms/testingQ"/>
                 <entry name="java:jboss/exported/jms/testingQ"/>
                </jms-queue>
                <connection-factory name="InVmConnectionFactory" connectors="in-vm" entries="java:/ConnectionFactory"/>
                <connection-factory name="RemoteConnectionFactory" connectors="http-connector" entries="java:jboss/exported/jms/RemoteConnectionFactory"/>
                <connection-factory name="testingQFactory" connectors="http-connector" entries="java:jboss/exported/jms/testingQFactory"/>
                <pooled-connection-factory name="activemq-ra" transaction="xa" connectors="in-vm" entries="java:/JmsXA java:jboss/DefaultJMSConnectionFactory"/>
            </server>
        </subsystem>

My Servlet code which produces and consumes the message is below:
private Message createJMSMessageForjmsTestingQ(Session session, Object
messageData) throws JMSException {
// TODO create and populate message to send
    TextMessage tm = session.createTextMessage();
    tm.setText(messageData.toString());
    return tm;
}

private void sendJMSMessageToTestingQ(Object messageData) throws
NamingException, JMSException {
    Context c = new InitialContext();
    ConnectionFactory cf = (ConnectionFactory)
c.lookup("java:comp/env/jms/testingQFactory");
    Connection conn = null;
    Session s = null;
    try {
        conn = cf.createConnection();
        s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
        Destination destination = (Destination)
c.lookup("java:comp/env/jms/testingQ");
        MessageProducer mp = s.createProducer(destination);
        mp.send(createJMSMessageForjmsTestingQ(s, messageData));
    } finally {
        if (s != null) {
            try {
                s.close();
             } catch (JMSException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close
session", e);
            }
        }
         if (conn != null) {
            conn.close();
        }
}

}
My Message Driven Bean is mentioned below :
   /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dfc.jms;

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.Message;
import javax.jms.MessageListener;

/**
 *
 * @author croushan
 */
public class MDBBean implements MessageDrivenBean, MessageListener {

    private MessageDrivenContext context;

    // <editor-fold defaultstate="collapsed" desc="EJB infrastructure methods. Click on the + sign on the left to edit the code.">

    /**
     * @see javax.ejb.MessageDrivenBean#setMessageDrivenContext(javax.ejb.MessageDrivenContext)
     */
    public void setMessageDrivenContext(MessageDrivenContext aContext) {
        context = aContext;
    }

    /**
     * See section 15.4.4 of the EJB 2.0 specification
     * See section 15.7.3 of the EJB 2.1 specification
     */
    public void ejbCreate() {
        // TODO Add code to acquire and use other enterprise resources (DataSource, JMS, enterprise bean, Web services)
    }

    /**
     * @see javax.ejb.MessageDrivenBean#ejbRemove()
     */
    public void ejbRemove() {
        // TODO release any resource acquired in ejbCreate.
        // The code here should handle the possibility of not getting invoked
        // See section 15.7.3 of the EJB 2.1 specification
    }

    // </editor-fold>

    public void onMessage(Message aMessage) {
        System.out.println("Message is :"+aMessage.toString());
    }

    }

Below is the ejb-jar.xml code :
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">
  <enterprise-beans>
        <message-driven>
            <display-name>MDBBeanMDB</display-name>
            <ejb-name>MDBBean</ejb-name>
            <ejb-class>dfc.jms.MDBBean</ejb-class>
            <transaction-type>Container</transaction-type>
            <message-destination-type>javax.jms.Queue</message-destination-type>
            <message-destination-link>jms/testingQ</message-destination-link>
            <activation-config>
                <activation-config-property>
                    <activation-config-property-name>acknowledgeMode</activation-config-property-name>
                    <activation-config-property-value>Auto-acknowledge</activation-config-property-value>
                </activation-config-property>
                <activation-config-property>
                    <activation-config-property-name>destinationType</activation-config-property-name>
                    <activation-config-property-value>javax.jms.Queue</activation-config-property-value>
                </activation-config-property>
            </activation-config>
        </message-driven>
        </enterprise-beans>
    <assembly-descriptor>
        <container-transaction>
            <method>
                <ejb-name>MDBBean</ejb-name>
                <method-name>*</method-name>
            </method>
            <trans-attribute>Required</trans-attribute>
        </container-transaction>
        <message-destination>
            <display-name>Destination for MDBBeanMDB</display-name>
            <message-destination-name>jms/testingQ</message-destination-name>
        </message-destination>
        </assembly-descriptor>
    </ejb-jar>

Thanks,
Chandan

A: Messaging is not included in the default standalone profile of wildfly 10. You can either switch to either standalone-full or standalone-full-ha profile or manually enable the corresponding subsystem messaging-activemq. For that you need to add extension:
<extension module="org.wildfly.extension.messaging-activemq"/>
and then the sub module config:
<subsystem xmlns="urn:jboss:domain:messaging-activemq:1.0">
    <server name="default">
        <security-setting name="#">
            <role name="guest" send="true" consume="true" create-non-durable-queue="true" delete-non-durable-queue="true"/>
        </security-setting>
        <address-setting name="#" dead-letter-address="jms.queue.DLQ" expiry-address="jms.queue.ExpiryQueue" max-size-bytes="10485760" page-size-bytes="2097152" message-counter-history-day-limit="10"/>
        <http-connector name="http-connector" socket-binding="http" endpoint="http-acceptor"/>
        <http-connector name="http-connector-throughput" socket-binding="http" endpoint="http-acceptor-throughput">
            <param name="batch-delay" value="50"/>
        </http-connector>
        <in-vm-connector name="in-vm" server-id="0"/>
        <http-acceptor name="http-acceptor" http-listener="default"/>
        <http-acceptor name="http-acceptor-throughput" http-listener="default">
            <param name="batch-delay" value="50"/>
            <param name="direct-deliver" value="false"/>
        </http-acceptor>
        <in-vm-acceptor name="in-vm" server-id="0"/>
        <jms-queue name="ExpiryQueue" entries="java:/jms/queue/ExpiryQueue"/>
        <jms-queue name="DLQ" entries="java:/jms/queue/DLQ"/>
        <connection-factory name="InVmConnectionFactory" entries="java:/ConnectionFactory" connectors="in-vm"/>
        <connection-factory name="RemoteConnectionFactory" connectors="http-connector" entries="java:jboss/exported/jms/RemoteConnectionFactory"/>
        <pooled-connection-factory name="activemq-ra" entries="java:/JmsXA java:jboss/DefaultJMSConnectionFactory" connectors="in-vm" transaction="xa"/>
    </server>
</subsystem>

In domain mode, the profiles full and full-ha have messaging enabled by default.


text:
Q: Formula typed in quill.js not rendering correctly in html I am typing math formulae in Quill.js (uses KaTeX) and rendering it as an html. However the formula seems to be rendering twice.
When I inspected the HTML, there are two span elements corresponding to each part. The correct one has class "katex-mathml" and another has the class "katex-html" with attribute "aria-hidden" set to true and still is visible on the page. What is going on here?

A: That's the default behavior of Katex. From https://katex.org/docs/options.html:
output: string. Determines the markup language of the output. The valid choices are:

html: Outputs KaTeX in HTML only.
mathml: Outputs KaTeX in MathML only.
htmlAndMathml: Outputs HTML for visual rendering and includes MathML for accessibility. This is the default.

Are you perhaps just missing to include the katex css?
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.13.16/dist/katex.min.css" integrity="sha384-6LkG2wmY8FK9E0vU9OOr8UvLwsaqUg9SETfpq4uTCN1agNe8HRdE9ABlk+fVx6gZ" crossorigin="anonymous">

Otherwise your options are:

*

*specify the katex option to only produce html or mathml (not both), or

*manually add a css rule katex-html { display: none; } (or analogously for mathml).


text:
Q: Function to count words So I have a task to write a program that counts how many words are in a string. The words can be separated by whitespace or any symbols.
The problem I have is that it's not passing one of my autotests.
The autotest input:
"Space... The final frontier... These are the voyages of the starship Enterprise. Its five-year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!"
The function for this example returns 32 instead of 38.
I have realized that there is a problem with my counter because it resets to 0. But I don't understand why it's doing that. How do I fix it?
int count_words(const char *str)

{

    int count=0;

    while(*str!='\0')

    {

       if((count!=0 && !isalpha(*str) && isalpha(*(++str))|| (count==0 && isalpha(*str))))

       {

           count++;

       }

       if(*str=='\0')

       break;

    str++;

    }

    return count;

}

A: You need to track whether you are currently "in a word" or not "in a word".  When you transition from "not in" to "in", then you can count another word.
int count_words(const char *str)
{
    int count = 0;
    bool inword = false;
    for( ; *str; str++ )
    {
        if( isalpha(*str) )
        {
            if( !inword )
                count ++;
            inword = true;
        }
        else
        {
            inword = false;
        }
    }
    return count;
}


text:
Q: Using values_list and extra on same queryset I have some existing code that calls values_list on a queryset. I need to add something using extra to this queryset. If I call extra before values_list the extra stuff is gone from the query after the values_list. If I call extra after the call to values_list it seems to have to effect - the extra stuff is not in the query.
Here is some debugger output. extra before values_list - it's there then gone:
-> queryset = queryset.extra(select={field['name'] : field['name']})
(Pdb) n
-> queryset = queryset.values_list(*self.get_search_columns())
(Pdb) print queryset.query
SELECT (top-bottom) AS `top-bottom`,  ....
(Pdb) n
-> data = list(queryset)
(Pdb) print queryset.query
SELECT `data_cst`.`image_measurer_id`, `data_cst`.`image_pr_top_id`,
`data_target`.`name`, `data_recipe`.`name`, `data_cst`.`ep`,
`data_lot`.`name`, `data_cst`.`date_time`, `data_cst`.`bottom` FROM
`data_cst` INNER JOIN `data_target` ON (`data_cst`.`target_name_id` =
`data_target`.`id`) INNER JOIN `data_recipe` ON
(`data_cst`.`recipe_id` = `data_recipe`.`id`) INNER JOIN `data_lot` ON
(`data_cst`.`lot_id` = `data_lot`.`id`) WHERE (`data_cst`.`date_time`
<= 2013-03-26 23:59:59  AND `data_cst`.`date_time` >= 2010-03-26
00:00:00 ) ORDER BY `data_cst`.`date_time` DESC

But if I reverse the order the extra doesn't make to the query at all:
-> queryset = queryset.values_list(*self.get_search_columns())
(Pdb) n
-> queryset = queryset.extra(select={field['name'] : field['name']})
(Pdb) print queryset.query
SELECT `data_cst`.`image_measurer_id`, `data_cst`.`image_pr_top_id`,
`data_target`.`name`, `data_recipe`.`name`, `data_cst`.`ep`,
`data_lot`.`name`, `data_cst`.`date_time`, `data_cst`.`bottom` FROM
`data_cst` INNER JOIN `data_target` ON (`data_cst`.`target_name_id` =
`data_target`.`id`) INNER JOIN `data_recipe` ON
(`data_cst`.`recipe_id` = `data_recipe`.`id`) INNER JOIN `data_lot` ON
(`data_cst`.`lot_id` = `data_lot`.`id`) WHERE (`data_cst`.`date_time`
<= 2013-03-26 23:59:59  AND `data_cst`.`date_time` >= 2010-03-26
00:00:00 ) ORDER BY `data_cst`.`date_time` DESC
{Pdb) n
-> data = list(queryset)
(Pdb) print queryset.query
SELECT `data_cst`.`image_measurer_id`, `data_cst`.`image_pr_top_id`,
`data_target`.`name`, `data_recipe`.`name`, `data_cst`.`ep`,
`data_lot`.`name`, `data_cst`.`date_time`, `data_cst`.`bottom` FROM
`data_cst` INNER JOIN `data_target` ON (`data_cst`.`target_name_id` =
`data_target`.`id`) INNER JOIN `data_recipe` ON
(`data_cst`.`recipe_id` = `data_recipe`.`id`) INNER JOIN `data_lot` ON
(`data_cst`.`lot_id` = `data_lot`.`id`) WHERE (`data_cst`.`date_time`
<= 2013-03-26 23:59:59  AND `data_cst`.`date_time` >= 2010-03-26
00:00:00 ) ORDER BY `data_cst`.`date_time` DESC

Is there some way to use both values_list and extra on same queryset?
Here's a very simple example showing it's not working:
(Pdb) CST.objects.all().extra(select={'ep': 1}).values_list('image_measurer_id')
[(86456L,), (86454L,), (86452L,), (86450L,), (86448L,), (86446L,),
(86444L,), (86442L,), (86440L,), (86438L,), (86436L,), (86434L,),
(86432L,), (86430L,), (86428L,), (86426L,), (86424L,), (86422L,),
(86420L,), (86418L,), '...(remaining elements truncated)...']

This should return 2 columns per row.

A: You'd need to include your extra select in the values_list.
E.g.
CST.objects.extra(select={'ep': 1}).values_list('image_measurer_id','ep')


text:
Q: Control flow and syntax errors with elif I am trying to create a program that executes the following:

*

*secret_num == generate a random # between 1-10

*ask user to guess this number between 1-10

*if guess == secret_num congratulate them and provide the number of guesses number_guesses it took (minus any duplicate guesses)

*account for duplicate guesses

*let them know if guess is too high or low

I know this is abc stuff for many of you but I am having typical new programmer problems with syntax, indentation and control flow. Right now I'm getting a syntax on the elif guess == secret num. Otherwise I cannot get this code to account for duplicates to save my life. I would appreciate any help. Thank you .
import random

def game():
# generate a random number between 1 -100 and initiate repeat guess list
    secret_num=random.randint(1,10)
# initiate duplicate list and number of guesses
    already_guesses = []
    number_guesses = 0

    while True:
# ask for user guess
        guess = int(input('Guess a number from 1-10> '))
# help with guesses and announce if it is correct number!
# catch someone if they submit the same number
        if guess in already_guesses:
            print ("You already guessed that number, try again")
        already_guesses.append(guess)
        number_guesses += 1
        elif guess == secret_num:
            print("whooohoo! you guessed it, my number is {}".format(secret_num))
            print("It took you {} guesses".format(number_guesses - len([already_guesses])))
            break
        elif guess < secret_num:
            print("You\'re getting hot, try a higher number")
        else:
            guess > secret_num
            print("You\'re cold, try a lower number")
# ask if they want to play again
    else:
        play_again = input("Do you wanna play again? y/n")
        if play_again != 'n':
            game()
        else:
            print("Bah Bye!")

game()

A: There are some other issues with your code as well (after indenting as mentioned in the comments):
import random

def game():
    # Generate a random number between 1-100 and initiate repeat guess list
    secret_num=random.randint(1,10)
    # Initiate duplicate list
    # Consider using a set instead so you don't have to cast it into a set later
    already_guesses = []

    while True:
    # Ask for user guess
        guess = int(input('Guess a number from 1-10> '))
        # Help with guesses and announce if it is correct number!
        # Catch someone if they submit the same number
        if guess in already_guesses:
            print ("You already guessed that number, try again")
        elif guess == secret_num:
            # Format your strings properly
            print("whooohoo! you guessed it, my number is {0}".format(secret_num))
            # See how many unique guesses there were and add the correct guess to it (+1)
            # To do so just use a set
            print("It took you {0} guesses".format(
                len(set(already_guesses))+1
            ))
            break
        elif guess < secret_num:
            print("You\'re getting hot, try a higher number")
        else:
            guess > secret_num
            print("You\'re cold, try a lower number")
        # Make sure to append the guess to the already_guessed list in any case, not just if the number is in already_guesses
        # If you only do that in your original if block, already_guesses will always remain empty
        already_guesses.append(guess)

    # Ask if they want to play again
    play_again = input("Do you wanna play again? y/n")
    if play_again != 'n':
        game()
    else:
        print("Bah Bye!")

game()


text:
Q: Non Ui/Main Thread is able to update ui android Why my app is able to access UI elements from a non UI thread? According to Android documentation, we can't access UI element in the non UI thread. The app is not crashed and the view is getting updated.
class MainActivity : AppCompatActivity() {

private  val TAG = "MainActivity"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val tv = findViewById<TextView>(R.id.tv)

    Thread(Runnable(){
        Log.i(TAG, Thread.currentThread().name)

        tv.text = "Hi"

    }).start()

A: You can never update the UI from any other threads except the MainThread/UiTHread. You can call a handler with looper.getMainLooper() which will create a handler in the main thread. Now you can update your UI within this.


text:
Q: ImportError.But i could run the **.py in command line,i couldn't run it in Pycharm I create a virtual env by anaconda and conda,then I have tried import the pandas
But the error I am getting:

File "E:/Py/Pynet/Pydata/d01.py", line 8, in
      import pandas as pd
      File "G:\Kits\Sword\Anaconda\envs\env4\lib\site-packages\pandas__init__.py", line 19, in
      "Missing required dependencies {0}".format(missing_dependencies))
      ImportError: Missing required dependencies ['numpy'],

the same code that i run have no problem in command line,but it have bug as above in pycharm,
why does the happen?

A: You need to point Pycharm to your virtualenv. See the official docs for more details: https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html.


text:
Q: Get alert on click datepicker date using jquery $(".setDate").on('change', 'input', function() {
      alert("s"); //Not working at all

});

$(".setFeastDate").click(function(){
      alert("s"); //Working but on click button
});

<input class="ft-date-picker-sm setDate" value="{{Carbon\Carbon::parse($some_date)->format('l, M j')}}" id="{{$some['id']}}" readonly="true"/>

*

*I expect it Should alert on selecting date not input field how could it possible pls suggest

A: Try:
$(".setDate").bind('change keyup', function() {
    alert("s");
});

A: Simply if you use JQuery  you can use 'onSelect' event like
 $("#datepicker").datepicker({
    dateFormat: 'dd M yyyy',
    onSelect: function(dateText){
         // write your logic here
        }
});

Ref: https://jqueryui.com/datepicker/
Try this:https://jsfiddle.net/1yugqnob/


text:
Q: My transaction keeps reverting even though i have funded it with more than enough eth. I am running it on a persistent ganache network with brownie My enter lottery function which charges 5 dollars won't transact successfully when I deploy it with brownie. It works fine on remix, but when i try making a script file to run it it keeps sending the error
 ValueError: Gas estimation failed: 'execution reverted: VM Exception while processing
 transaction: revert'. This transaction will likely revert. If you wish to broadcast, you
 must set the gas limit manually.

At first I tried creating a separate script file to run it but it send that error.I tried running it in my deploy script but it still doesn't work.
My deploy script
        from brownie import lottery, accounts, config, network,
        MockV3Aggregator, LinkToken, VRFCoordinatorMock
        from scripts.helpful import get_account, deploy_mocks,
        LOCAL
        from web3 import Web3

        value = Web3.toWei(0.04, "ether")

        def deploy_txn():
            account = get_account()
            print(f"owner is {account}")
            print(f"{network.show_active()} is the current network")
            if network.show_active() not in LOCAL:
                pfaddress = config[network.show_active()]["padress"]
                vrf = config[network.show_active()]["vrf"]
                link = config[network.show_active()]["link_token"]
                keyhash = config[network.show_active()]["keyhash"]
                fee = config[network.show_active()]["fee"]
            else:
                deploy_mocks()
                pfaddress = MockV3Aggregator[-1].address
                vrf = VRFCoordinatorMock[-1].address
                link = LinkToken[-1].address
                keyhash = '0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311'
                fee = '100000000000000000'

            caddr = lottery.deploy(vrf, pfaddress, link, keyhash, fee, {"from": account})
            print(caddr)

        def start_lottery():
            account = get_account()
            lottery[-1].startLottery({"from": account})

        def enter_lottery():
            account = get_account()
            lottery[-1].enter({"from": account, "value": value})

        def main():
            deploy_txn()
            start_lottery()
            enter_lottery()

My solidity enterLottery function
   function enter() payable public {
        require(ETHtoUSD(msg.value) >= usdfee, "Not enough ETH!");
        require(currentstate == lotteryState.open, "Lottery isn't open yet!");
        players.push(payable(msg.sender));
     }

the usdfee is $5 and I funded it with 0.04ETH($64)


text:
Q: Media Queries in React: How to pass a variable to size=full prop in  component const isMobile = useMediaQuery('(max-width:992px)');

Old Syntax:
<Drawer full={isMobile}></Drawer>

But acc to new changes, here: Rsuite

full is Deprecated. Use size="full" instead for Full screen

So, New Syntax would be:
 <Drawer size='full' ></Drawer>

In this case, how to pass the isMobile to Drawer component?

A: You can done with it like this

<Drawer size={ isMobile  ? 'full' : 'sm'} ></Drawer>


text:
Q: $x,y \in R^n,x^Ty \le 1, |y|_2 = 1$, can it be true that for some $i, x_i > 1$ and is it true that $|x|_2 \le 1$?
We have that for $x,y \in R^n,x^Ty \le 1, |y|_2 = 1$, can it be true that for some $i, x_i > 1$ and is it true that $|x|_2 \le 1$ ($|*|_2$-is the euclidian norm)?

$x_1y_1+x_2y_2+...+x_ny_n \le 1 = y_1^2+y_2^2+...+y_n^2$ I tried to get a contradiction assuming that $|x|_2 = x_1^2+x_2^2+...+x_n^2 \ge 1$. So, $y_1(x_1-y_1)+...+y_n(x_n-y_n) \le 0, x_1(x_1-y_1)+...+x_n(x_n-y_n) \ge 0$. However, I am stuck.
I also tried to do it with inner product and get $<x,y> = <x-y,y>+<y,y>$, since $<y,y> = 1, <x,y> \le 1$, then $<x-y,y> = 0$ so $x=y$.

A: Geometrically speaking, $|x^T y|$ only controls the length of the projection of $x$ in the direction of $y$. The length of $x$ itself can still be large. In fact, if $x\perp y$ and $x\neq 0$ (such a vector exists if $n\geq 2$), then $x^T y=0$, but $|x|_2$ can be made arbitrarily big by multiplying $x$ with a constant factor. Similarly, $x_i$ can be made arbitrarily big for some $i$.


text:
Q: Tomcat: redirect `domain.com` to `www.domain.com` I hv my spring app pon tomcat. How can i redirect example.com to www.example.com in Tomcat. I checked UrlRewriteFilter but it seems a bit complicated to me as it was not happening. any othet solution ?

A: Also you can use HttpRedirectFilter.

HttpRedirectFilter is a servlet which implements javax.servlet.Filter interface. It inspects the URL of a HTTP request and either forwards the request to a different location, or redirects the user agent to a new URL. It can be used as a general redirector on a servlet container such as Apache Tomcat.

A: It would probably be easier to just add an A record to your DNS that points www.example.com to the same address as example.com.  How you go about that depends on your registrar or host.

A: You should write a servlet to redirect your request from example.com to www.example.com using Servlet Filters.
Try this out-
      HttpServletResponse res = (HttpServletResponse) response;
      HttpServletRequest req = (HttpServletRequest) request;

        if (req.getServerName().equals("example.com")) {
            res.sendRedirect("http://www.example.com"+req.getRequestURI());
        }else{
            fc.doFilter(request, response);
        }


text:
Q: Kubernetes with a fixed hostname for pods we have a need for an external clients to connect to the POD via static hostname running on Kubernetes containers/sessions. The issue is that whenever we restart a session we get a new hostname generated for that container. Is there a way we can get a fixed hostname for the pods, such that it doesn't change every time we restart ??
$ kubectl get pods
NAME                                                              READY   STATUS             RESTARTS   AGE
anaconda-app-0072b5a97aad4bc5ba708a405609ad2e-74757d95fd-4cfms    2/2     Running            521        18d
anaconda-app-048b92d480d34da3a6602eace5f4c1c4-84d5669674-drx2c    1/2     CrashLoopBackOff   5086       77d
anaconda-app-0a529b10874e4c79a361050897bf3a00-64fdf8967f-ctc9z    2/2     Running            521        18d
anaconda-app-128b6866e59a408d937768835c04666c-5b774b8977-rhbp7    1/2     CrashLoopBackOff   5087       18d

If we can get a static name for the pods whenever the session is restarted that would be awesome, such that we can give one single static IP/hostname to the clienst?

A: consider running a statefulset with one replica. host name remains same for statefulset


text:
Q: How to find the right xlookup formula I am stuck on the right excel formula to use for my situation....
I have a spreadsheet A with that information:

IP

127.0.0.1

128.11.21.2

I have another spreadsheet B with that information:

IP
IP2
IP3
OS
Techno
Comment

127.0.0.1
127.0.0.1
212.22.23.25
Windows
Oracle
None

128.11.21.2
215.11.51.89
215.11.51.98
Linux
Java
Fix it

I would like to check if the information on the spreadsheet A (IP) are  in the spreadsheet B (IP, IP2, IP3)
if it is the case, I want to add the column OS, Techno and Comment liked to the same IP.
I used Xlookup but it didn't work...
Someone could guide me ?
Thanks,
ST

A: So, yet another (boring) example of the use of vlookup() and index() with match():

So an update to use the column headings, removed the if(0 with vlookup() but you can put that back:


text:
Q: Call to a member function record_count() on null codeigniter Trying to set up some pagination from a database that has a list of members in it. I had a query that returned the results but I could not incorporate it into the pagination example I found on the internet. Now i get a Call to a member function record_count() on null error when I try to load my memberlist. Below is the code.
Model
public function count_members()
{
    return $this->db->count_all("Users");
}

public function getMembers($limit, $start)
{
    $this->db->limit($limit, $start);
    $query = $this->db->get("users");

    if ($query->num_rows() > 0){
        foreach ($query->result() as $row) {
            $data[] = $row;
        }

        return $data;
    }
    return false;
    /*if ($id == null) {
        $query = $this->db->get('users');
    }else{
        $query = $this->db->get_where('users', ['id' => $id]);
    }
    return $query->result();  */
}

View

Member Listing

    First Name
    Last Name
    Email Address
    Status
    Last Login
    Delete
    Write Up

    <?php foreach ($members as $_key => $_value): ?>

    <?=$_value->first_name?>
    <?=$_value->last_name?>
    <?=$_value->email?>
    <?=$_value->status?>
    <?=$_value->last_login?>
    <a href="<?=site_url("admin/delete_member/{$_value->id}");?>">[X]

<?php endforeach;?>
<?php echo $links; ?>

<a href="<?php echo base_url(); ?>admin/home">Back to Dashboard

Controller
public function view_members()
    {
        $this->load->model('Users_model');
        $config = array();
        $config["base_url"] = base_url() . "admin/view_members";
        $config["total_rows"] = $this->Users->record_count();
        $config["per_page"] = 20;
        $config["uri_segment"] = 3;

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data["results"] = $this->Users->getMembers($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();

        //$this->data['members'] = $this->Users_model->getMembers();
        $this->load->view('admin/inc/admin_header');
        $this->load->view('admin/view_members', $this->data);
        $this->load->view('admin/inc/admin_footer');
    }

Error Messages
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Admin::$users
Filename: controllers/Admin.php
Line Number: 217
Fatal error: Call to a member function count_members() on null in G:\xampp\htdocs\highball061516\application\controllers\Admin.php on line 217
A PHP Error was encountered
Severity: Error
Message: Call to a member function count_members() on null
Filename: controllers/Admin.php
Line Number: 217

A: In code igniter pagnation, $config["total_rows"] parameter requires total number of records exists in database. In your code, it was getting this count form a function that doesn't exists in model. It should get it from count_members instead. Here is the updated controller code:
public function view_members()
{
    $this->load->model('Users_model');
    $config = array();
    $config["base_url"] = base_url() . "admin/view_members";

    // Code modified here
    $config["total_rows"] = $this->Users_model->count_members();

    $config["per_page"] = 20;
    $config["uri_segment"] = 3;

    $this->pagination->initialize($config);

    $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
    $data["results"] = $this->Users->getMembers($config["per_page"], $page);
    $data["links"] = $this->pagination->create_links();

    //$this->data['members'] = $this->Users_model->getMembers();
    $this->load->view('admin/inc/admin_header');
    $this->load->view('admin/view_members', $this->data);
    $this->load->view('admin/inc/admin_footer');
}


text:
Q: Selector for one tag directly followed by another tag This selects all  tags directly preceded by  tags:
A+B {
    /* styling */
}

What is the selector for all  tags directly followed by  tags?
Here's sample HTML fitting my question:
some text
some text

A: Although it's not very handy, nowadays you could achieve this behavior by reversing the order of your elements both when you generate the HTML and by applying the CSS rules: display: flex and flex-direction: column-reverse

ul {
  display: flex;
  flex-direction: column-reverse;
}

.b ~ .a {
  color: red;
}

A 3

C 2

C 1

B 1

A 2

A 1

Also, if you have 2 or more inline elements, you could achieve it by applying float: right, as they will be displayed in reverse order:

ul {
  float: left;
  list-style-type: none;
}

li {
  float: right;
}

li:not(:first-child) {
  margin-right: 20px;
}

.b ~ .a {
  color: red;
}

A 3

C 2

C 1

B 1

A 2

A 1

A: Do you mean to style A given that it has a B element directly inside or followed? Like this:

// OR

You can't do such a thing in CSS (yet). Eric Meyer states that this kind of selector has been discussed quite a few times on the CSS mailing list, and isn't doable. Dave Hyatt, one of the core WebKit developers, comments with a good explanation of why it can't be done.
Check out: Shaun Inman's blog post and the comment by Eric Meyer.
David Hyatt weighs in, too.

A: You can't in css.
Edit: To be a bit more helpful, if you use for example jQuery (a JavaScript library), you can use .prev().

A: You can ONLY do the converse: This selects all  tags directly preceded by  tags.
This is logically equivalent to your request.
I often use this to style a row of many checkboxes with labels
CSS:
label+input {
    margin-left: 4px;
}

DOM:
<input id="a" name="a" type="checkbox"/>...
<input id="b" name="b" type="checkbox"/>...
<input id="c" name="c" type="checkbox"/>...

A: You can now use the :has() css selector (caniuse):
    .first:has(+ .second) {
        background: #ff0000;
    }

That can be read: select all elements with class ".first" that are followed by element of class ".second"

Foo

Bar


text:
Q: VBScript To Process Array I am attempting to add a few registry keys by using a VBScript.  For some reason the keys are not added, when I run this script.  I do not receive an error either.  Did I set up the array incorrectly?  The user has permissions to add/edit/modify the registry.
Code originally written by Daniel Pineault; all I did was add a For Each loop.
Const HKEY_CURRENT_USER = &H80000001

Dim oRegistry
Dim sPath                   'Path to set as a Trusted Location
Dim sDescription            'Description of the Trusted Location
Dim bAllowSubFolders        'Enable subFolders as Trusted Locations
Dim bAllowNetworkLocations  'Enable Network Locations as Trusted Locations
Dim bAlreadyExists
Dim sParentKey
Dim iLocCounter
Dim arrChildKeys
Dim sChildKey
Dim sValue
Dim sNewKey

Set oRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
sPath = "C:\Test\"
sDescription = "SetThroVBScript"
bAllowSubFolders = True
bAlreadyExists = False

x = Array("Software\Microsoft\Office\12.0\Access\Security\Trusted Locations","Software\Microsoft\Office\12.0\Excel\Security\Trusted Locations","Software\Microsoft\Office\14.0\Excel\Security\Trusted Locations","Software\Microsoft\Office\14.0\Access\Security\Trusted Locations")

For Each sParentKey In x
    iLocCounter = 0
    oRegistry.EnumKey HKEY_CURRENT_USER, sParentKey, arrChildKeys
    For Each sChildKey in arrChildKeys
        oRegistry.GetStringValue HKEY_CURRENT_USER, sParentKey & "\" & sChildKey, "Description", sValue
        If sValue = sDescription Then bAlreadyExists = True

        If CInt(Mid(sChildKey, 9)) > iLocCounter Then
            iLocCounter = CInt(Mid(sChildKey, 9))
        End If
    Next

    If bAlreadyExists = False Then
        sNewKey = sParentKey & "\Location" & CStr(iLocCounter + 1)

        oRegistry.CreateKey HKEY_CURRENT_USER, sNewKey
        oRegistry.SetStringValue HKEY_CURRENT_USER, sNewKey, "Path", sPath
        oRegistry.SetStringValue HKEY_CURRENT_USER, sNewKey, "Description", sDescription

        If bAllowSubFolders Then
            oRegistry.SetDWORDValue HKEY_CURRENT_USER, sNewKey, "AllowSubFolders", 1
        End If
    End If
Next


text:
Q: Appium AndroidUIAutomator2 scroll is very slowly
When I scroll with the code below, it scrolls very slowly, how can I speed it up?
public WebElement scrollToElement() {
    return getDriver().findElement(AppiumBy.androidUIAutomator(
            "new UiScrollable(new UiSelector().resourceId(\"tv_today_campaigns\")).scrollIntoView(new UiSelector().text(\"Kampanyalar ve Duyurular\"))"));
}


text:
Q: How to serve Allure Report without automatically starting the browser When i start the allure, the server always attempts to start the browser:
$ /home/allure/allure-2.3.4/bin/allure serve target/allure-results -p 5012
    Generating report to temp directory...
    Report successfully generated to /tmp/779851636804605067/allure-report
    Starting web server...
    2017-08-21 17:51:00.271:INFO::main: Logging initialized @3082ms
    Xlib:  extension "RANDR" missing on display ":99".
    Exception in thread "main" java.lang.UnsupportedOperationException: The BROWSE action is not supported on the current platform!
            at java.awt.Desktop.checkActionSupport(Desktop.java:225)
            at java.awt.Desktop.browse(Desktop.java:381)
            at io.qameta.allure.Commands.openBrowser(Commands.java:207)
            at io.qameta.allure.Commands.open(Commands.java:135)
            at io.qameta.allure.Commands.serve(Commands.java:119)
            at io.qameta.allure.CommandLine.run(CommandLine.java:136)
            at java.util.Optional.orElseGet(Optional.java:267)
            at io.qameta.allure.CommandLine.main(CommandLine.java:72)
    2017-08-21 17:51:06.387:WARN:oejsh.ResourceHandler:qtp1928301845-20: org.eclipse.jetty.io.EofException
    2017-08-21 17:51:06.388:WARN:oejsh.ResourceHandler:qtp1928301845-15: org.eclipse.jetty.io.EofException

The problem is not in the error, but in the launch, I don't need to start it on this host.
How do I start the allure server without starting the browser?

A: You can use the docker container Allure Docker Service, recognize the results automatically and update the reports without doing anything:
https://github.com/fescobar/allure-docker-service


text:
Q: How to show star rating on the category listing page? I am working on the mobile site and I need to show the product star rating under each product.
The helper calls the template summary_short.phtml which has section to show the star rating but for some reason the object carries on information only about the number of reviews on the grid page. The same works fine on the product page.
I also don't want to do the query in the loop to avoid slowing down the platform.

A: It should be there by default ...
In default/template/review/helper/summary_short.phtml
<?php if ($this->getReviewsCount()): ?>

        <?php if ($this->getRatingSummary()):?>

                <div class="rating" style="width:<?php echo $this->getRatingSummary() ?>%">

        <?php endif;?>
        <a href="#" onclick="var t = opener ? opener.window : window; t.location.href='<?php echo $this->getReviewsUrl() ?>'; return false;">

<?php elseif ($this->getDisplayIfEmpty()): ?>

<?php echo $this->__('Be the first to review this product') ?>

<?php endif; ?>

A: In app/design/frontend/base/default/template/review/helper/summary.phtml as alluded to before:
You need to change it to resemble:

        <div class="rating" style="width:<?php echo $this->getRatingSummary() ?>%">

        <a href="<?php echo $this->getReviewsUrl() ?>"><?php echo $this->__('%d Review(s)', $this->getReviewsCount()) ?>
        |
        <a href="<?php echo $this->getReviewsUrl() ?>#review-form"><?php echo $this->__('Add Your Review') ?>

We're stripping out the conditions to check if there are existing reviews so that it will always show.
Be sure to make a copy of the original and save it with the same path in your own package/theme - do not overwrite the base template.
In your catalog/product/list.phtml or where-ever you are calling the review summary, be sure to remove the condition that surrounds <?php echo $this->getReviewsSummaryHtml($_product, false, true) ?>
.
From the docs:
string getReviewsSummaryHtml ( $product, [string $templateType = false], [bool $displayIfNoReviews = false])


text:
Q: How to iterate and change all elements of a numpy array? I am working on a machine learning task and trying to convert all strings in a set of data to floats using hash() to do this I need to iterate over all the elements of a numpy array whilst not knowing if it is a 2D 3D or 4D array and then change each element. Is there any way to do this without using nested loops?

A: You can try numpu.vectorize, already mentioned here
Note:
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.here
arr = np.array([['aba', 'baa', 'bbb'],
              ['xxy', 'xyy', 'yyy']])
v_hash = np.vectorize(hash)
v_hash(arr)

array([[-1538054455328520296, -1528482088733019667, -7962229468338304433],
       [ 5621962119614158870,  1918700875003591346, -3216770211373729154]])