text:
Q: Finding limit of a sequence defined by another sequence
Let there be $\{a_n\}$ such that $a_{n+2}=2a_{n+1}+2a_n$ and $\{b_n\}$ such that $b_n=\frac{a_{n+1}}{a_n}$ if $\lim_{n \to \infty}b_n=L$ what is the limit $L$?

I thought about if $L$ exist so I can use the arithmetic laws of limits.
$\lim b_n=\lim \frac{a_{n+1}}{a_n}$  and $\lim b_n=\lim \frac{2a_{n+1}+a_n}{a_{n+1}}$.
But could not find how to proceed to find the answer.

A: From $a_{n+2} = 2 a_{n+1} + 2 a_n$ it follows that
$b_{n+1} = 2 + 2/b_n$. If $\lim_{n \to \infty} b_n = L$ exists,
what can you conclude about $L$?

A: First solve the recursion for $a_n$.    The general solution is
$a_n=A\lambda^n+B\mu^n$.  Use the recursion to find a formula that $\lambda$ and $\mu$ satisfy; then calculate $b_n$.


text:
Q: Change WooCommerce product type and update status in the same time I have an XML feed of producs, WordPress (last version), WpAllImport Pro (last version) and WooCommerce (last version) and I want to update my products periodically.
In order to update my products, I need to make something with the old ones that disappear from the XML.
WPAI have this option named "Delete products that are no longer present in your file" and a custom function for this: "function my_is_post_to_delete( $is_post_to_delete, $post_id, $import )"
Now, the problem is that my store is full of External products and for this type of product, I don't have stock.
What I need is to change the product type from External to Simple and then to update his stock and then his status to "out of stock".
I have the following code:
<?php

function my_is_post_to_delete( $is_post_to_delete, $post_id, $import ) {
    if ( $import->id == 2 ) {

        $product = wc_get_product( $post_id );
        $sku = $product->get_sku();
        wp_set_object_terms($post_id, 'simple','product_type');
        update_post_meta($post_id, '_manage_stock', 'yes');

        //$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );

        // Get an instance of the WC_Product object
        //$product = new WC_Product( $product_id );

        // Get product stock quantity and stock status
        //$stock_quantity = $product->get_stock_quantity();
        //$stock_status   = $product->get_stock_status();

        // Set product stock quantity (zero) and stock status (out of stock)
        //$product->set_stock_quantity();
        //$product->save();

        $woocmmerce_instance = new WC_Product( $post_id );
        $new_quantity=wc_update_product_stock( $woocmmerce_instance, $quantity);

        $product->set_stock_status('outofstock');

        // Save the data and refresh caches
        $product->save();

        //file_put_contents(get_home_path() .'/result.stef', $product->get_sku().'\n' );
        return false;

    }
}
add_filter( 'wp_all_import_is_post_to_delete', 'my_is_post_to_delete', 10, 3 );

?>

but I get an error:
CRITICAL Uncaught WC_Data_Exception: External products cannot be stock managed. in /home/etc/public_html/qcd/wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-data.php:810

Stack trace:
#0 /home/etc/public_html/qcd/wp-content/plugins/woocommerce/includes/class-wc-product-external.php(120): WC_Data->error('product_externa...', 'External produc...')
#1 /home/etc/public_html/qcd/wp-content/uploads/wpallimport/functions.php(33): WC_Product_External->set_stock_status('outofstock')
#2 /home/etc/public_html/qcd/wp-includes/class-wp-hook.php(286): my_is_post_to_delete(true, '3329', Object(PMXI_Import_Record))
#3 /home/etc/public_html/qcd/wp-includes/plugin.php(208): WP_Hook->apply_filters(true, Array)
#4 /home/etc/public_html/qcd/wp-content/plugins/wp-all-import-pro/models/import/record.php(4169): apply_filters('wp_all_import_i...', true, '3329', Object(PMXI_Import_Record))
#5 /home/etc/public_html/qcd/wp-content/plugins/wp-all-import-pro/controllers/admin/import.php in /home/etc/public_html/qcd/wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-data.php on line 810

As a final note:
I want to "Instead of delete my products" to make them out of stock.

A: Have you tried updating the variation cache?
update_post_meta( $product_id, '_stock_status', wc_clean( 'outofstock' ) );
wp_set_post_terms( $product_id, 'outofstock', 'product_visibility', true );
wc_delete_product_transients( $product_id );

A: <?php

function my_is_post_to_delete( $is_post_to_delete, $post_id, $import ) {

    // Set the ID of your import
    if ( $import->id == 2 ) {

        $product = wc_get_product( $post_id );
        $sku = $product->get_sku();

        // Change product type to simple
        wp_set_object_terms($post_id, 'simple','product_type');

        // Make the product stock manageable
        update_post_meta($post_id, '_manage_stock', 'yes');

        // Set the product quantity to 0
        $product->set_stock_quantity();

        // Update the product status to Out of stock
        update_post_meta( $post_id, '_stock_status', wc_clean( 'outofstock' ) );
        wp_set_post_terms( $post_id, 'outofstock', 'product_visibility', true );

        // Delete cache
        wc_delete_product_transients( $post_id );

        return false;

    }
}
add_filter( 'wp_all_import_is_post_to_delete', 'my_is_post_to_delete', 10, 3 );

?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pull XML key "value" from SQL CLOB I am attempting to extract information from XML stored in a CLOB column. I've searched the forums and thus far have been unable to get the data to pull as needed. I have a basic understanding of SQL but this is beyond me.
The XML is similar to the following:
<?xml version="1.0" encoding="UTF-8"?>

<Response>
    <Header>
        <OrderNum value="12354321"/>
        <ExtractDate value="11-30-2012"/>
        <RType value="Status"/>
        <Company value="Company"/>
    </Header>
    <Body>
        <Status>
            <Order>
                <ActivityType value="ValidateRequest"/>
                <EndUser>
                    <Name value="Schmo, Joe"/>
                    <Address>
                        <SANO value="12345"/>
                        <SASN value="Mickey Mouse"/>
                        <SATH value="Lane"/>
                        <SASS value="N"/>
                        <City value="Orlando"/>
                        <State value="FL"/>
                        <Zip value="34786"/>
                        <Number value="5550000"/>
                    </Address>
                </EndUser>
                <COS value="1"/>
                <TOS value="3"/>
                <MainNumber value="5550000"/>
            </Order>
            <ErrorCode value="400"/>
            <ErrorMessage value="RECEIVED"/>
        </Status>
    </Body>
</Response>

I want to get the values under "Address".
I've tried the following but it returns "NULL".
SELECT EXTRACTVALUE(XMLTYPE(RESPONSE_CLOB),'/Response/Body/Status/Order/EndUser/Address/SANO') AS SANO
FROM RESPONSE_TABLE
WHERE ROWNUM < 2

I am trying to get it so I can pull the "12345" assigned as "value" in "SANO" (ultimately getting the value for other fields, but want to at least get the one working first).

A: You're currently retrieving the text value of the node, but 12345 is the value attribute of the element rather than its text content. So you would need to use the @attribute syntax, i.e.:
SELECT EXTRACTVALUE(XMLTYPE(RESPONSE_CLOB),'/Response/Body/Status/Order/EndUser/Address/SANO/@value') AS SANO
FROM RESPONSE_TABLE
WHERE ROWNUM < 2;

SANO
--------------------
12345

But extractvalue is deprecated; assuming you're on a recent version of Oracle it would be better to use an XMLQuery:
SELECT XMLQUERY(
  '/Response/Body/Status/Order/EndUser/Address/SANO/@value'
  PASSING XMLTYPE(RESPONSE_CLOB)
  RETURNING CONTENT
  ) AS SANO
FROM RESPONSE_TABLE
WHERE ROWNUM < 2;

You may find it even easier to use an XMLTable - necessary if an XML document has multiple Address nodes, but even with just one pulling the values out as columns is less repetitive, and it makes it easier to retrieve suitable  data types:
select x.*
from response_table rt
cross join xmltable(
  '/Response/Body/Status/Order/EndUser/Address'
  passing xmltype(rt.response_clob)
  columns sano number path 'SANO/@value',
    sasn varchar2(30) path 'SASN/@value',
    sath varchar2(10) path 'SATH/@value'
    -- etc.
) x
where rownum < 2;

                SANO SASN                           SATH
-------------------- ------------------------------ ----------
               12345 Mickey Mouse                   Lane

Read more about using these functions to query XML data.


text:
Q: Why isn't the product $\sigma$-algebra defined as the pre-image $\sigma$-algebra of the canonical projections Let $f:X_1\times X_2\rightarrow Y$ be a mapping and let $\mathscr{B}$ be the $\sigma$-algebra on $Y$. Now, we know that the pre-image is a $\sigma$-algebra, so in this case $f^{-1}(\mathscr{B})$ must be a $\sigma$-algebra on the product $X_1\times X_2$. Is this correct? Because the only product $\sigma$-algebra that I know of is the one generated by the product of measurable sets. My second question is: why is the product $\sigma$-algebra defined to be the $\sigma$-algebra generated by product of measurable sets, and not the the pre-image of the canonical projections $p_i^{-1}(A)$ where $A\in \mathscr{A_{i}}$ and $\mathscr{A_{i}}$ being the $\sigma$-algebra on $ X_i$. My second question is inspired by the way the product topology is defined.

A: If instead of an arbitrary $f$, you use the two projections $\pi_1,\pi_2$ to generate a $\sigma$-algebra, then that will coincide with what is usually called the product $\sigma$-algebra (the one generated by "rectangles"). Using an arbitrary $f$  is kind of irrelevant because you're not exploiting the product structure.
More generally, let $\{(X_i,\mathscr{A}_i)\}_{i\in I}$ be measurable spaces, where $I$ is any non-empty index set. Let $X:= \prod\limits_{i\in I}X_i$ be the cartesian product of the sets (i.e the collection of all functions $f:I\to \bigcup_{i\in I}X_i$ such that for each $i\in I$, $f(i)\in X_i$... which is typically just written as $(x_i)_{i\in I}$ rather than the function $f$ notation). On the product space $X$, we can define two obvious $\sigma$-algebras: the product and box $\sigma$-algebras (but see my remarks below about terminology).

1. Product $\sigma$-algebra.
This is the smallest $\sigma$-algebra, $\mathscr{A}_{\text{prod}}$, on the product space $X$ such that each projection $\pi_i:X\to X_i$ (defined as $\pi_i(f):= f(i)$) is $\mathscr{A}_{\text{prod}}$-$\mathscr{A}_i$ measurable. This means:
\begin{align}
\mathscr{A}_{\text{prod}}&=\sigma\left(\bigcup_{i\in I}\pi_i^{-1}(\mathscr{A}_i)\right)
\end{align}
where $\sigma (\cdots)$ means the $\sigma$-algebra generated by the collection of subsets specified inside (the intersection of all $\sigma$-algebras containing the set inside). We're just taking all those sets required to ensure each $\pi_i$ becomes measurable, and making a $\sigma$-algebra out of those. Note that it is common to denote $\mathscr{A}_{\text{prod}}$ as $\bigotimes_{i\in I}\mathscr{A}_i$.
A nice fact about the product $\sigma$-algebra is that because it plays nicely with the projections $\pi_i$, we have the following theorem (as always when dealing with "products"):

Theorem.
Let $\{(X_i,\mathscr{A}_i)\}_{i\in I}$, where $I$ is a non-empty index set, be a collection of measurable spaces, let $X$ be the cartesian product of $X_i$, and let $\mathscr{A}_{\text{prod}}$ be the product $\sigma$-algebra as above. For any measurable space $(Y,\mathscr{B})$, and any function $f:Y\to X$, we have that $f$ is $\mathscr{B}$-$\mathscr{A}_{\text{prod}}$ measurable if and only if for each $i\in I$ the component function $\pi_i\circ f$ is $\mathscr{B}$-$\mathscr{A}_i$ measurable.

The implication $\implies$ is trivial since composition of measurable functions (with correct $\sigma$-algebras) is again measurable. For the converse, you need to know that to prove $f$ is measurable, you just have to show that for some generating set of $\mathscr{A}_{\text{prod}}$, such as $\bigcup_{i\in I}\pi_i^{-1}(\mathscr{A}_i)$, all the preimages under $f$ lie in $\mathscr{B}$. But this is exactly what measurability of each $\pi_i\circ f$ means. This completes the proof.

2. Box $\sigma$-algebra.
We define the box $\sigma$-algebra $\mathscr{A}_{\text{box}}$ to mean the $\sigma$-algebra generated by all "measurable boxes/rectangles", i.e
\begin{align}
\mathscr{A}_{\text{box}}:=\sigma\left(\left\{\prod_{i\in I}A_i\,\bigg| \, \text{for all $i\in I$, }A_i\in \mathscr{A}_i\right\}\right)
\end{align}

3. Relationship between Product and Box $\sigma$-algebras.
The main relationship between them is summarized in the following theorem:

Theorem.
With notation as above, we always have that $\mathscr{A}_{\text{prod}}\subset \mathscr{A}_{\text{box}}$. If we make the additional assumption that the index set $I$ is countable, then we have the opposite inclusion as well, and thus $\mathscr{A}_{\text{prod}}=\mathscr{A}_{\text{box}}$.
Finally, if there are uncountably many $i\in I$ such that $\mathscr{A}_i\neq \{\emptyset,X_i\}$ is not the trivial $\sigma$-algebra, then we have a strict inclusion $\mathscr{A}_{\text{prod}}\subsetneq \mathscr{A}_{\text{box}}$.

The first part of the proof is easy: for any $i\in I$ and measurable set $A_i\in \mathscr{A}_i$, the set $\pi_i^{-1}(A_i)$ is a product of sets $\prod_{j\in I}A_j$, where for $j\neq i$, $A_j=X_j$ (i.e we're only placing restrictions on the $i^{th}$ coordinate). This shows that the generating set of product $\sigma$-algebra is contained in the generating set for the box $\sigma$-algebra, hence we also have inclusions of the $\sigma$-algebras themselves.
Conversely, if $I$ is a countable index set, and we consider a measurable rectangle $\prod_{i\in I}A_i$, then this can be written as $\bigcap_{i\in I}\pi_i^{-1}(A_i)$. This is a countable intersection of sets in $\mathscr{A}_{\text{prod}}$, and thus still belongs to $\mathscr{A}_{\text{prod}}$. Since the generating set of $\mathscr{A}_{\text{box}}$ is contained in $\mathscr{A}_{\text{prod}}$, we have $\mathscr{A}_{\text{box}}\subset \mathscr{A}_{\text{prod}}$, hence completing the proof.
For the final statement, we may without loss of generality assume that for each $i\in I$, $\mathscr{A}_i\neq \{\emptyset, X_i\}$. For each $i\in I$, pick a measurable set $A_i\in \mathscr{A}_i\setminus \{\emptyset,X_i\}$, and consider $A=\prod_{i\in I}A_i$. This clearly lies in the box $\sigma$-algebra, but we claim this is not in the product $\sigma$-algebra. To see this, note that
\begin{align}
\mathscr{A}_{\text{prod}}&:=\sigma\left(\bigcup_{i\in I}\pi_i^{-1}(\mathscr{A}_i)\right)=\bigcup_{\substack{C\subset I\\ \text{$C$ countable}}}\sigma\left(\bigcup_{i\in C}\pi_i^{-1}(\mathscr{A}_i)\right),
\end{align}
where "countable" means finite or countably infinite. The second equality is a general measure theory exercise: the inclusion $\supset$ is clear, and you can directly verify that the set on the right is a $\sigma$-algebra (the key thing being countable union of countably index sets is again a countable index set), and the RHS contains the generating set $\bigcup_{i\in I}\pi_i^{-1}(\mathscr{A}_i)$ of the LHS. This proves the second equality.
So, suppose for the sake of contradiction that $A$ belongs to the product $\sigma$-algebra. Then, by the above equality, there is some countable $C\subset I$ such that $A\in \sigma\left(\bigcup\limits_{i\in C}\pi_i^{-1}(\mathscr{A}_i)\right)$. This implies that $A$ "depends only on the coordinates in $C$". To make this statement more precise, let $\pi_C:\prod_{i\in I}X_i\to \prod_{i\in C}X_i$, $\pi_C(f):=f|_C$ be the canonical projection defined by restricting the function to the smaller domain $C$. Also, for each $j\in C$, let $p_j:\prod_{i\in C}X_i\to X_j$ be the usual projection $p_j(g):=g(j)$. The relationship between all the projections is that for $i\in C$, we have $\pi_i=p_i\circ \pi_C$ (just unwind the definitions on the RHS). So, we have
\begin{align}
A\in \sigma\left(\bigcup_{i\in C}\pi_i^{-1}(\mathscr{A}_i)\right)&=
\sigma\left(\bigcup_{i\in C}\pi_C^{-1}(p_i^{-1}((\mathscr{A}_i)))\right)\\
&=\sigma\left(\pi_C^{-1}\left(\bigcup_{i\in C}p_i^{-1}(\mathscr{A}_i)\right)\right)\\
&\subset \pi_C^{-1}\left(\text{power set of $\prod_{i\in C}X_i$}\right)
\end{align}
This shows us that there is some subset $G\subset \prod_{i\in C}X_i$ such that $A=\pi_C^{-1}(G)$.
So, now if we fix an index $j\in I\setminus C$ (such an index exist since $I$ is uncountable while $C$ is countable), then
\begin{align}
A_j=\pi_j(A) = \pi_j(\pi_C^{-1}(G))\in \{\emptyset,X_j\}
\end{align}
which contradicts our assumption about $A_j$. This completes the proof. Note that the last part is because  (assuming things are non-empty), an element of $\pi_C^{-1}(G)$ is by definition a function $f:I\to \bigcup_{i\in I}X_i$ such that its restriction $f|_C$ belongs to $G$. Since $j\notin C$, if we modify $f(j)$ only, we get a new function $\tilde{f}$, which still belongs to $\pi_C^{-1}(G)$ because $\tilde{f}|_C=f|_{C}\in G$. Since we can change the $f(j)$ value arbitrarily, we can ensure we get anything in $X_j$.

Final Remarks.
The way I introduced things here, the analogy with topology should be strikingly similar, with the one exception that for topology, the product and box topologies coincide provided the index set is finite (merely countable is not enough anymore).
So, note that in particular for the index set $I=\{1,2\}$ so that $X=X_1\times X_2$, the two descriptions of the $\sigma$-algebras are equivalent.
I think the terminology I have introduced here is the most appropriate one, but I should mention that (in Probability) I've also seen $\mathscr{A}_{\text{prod}}$ being described as "the cylindrical $\sigma$-algebra", and $\mathscr{A}_{\text{box}}$ being described as "the product $\sigma$-algebras"; this second bit it pretty absurd to me, so I avoid this terminology.


text:
Q: C++ macro to get full function path and declaration I want to get full function path and declaration in code via macro or some compiler magic. I have this code (click here to run):
#include <iostream>

namespace NS {

    struct Foo {
        static int sum(int a, int b) {
            std::cout << "This is from " << __FILE__ << ":" << __LINE__ << " @ " <<     __func__ << std::endl;
            return a+b;
        }

        static int sum(int a, int b, int c) {
            std::cout << "This is from " << __FILE__ << ":" << __LINE__ << " @ " <<     __func__ << std::endl;
            return a+b+c;
        }

   };
}

int main() {
    NS::Foo::sum(1,2);
    NS::Foo::sum(1,2, 3);
}

And I get the output:
This is from /some/where/main.cpp:7 @ sum
This is from /some/where/main.cpp:12 @ sum

My questions are:

*

*How do I get the full path of sum function invoked?(NS::Foo::sum)

*How can I get the full function declaration with argument types?( sum(int, int) or sum(int, int, int))

I am interested in mainstream compilers: Clang, GCC, Microsoft C++ compiler

A: Answering for GCC.
Checkout the __PRETTY_FUNCTION__ macro. I've found it in the defintion of assert macro in <assert.h>. Perhaps same could be found for other compilers and libc implementations.

A: For Microsoft Visual Studio compiler, __FUNCSIG__ can give you a lot about the function.
__FUNCSIG__ will give you full function signature
__FUNCDNAME__ gives magnled name.
__FUNCTION__ is just for function name.

A: If you don't want to limit yourself to a single compiler, and don't fancy writing a pre-processor ifdef chain yourself, boost has already defined a macro BOOST_CURRENT_FUNCTION which is defined as the full function signature macro that's defined on the used compiler. __PRETTY_FUNCTION__ in gcc and other compilers that support that, __FUNCSIG__ where that is supported (msvc), also supports some lesser used compilers and falls back to __func__ as defined by the C standard (or a static placeholder if even that's not supported).


text:
Q: Is there a way to avoid widows when placing an image at the end of a paragraph? I have a site where the client wants to be able to put a stylized graphic at the end of some link text. Conceptually, it'd be like this:
This is My Fancy Title
Except at some widths, word-wrapping causes the image to wrap as a widow on it's own line.
I've tried quite a few different approaches to this, including the widows CSS property, but nothing seems to work 100%.
Any suggestions?

A: You can use white-space: nowrap.
That will cause the text and image to not wrap to the next line.
Add a span and put one or 2 words and the image in it, make it inline-block

span {
  display: inline-block;
}
This is My Fancy Title


text:
Q: Determining the optimum number of worker threads Imagine, that we have X (30 for example) number of system. Each system has an
array of Entities on which it has to operate (the number of Entities for a system is different for each) . So basically, systems contain algorithms and Entities contain data to be acted upon. Each system can specify what kind of Entities it can act upon, thus an Entity can be operated upon by multiple systems.
The systems are arranged in a chain, meaning that we run then sequentially, not in paralell. They are called upon in the same sequence each time to act upon their Entities (all we have to do is call their System::process method.
This system chain is run 60 times each second.

Currently, it is implemented so that a system runs on a single thred, processing it's Entities sequentially. I'd like to have concurrency.
Systems do not have state, therefore we can safely call their process methods on multiple threads at once, given that we tell each method call on which portion of the system's Entities should it work on.
Example: we determin that we have 2 cores available, therefore we run each system on 2 threads. One of the threads calls a system's process method and tells it to process from 0 to 20 (indexes of the array containing the Entities), the other thread calls the same system's process method and tells it to process from 20 to 40.

Now the questions: what is the optimal number of threads the load should be distributed on, taking the probable cache size and cores and what not into account. (Maybe decided empirically by testing?)
What would be the most efficent way to manage the Threads (thread pool etc.)?


text:
Q: What is the correct way to make the last page appear on pagination? I need to make the pagination show some amount of pages saying 5 then show the dots and last page. Making it look like:
1 2 3 4 5 ... 20
pager.phtml already has those within the template, but they depend on the following methods
canShowNextJump();
canShowLast();

both are defined within Magento\Theme\Block\Html\Pager
Is there any combination of Admin settings to achieve that or I will need to override methods/values in Pager block?

A: Add at Content > Design > Configuration > your Theme > Pagination > Pagination Frame Skip => 10 or try what is good for you


text:
Q: How can I test my NGINX website without a domain name? I configured 3 server blocks on nginx for 3 different domain names. But I'm yet to buy domain names. If I enter server IP address like http://53.208.12.57/index.html it was only opening first website (/var/www/site1/index.html). How to see my 2nd & 3rd websites on (/var/www/site2/index.html and /var/www/site3/index.html)?
I also tried opening http://53.208.12.57/site2/index.html also, but it was not working. So what is the correct path to open 2nd website?

A: Currently, the IP address does not match any server_name in your configuration, so nginx will use the default server.
You can manually add the IP address to one of your sites for the purposes of testing that site, or add the keyword default_server to its listen directive to move the default server away from the first server block.
For example:
server_name site2.example.com 53.208.12.57;

Or:
listen 80 default_server;

I realise that this is not ideal, as you will need to restart nginx to test each website. You can specify the Host header with curl, but I do not think that is the kind of test you are interested in performing.
See this document for details.


text:
Q: How to default variable (list of dates) to current date? For some dashboards we have a date variable to pick a date from a list of dates. The dates are queried from an elasticsearch datasource.
In our case it would be great if we could somehow set the default value to the current date.
We are using Grafana 7.1.1. I am not sure if it can be achieved at all - Currently I am thinking about extending the elasticsearch-query to put the current date on top but I don't think Grafana can set the default value based on the index.
Another idea is to use a "global" date variable for the current date which I can search for in the variable selection field and then save the dashhboard.
Any hints (including feasibility) are appreciated.

A: Correct, make current date first in that variable list and never Save current variables -> Grafana will preselect first value from the variable list in this case.
If you already have some saved current variables, then you need to edit dashboard model manually (export dashboard json/edit json - variable definition/import dashboard json).


text:
Q: How to get last object in each hour over last 7 days in Django using DatetimeField column? I have been doing a task of filtering values from a table called 'Feeds',
The row gets inserted every 10 mins into the system.
ie. 6 rows every hour I am storing its datetime in a column called timestamp.
I want to filter last row of each such hour of past 7 days.
Here is my code.
class Feeds(models.Model):
    value = models.FloatField()
    timestamp = models.DateTimeField(auto_now_add=True)`

Please Help to solve this.
Thank you.

A: Get the objects of last 7 days, then get objects from every hour and find the object with the greatest datetime value, exclude others.
d = datetime.now() - timedelta(days=7)
feeds = Feeds.objects.filter(timestamp__gte=d)
d = d.replace(minute=0, second=0, microsecond=0)
while d <= datetime.now():
    temp = feeds.filter(timestamp__range=(d, d + timedelta(hours=1)))
    if temp:
        temp = temp.exclude(timestamp=temp.all().order_by('-timestamp')[0].timestamp)
        for t in temp:
            feeds = feeds.exclude(timestamp=t.timestamp)
    d += timedelta(hours=1)


text:
Q: How to debug high CPU usage on Java process, not caused by Java threads I have a Java application that runs on Tomcat on Linux. After running for several weeks, it starts taking close to 100% CPU (as displayed by 'top' command), but none of the Java threads takes more than 5% CPU; it's not kernel CPU either (that one is between 0.2-0.5%). So something else (native code? JVM itself?) is causing this high CPU usage. The problem can only be solved by restarting Tomcat.
So the question is: is there the way to find out what is causing this high CPU usage, if not Java threads? Is there a way to "look at" native libraries running inside Java process. Or what should be my debugging strategy in this case?
Versions: Linux 2.6 (CentOS), Apache Tomcat/6.0.33, JVM: Sun 1.6.0_29-b11. The application happens to be Forgerock OpenAM 10.0 (I am checking known issues on their end too, but so far didn't find the exact match, so looking for more generic suggestions)

A: This seems to be long unanswered. Investigating cpu for a java process is based on analyzing the cpu consumption of each of the pthread of the jvm process. Here is a link to the post that explains this: http://www.learnings.today/investigating-cpu-usage-in-a-java-process/


text:
Q: What does Rails mean when it reports spending time rendering a view? Here's an excerpt from my Rails log:
Rendered songs/_song_list (683.4ms)
Completed in 841ms (View: 633, DB: 159) | 200 OK
What does Rails mean when it reports spending 633ms rendering the view?
In this particular case I'm iterating through a collection of items and printing an <li> for each (as the name of the partial suggests) -- is Rails spending that 633ms concatenating strings? I feel like that (or any other CPU-bound operation) should be roughly infinitely fast.

A: Make sure that you aren't fetching from the database on every item. Preload everything you will need with the include option on find, or else, while the View is running, you will be running tons of queries and initializing new ActiveRecord objects, which is a huge time-waster.

A: View in this case means everything: The bootstrap, includes, initializations, everything. It still seems like a lot, though. What does time look like in a view that does nothing?


text: Q: PowerShell Register-PSRepository Set Priority I have two PowerShell Repositories installed. It isn't possible to uninstall the default package feed (https://www.powershellgallery.com/api/v2/) with the Unregister-PSRepository command, and I don't want to get my packages over the default package feed. Is it somehow possible to set a priority over which package feed the packages will be installed?


text:
Q: Proving convergence in probability functions In the textbook during the steps to expand the convergance of probability the following is provided.
the condition for converges in probability is given as $\lim_{n\rightarrow \infty}\mathbb{P}(|X_n-X|>\epsilon)=0$
$\mathbb{P}(|X_n-c|>\epsilon)=\mathbb{P}(X_n>c+\epsilon)+\mathbb{P}(X_n<c-\epsilon)$
I dont understand why the inequality is not expanded as $X_n>\epsilon - c$ and $X_n<c-\epsilon$. It seems to be something so trivial that I can't find anywhere (or perhaps the correct query word).
How does it work?

A: The condition $|X_n-c|\le \epsilon $ means $X_n$ is within distance $\epsilon$ of $c$. In other words $X_n \in [c-\epsilon, c+ \epsilon]$.
Hence  the converse $|X_n-c| > \epsilon $ means  $X_n \notin [c-\epsilon, c+ \epsilon]$. In other words either  $X_n > c+ \epsilon$ or $X_n < c- \epsilon$.


text:
Q: Imported a virtual harddisk as new device and I need it to export it same way (VirtualBox) My first experience with vms. I got a folder with vmdk files (and lots of other stuff too) was able to make it work through using this under  New>Use a existing harddisk.
I have made some changes within this and need to send it to another pc. But when I send the same folder -the one mentioned above- to the other pc it seems like there hasnt been any changes.
There is another folder within the Virtual VM folder in a different place but that is just too small for this case (everything should be around 16 gb this folder is just over 1gb)
How can I export this the same way as I got it?

A: If you want the same settings when you move your VM from VirtualBox to another computer, you need to export your VM from VirtualBox.
You can do this, Select your VM File >> Export Appliance and import VM on another machine File >> Import Appliance. The extension of file will be .OVA.


text:
Q: Why PHP Simple HTML DOM Parser won't find an element? I'm using PHP Simple HTML DOM Parser with following code snippet:
<?php
include_once('../simple_html_dom.php');

$html = file_get_html('http://old.wowhead.com/npc=8404');

if ( $html->find('div.pin'))
echo 'Found';

?>

But it simply does not find
'

'

element on this html page: http://old.wowhead.com/npc=8404

A: i opened the link you gave and there is no div with a class of 'pin'. You have to give the method a valid element object.
try changing the selector to say
$html->find('div.pad1');

it works...in my case

A: I think div elements with class pin appears by JavaScript, so when you just download static html file there is no such elements.


text:
Q: Kostka number under dominance relation The Kostka number is defined as the number $K_{\lambda\mu}$ of semistandard Young tableaux, i.e, strictly increasing column, (nonstrictly) increasing column of the shape $\lambda$ and content $\mu$. I have seen a statement that $\lambda\unrhd\mu$ then $K_{\lambda\mu}>0$. But for $\lambda=(4,3,3)$ and $\mu=(4,2,4)$. It seems does not work:
1 1 1 1
2 2 3
3 3 3 not strictly increasing here..

A: You're getting confused by the ordering of $\mu$. It's true that $K_{\lambda\mu} = K_{\lambda\nu}$ whenever $\mu$ and $\nu$ are rearrangements of each other. For that reason, one very often assumes $\mu$ is a partition to begin with, i.e. $\mu$ is weakly decreasing. This is the usual setting in which dominance order is defined, as in this MO thread which has several proofs of your fact. If you allow $\mu$ to be just a composition rather than a partition, you need to use majorization order, which means you need to first sort the two things being compared and then use dominance order.
So, in your example of $\lambda = (4, 3, 3)$ and $\mu = (4, 2, 4)$, you really need check $4 \geq^? 4$, $4+3 \geq^? 4+\color{red}{4}$, $4+3+3 \geq^? 4+4+2$. The middle inequality fails, $\lambda$ does not dominate $\mu$.


text:
Q: The process cannot access the file because error while trying to write to a file I am getting this error when i am trying to write to a file in this manner:
    try
    {

        if (!File.Exists(path))
            File.CreateText(file.ToString());

        sw = flag == 1 ? File.CreateText(file.ToString()) : File.AppendText(file.ToString()); //Exception here

        sw.WriteLine(textToWrite);

        status = true;
    }

But before to this file i made a delete attempt to it also in another function in this way:
    try
    {
        File.Delete(path);
        status = true;
    }

Exception:
{"The process cannot access the file ... because it is being used by another process."}
Now as it seems file is still either taken by delete process of by the File.CreateText function, how can i make them release the file so i can start writing to it?

A: File.CreateText will return a streamwriter which has a file stream still opened. You should be using that. That is the reason why you get exception in successive calls to open the file.
Try this.
using(var sw = File.CreateText(...))
{
    //Do whatever
}

A: If you want to delete the file before writing a new file, try this:
File.WriteAllText(path, textToWrite);

If you want to append to a file (or create), try this:
File.AppendAllText(path, textToWrite);

Both of these methods close the file after writing.

A: CreateText returns StremWriter which you miss it. That's why it remains opened. You can easily close it:
StreamReader sr = File.OpenText(path);
sr.WriteLine(textToWrite);
sr.Close();


text:
Q: Can't uninstall SQL Server 2008 R2 SP3 I have encountered the error on SQL Server 2008 R2 where Report Builder 3 fails to load with error

Microsoft.ReportingServices.ComponentLibrary.Controls.dll, has a different computed hash than specified in manifest.

As described in this SQL Release Services blog post, this problem should be fixed by uninstalling SP3, uninstalling SP2, then re-installing SP3.
However I can't seem to uninstall SP3. When I navigate to Programs and Features -> View Installed Updates, click on SQL Server SP3, and choose Uninstall, I get a wizard window that looks like this:

There is no way to proceed. How do I move forward with this issue so that my users can get back to using Report Builder?

A: I know this is an older post, but to save anyone else a headache...
You will only be able to remove SP3, if you have already removed all other patches that have been applied since the SP3 install, you can do this via Windows Programs and features -> View Installed Updates, and checking all patch versions greater than the one for SP3.


text:
Q: iterating through imput elements to assign values to an array The code below  fetches a list of files that have been selected for upload.
It basically appends input elements inside a div above a form element:

How do I store all the attributes names in an array - fileNamesArray - on clicking the submit button.?
My attempt I'm yet to check if this works:
// beginning of attempt
// my approach:
// alert the user if no file is selected for upload and submit is clicked else
// I'd have to iterate through the input elements and contained in the div id="files_list", fetch all the file names and push all the values into an array $filesArray.
//rough attempt
$("Submit").click(function () {

    $filesArray

    $(div#files_list).getElementById('input').each(function($filesArray) {
        filesArray.push($this.attr("value"))
    });

    while( $filesArray.size != 0) {
        document.writeln("
" + $filesArray.pop() + "
");
    }
}

//end of attempt: I print out the names just to verify
Code Below:
$(document).ready(function(){
var fileMax = 6;
$('#asdf').after('
Files (maximum '+fileMax+'):
');
$("input.upload").change(function(){
doIt(this, fileMax);
});
});

function doIt(obj, fm) {
if($('input.upload').size() > fm) {alert('Max files is '+fm); obj.value='';return true;}
$(obj).hide();
$(obj).parent().prepend('<input type="file" class="upload" name="fileX[]" />').find("input").change(function() {doIt(this, fm)});
var v = obj.value;
if(v != '') {
$("div#files_list").append('
'+v+'<input type="button" class="remove" value="Delete" style="margin:5px;" class="text-field"/>
')
.find("input").click(function(){
$(this).parent().remove();
$(obj).remove();

return true;
});
}
};

Code for the HTML form:
<form action="test.php" method="post" enctype="multipart/form-data" name="asdf" id="asdf">

        <input type="file" id="element_input" class="upload" name="fileX[]" />

          <textarea name="textarea" cols="65" rows="4" class="text-field" id="textarea">Add a description</textarea>

        <input name="Submit" type="button" class="text-field" id="send" value="Submit" />

</form>

A: var my_array = new Array();

$('#asdf').bind('submit', function() {
    $.each(this.elements, function() {
        if ( this.type == 'file' ) {
            $('#file_list').append($(this).clone());
            my_array.push(this.value);
        }
    });

    for ( var i=0; i < my_array.length; i++ )
        alert(my_array[i]);
});

Here you go!
EDIT Updated due to OP's comment.


text:
Q: Heroku Error: Invalid schema, expected `mongodb` or `mongodb+srv` My app is able to connect to MongoDB locally but on heroku logs i'm getting this error:
Error: Invalid schema, expected mongodb or mongodb+srv
This is what my connection to mongodb looks like in my server.js file:
// // DB config
const db = require("./config/keys").mongoURI;

// // Connect to MongoDB
mongoose
  .connect(db)
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.log(err));

config/keys:
if (process.env.NODE_ENV === "production") {
  module.exports = require("./keys_prod");
} else {
  module.exports = require("./keys_dev");
}

keys_dev:
module.exports = {
  mongoURI:
    "mongodb://jenn123:jenn123@devconnect-shard-00-00-acrk4.mongodb.net:27017,devconnect-shard-00-01-acrk4.mongodb.net:27017,devconnect-shard-00-02-acrk4.mongodb.net:27017/test?ssl=true&replicaSet=devconnect-shard-0&authSource=admin&retryWrites=true",
  secretOrKey: "secret"
};

keys_prod:
module.exports = {
  mongoURI: "process.env.MONGO_URI",
  secretOrKey: "process.env.SECRET_OR_KEY"
};

Any help is greatly appreciated

A: Well, you're doing the production keys wrong.
process.env is an object containing the env variables as key and their values.
so instead of putting them in a string, you gotta remove the string and treat it as an object. like below:
module.exports = {
  mongoURI: process.env.MONGO_URI,
  secretOrKey: process.env.SECRET_OR_KEY
};

A: This is typically how I connect with mongoose.
const mongoose = require('mongoose');
const dotenv = require('dotenv').config();

let db = mongoose.connection;

mongoose.connect('your connection URL here', {
    auth: {
      user: "Your username",
      password: "Your password"
    }
  })
  .then(() => {
    console.log('connection successful')
    db = mongoose.connection;
    module.exports = db;
  })
  .catch((err) => {
    console.error(err)
  });

You can then use it in a file like so (this is assuming you've defined a job schema and are importing it):
const db = require('./db'); // provides the mongoDB connection
const mongoose = require('mongoose');
const ObjectId = require('mongoose').Types.ObjectId;
const Job = require('./schemas/jobs').Job

module.exports.createJob = function (newJob) {
    const job = new Job(newJob);
    return new Promise((resolve, reject) => {
    job.save((err, data) => {
      if (err) {
          reject(err);
      } else {
          resolve(data);
      }
    });
  });
};


text:
Q: KnockoutJS custom binding calling click event during bind, not on click I`m attempting to bind an observable array of people two a two column responsive layout with click events using knockoutjs.
I have created a custom binding called TwoCol that loops through the array, and appends nodes to the DOM to create my suggested layout, but the click events are giving me trouble when I try to apply them in a custom binding nested in a loop.
I have played with it quite a bit, and encountered all types of results, but where I`m at now is calling my ~click~ event during binding, rather than on click.
http://jsfiddle.net/5SPVm/6/
HTML:
<div data-bind="TwoCol: Friends" id="" style="padding: 20px">

JAVASCRIPT:
function FriendsModel() {
    var self = this;
    this.Friends = ko.observableArray();
    this.SelectedFriend = "";
    this.SetSelected = function (person) {
        alert(person);
        self.SelectedFriend = person;
    }
}
function isOdd(num) {
    return num % 2;
}
ko.bindingHandlers.TwoCol = {
    update: function (elem, valueAccessor) {
        var i = 0;
        var rowDiv;
        var vFriends = ko.utils.unwrapObservable(valueAccessor());
        $(elem).html('');
        while (i < vFriends.length) {
            //create row container every other iteration
            if (!isOdd(i)) {
                rowDiv = document.createElement("div");
                $(rowDiv).addClass("row-fluid");
                elem.appendChild(rowDiv);
            }
            //add column for every iteration
            var colDiv = document.createElement("div");
            $(colDiv).addClass("span6");
            rowDiv.appendChild(colDiv);
            //actual code has fairly complex button html here
            var htmlDiv = document.createElement("div");
            var htmlButton = vFriends[i]
            htmlDiv.innerHTML = htmlButton;
            colDiv.appendChild(htmlDiv);
            //i think i need to add the event to the template too?
            //$(htmlDiv).attr("data-bind", "click: { alert: $data }")
            //it seems that the SetSelected Method is called while looping
            ko.applyBindingsToDescendants(htmlDiv, { click: friends.SetSelected(vFriends[i]) });
            i++;
        }
        return { controlsDescendantBindings: true };
    }
}

var friends = new FriendsModel();
friends.Friends.push('bob');
friends.Friends.push('rob');
friends.Friends.push('mob');
friends.Friends.push('lob');
ko.applyBindings(friends);

A: I don't think you're using ko.applyBindingsToDescendants correctly.  I admit I'm a little confused as to the meaning of some of the values in your code, so I may have interpreted something incorrectly.
Here's a fiddle where I think it's working the way you intended:
http://jsfiddle.net/5SPVm/7/
http://jsfiddle.net/5SPVm/8/
Notice if manually control descendant bindings (return { controlsDescendantBindings: true };), you need to set that up in the init callback, instead of update.  The update callback is too late for that.
Quick rundown of the changes (edited):

*

*Moved the controlsDescendantBindings into the init binding callback

*Added the necessary parameter names to the binding param list to access additional values.

*I re-enabled the html.attr call.  Notice that now, because the binding context is set to the actual item, the SetSelected method doesn't exist at that level anymore, so it is necessary to use $parent.SetSelected.
        $(htmlDiv).attr("data-bind", "click: $parent.SetSelected")

*Fixed the ko.applyBindingsToDescendants call.  This method takes a binding context, which is created from the current binding context, and also takes the element to apply the binding to.  You don't want to reapply the binding, which is why this whole thing needs to be in the init handler.
        var childBindingContext = bindingContext.createChildContext(vFriends[i]);
    ko.applyBindingsToDescendants(childBindingContext, colDiv);


text:
Q: How to make a Cardview expand by clicking it? I'm trying to make some Cardview expand when clicking. I was able to do this by setting the original Cardview size to 50dp and then setting its height to WRAP_CONTENT, as shown in the image below:

Here's the code:
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        holder.cvCard.setLayoutParams(new ConstraintLayout.LayoutParams(holder.cvCard.getWidth(), ConstraintLayout.LayoutParams.WRAP_CONTENT));
    }
});

The problem, as you can see, is that by changing the size of the Cardview, it loses its margins and looks that way misaligned. Can you guys help me?

A: Do this
holder.itemView.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    if(YOURCARDVIEW.getVisibility() == View.VISIBLE) {
     YOURCARDVIEW.setVisibility(View.GONE);
    }else {
     YOURCARDVIEW.setVisibility(View.VISIBLE);
    }
   });

And in your XML keep the visibility= gone

A: Try this!
Your view holder xml code should look similar to this:
       <android.support.v7.widget.CardView
            android:id="@+id/cardView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardElevation="4dp"
            app:cardCornerRadius="4dp"
            android:clipChildren="true"
            android:layout_margin="16dp"
            android:clickable="true"
            android:focusable="true"
            android:background="?attr/selectableItemBackgroundBorderless">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <!--visible content-->
                <LinearLayout
                    android:id="@+id/lytVisible"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal"
                    android:padding="16dp"
                    android:gravity="center_vertical">

                    <ImageView
                        android:layout_width="24dp"
                        android:layout_height="24dp"
                        android:src="@drawable/ic_print_black_24dp"
                        android:tint="#555555"/>

                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="Click me to expand"
                        android:layout_marginLeft="16dp"
                        android:textSize="16dp"
                        android:textColor="#333333"/>
                </LinearLayout>
                <!--end visible content-->

                <!--hidden content-->
                <LinearLayout
                    android:id="@+id/lytHidden"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:padding="16dp"
                    android:visibility="gone">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."/>

                </LinearLayout>
                <!--end hidden content-->

            </LinearLayout>
        </android.support.v7.widget.CardView>

And here your java code:
holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            View hiddenView = holder.itemView.findViewById(R.id.lytHidden);
            hiddenView.setVisibility( hiddenView.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
        }
    });

Good luck!


text:
Q: paypal Preapproval API we are trying to add a pre-approval paypal process to our website before a user can bid on any of our items for sale. We currently accomplished this using Authorize.net but want to now integrate paypal as well.
I have been doing some research and am trying to find out if paypal even offers such a solution. The main reason for adding this verification is of course to make sure an individual actually has the money to purchase the item, some items can range from $100-$100,000. Does paypal offer a pre approval process for those types of transactions?
https://developer.paypal.com/docs/classic/api/adaptive-payments/Preapproval_API_Operation/

A: The Preapproval API gives your application permissions to trigger payments on a user's behalf without further approval (no login required to submit payments with a preapproval ID).  There is no guarantee funds will be available when you submit this payment.  A transaction with a preapproval ID could simply fail like any other transaction.
It sounds like what you're looking is the Authorization and Capture process, which is probably what you're doing with Auth.net, too.
With PayPal you can run Authorizations from credit cards directly (exactly like you do with Auth.net) and you can also do it with Express Checkout, which would be PayPal login payments.


text:
Q: Scala under MSys2 - failure to initialize terminal My environment is Windows 10 x64/Scala 2.11.7/Msys2 latest.
When running Scala from MSys2 console, I see the following:
$ scala
[ERROR] Terminal initialization failed; falling back to unsupported
java.lang.NoClassDefFoundError: Could not initialize class org.fusesource.jansi.internal.Kernel32
    at org.fusesource.jansi.internal.WindowsSupport.getConsoleMode(WindowsSupport.java:50)
    at jline.WindowsTerminal.getConsoleMode(WindowsTerminal.java:204)
    at jline.WindowsTerminal.init(WindowsTerminal.java:82)
    at jline.TerminalFactory.create(TerminalFactory.java:101)
    at jline.TerminalFactory.get(TerminalFactory.java:158)
    at jline.console.ConsoleReader.<init>(ConsoleReader.java:229)
    at jline.console.ConsoleReader.<init>(ConsoleReader.java:221)
    at jline.console.ConsoleReader.<init>(ConsoleReader.java:209)
    at scala.tools.nsc.interpreter.jline.JLineConsoleReader.<init>(JLineReader.scala:61)
    at scala.tools.nsc.interpreter.jline.InteractiveReader.<init>(JLineReader.scala:33)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$scala$tools$nsc$interpreter$ILoop$$instantiate$1$1.apply(ILoop.scala:865)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$scala$tools$nsc$interpreter$ILoop$$instantiate$1$1.apply(ILoop.scala:862)
    at scala.tools.nsc.interpreter.ILoop.scala$tools$nsc$interpreter$ILoop$$mkReader$1(ILoop.scala:871)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$15$$anonfun$apply$8.apply(ILoop.scala:875)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$15$$anonfun$apply$8.apply(ILoop.scala:875)
    at scala.util.Try$.apply(Try.scala:192)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$15.apply(ILoop.scala:875)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$15.apply(ILoop.scala:875)
    at scala.collection.immutable.Stream.map(Stream.scala:418)
    at scala.tools.nsc.interpreter.ILoop.chooseReader(ILoop.scala:875)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1$$anonfun$apply$mcZ$sp$2.apply(ILoop.scala:916)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply$mcZ$sp(ILoop.scala:916)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:911)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:911)
    at scala.reflect.internal.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:97)
    at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:911)
    at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:74)
    at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:87)
    at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:98)
    at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:103)
    at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)

Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.

scala>

When running it from cmd.exe, it works as expected. To debug the issue, I tried the following Scala program:
object Test extends App {
    println(org.fusesource.jansi.internal.WindowsSupport.getConsoleMode)
}

When run from Msys2, it produces the following error:
java.lang.UnsatisfiedLinkError: Could not load library. Reasons: [no jansi in java.library.path]
    at org.fusesource.hawtjni.runtime.Library.doLoad(Library.java:182)
    at org.fusesource.hawtjni.runtime.Library.load(Library.java:140)
    at org.fusesource.jansi.internal.Kernel32.<clinit>(Kernel32.java:37)
    at org.fusesource.jansi.internal.WindowsSupport.getConsoleMode(WindowsSupport.java:50)
    at Test$.delayedEndpoint$Test$1(Test.scala:5)
    at Test$delayedInit$body.apply(Test.scala:1)
    at scala.Function0$class.apply$mcV$sp(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
    at scala.App$class.main(App.scala:76)
    at Test$.main(Test.scala:1)
    at Test.main(Test.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at scala.reflect.internal.util.ScalaClassLoader$$anonfun$run$1.apply(ScalaClassLoader.scala:70)
    at scala.reflect.internal.util.ScalaClassLoader$class.asContext(ScalaClassLoader.scala:31)
    at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.asContext(ScalaClassLoader.scala:101)
    at scala.reflect.internal.util.ScalaClassLoader$class.run(ScalaClassLoader.scala:70)
    at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.run(ScalaClassLoader.scala:101)
    at scala.tools.nsc.CommonRunner$class.run(ObjectRunner.scala:22)
    at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:39)
    at scala.tools.nsc.CommonRunner$class.runAndCatch(ObjectRunner.scala:29)
    at scala.tools.nsc.ObjectRunner$.runAndCatch(ObjectRunner.scala:39)
    at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:65)
    at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:87)
    at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:98)
    at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:103)
    at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)

What I tried and it didn't work:

*

*Some threads on the internet mention that it might be caused by missing VC2008 runtime, so I made sure that I have it both for x64 and x86.

*Extracting jansi.dll from scala/lib/jline-2.12.1.jar and putting it in my working directory (with "." included in java.library.path).

*Starting with a fresh MSys2 home directory.

*running bash --login -i from cmd.exe (same error when running scala)

*trying 32-bit and 64-bit JREs

One more thing: the issue doesn't affect sbt; for example, running "sbt console" gives me a working Scala command line, albeit of version 2.10.4.

A: The problem is caused by the name clash between the scala shell script in scala/bin directory and scala.bat in the same directory. Msys2 runs the shell script, while cmd.exe runs the batch file. Apparently, the shell script is not suited for Msys2, which causes the error that I witnessed. Issuing cmd //c scala.bat from MSys2 results in a functional Scala command line.
It is also trivial to edit the scala shell script to support MSys2: https://gist.github.com/kirillkh/a9ba2e00ef2e901f13bf
I have opened a pull request with this change on the GitHub: https://github.com/scala/scala/pull/4674


text:
Q: Gtk Application - CSS Styling GTK widgets is not working I am building a simple GTK application but I am having issues styling it.
Here is a screenshot
Its a very basic Gtk.Dialog with some Gtk.Box with Gtk.Label and Gtk.Entry inside. I want to give some margins to the dialog content and also align the labels to the left.
I read I need to do it with css, but I am having troubles getting in to work. I am loading my stylesheet like this:
style_provider = Gtk.CssProvider()
style_provider.load_from_data(GTK_STYLE)

Gtk.StyleContext.add_provider_for_screen(
           Gdk.Screen.get_default(),
            style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_USER
)

And here my expirements with the css file:
GTK_STYLE = """
* {
    background: blue;
    -GtkDialog-content-area-spacing: 10;
}

.label {
    background: red;
}

GtkLabel {
    color: red;
}

GtkDialog {
    background: red;
}
"""

From this css, only the global blue background is being applied. Nothing of my other style definitions are being applied.
What I am missing? Do I need to be more specific in the selectors? How do I know the hierarchy then?
Thank you for your help.

A: The documentation lists styling properties under CSS nodes, see for instance the docs for GtkLabel: https://developer.gnome.org/gtk3/stable/GtkLabel.html
So I believe in order to set the color of all GtkLabels you'd have to write (untested):
label {
    color: red;
}

For more information go to https://developer.gnome.org/gtk3/stable/chap-css-overview.html


text:
Q: IBM Worklight - Build failure with Adobe Air I am working on a Worklight hybrid application. In this setup I have already set the environment path for the Adobe Air SDK. I am following these steps:

*

*Download the Adobe Air SDK from the Air SDK on Adobe website.

*Unpack the archive into a folder of your choice.

*Set an environment variable (either locally or on the central build server) named AIR_HOME, pointing to the place where you opened the SDK. The Worklight® Builder uses this environment variable to run the build and sign tool when building AIR applications.

And this is the build error I get in Eclipse:

E: air build failed: The path provided in the environment variable
  'AIR_HOME' is not valid. Ensure that the provided path points to the
  root folder of the installed Adobe AIR SDK.

A: In my Windows 7 machine and using Worklight 6.1, I have the following set in System Properties > Environment Variables... > System variables. The build passed successfully.
Variable: AIR_HOME
Value: C:\WorklightDev\AdobeAir (the root folder where the SDK was extracted to)
Once building the environment, you will see the following message:

A dummy certificate is used to sign the air application because a
  PKCS12 certificate from a certificate authority is not available. To
  use a certificate, set the <certificate> element under the <air>
  element in application-descriptor.xml.

This is not an error but a warning.
It means what it means - that you did not provide a certificate for your application, so a dummy certificate is being used instead.
See the following Information Center topic: Signing Adobe Air applications

Adobe AIR applications must be digitally signed in order for users to
  install them. IBM® Worklight provides a default certificate for
  signing AIR applications that can be used for development and test
  purposes.
To sign an AIR application for production distribution, using your own
  certificate, follow these instructions:

*

*Obtain a PKCS12 certificate from a certificate authority (see here for more information),
  and export it as a PFX file.

*Place this certificate on your hard disk.

*Set the <certificate> element under the <air> element in
  application-descriptor.xml
The structure of the <certificate> element is:
<certificate password="password" PFXFilePath="path-to-pfx"/>
where password is the password for the PFX certificate, and path-to-pfx can
  either be relative to the root of the application, or an absolute
  path.

Find the time to familiarize yourself with Worklight. This is not optional.
Read the following:

*

*IBM Worklight Getting Started

*IBM Worklight Information Center


text:
Q: Windows 10 desktop IE shortcut always available with Offline File feature disabled Context
For Windows 10 laptops , that are joined to a Windows domain , offline files is disabled due to security reasons.
No files are allowed to be stored locally on the laptops, by the end user.
For same security reason access to C drive is also restricted for domain users. They only have access to drive mappings, that are avaible when connected to LAN/Domain.
Next to that, the user profile folders (desktop, documents, pictures etc.) are redirected to a central server, that is available through drive mapping when the laptop is connected to the Domain/LAN.
Challenge
When the laptop is offline (meaning offline from the domain/LAN), an Internet Explorer shortcut should be easily available however. For example on the desktop. This to enable the user to access an RDP server farm.
The challenge is to give the user access to the IE shortcut/URL when not connected to the LAN, and at the same time keep up with the security restrictions of User folder Redirection and Disallowing Offline Files.
Options?
What options are there to achieve the goals as described?
I have experimented with the GPO "Specify administratively assigned Offline Files".
Is it correct to say that the GPO "Specify administratively assigned Offline Files", only works when Offline Files is enabled, i.e. enabling the GPO "Allow or Disallow use of the Offline Files feature" ?

A: You can copy the shortcut to C:\Users\Public\Desktop, this is the "All users" desktop. The content of Public\Desktop is "merged" (the view is merged, the file is not copied) with the content of the users' profile.
About this: Is it correct to say that the GPO "Specify administratively assigned Offline Files", only works when Offline Files is enabled =>I don't know.

A: What did work was to add the shortcut to the All User's Start Menu in the GPO configuration.
The shortcut specifically needs this setting on the Common tab of the shortcut setting in the GPO to be turned off (unticked):
" Run in logged on user's security context"
The start menu item remains after reboot.
gpo shortcut general tab
gpo shortcut common tab


text:
Q: Distributed decentralized ring I am trying to implement a distributed ring in Erlang, in which each node will store data.
My idea was create a gen_server module node_ring which will provide state of node in ring:
-record(nodestate, {id, hostname, previd, nextid, prevnodename, nextnodename, data}).

Next, I created virtual hosts via:
werl -sname node -setcookie cook
werl -sname node1 -setcookie cook
werl -sname node2 -setcookie cook

In the first node: node@Machine I start the first item in the ring:
**(node@Machine)1> node_ring:start_link()**

Functions:
start_link() ->
    {Hostname, Id} = {'node@Machine', 0},
    {ok, Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, [first, Hostname, Id], []).

and:
init([first, Hostname, Id]) ->
            State = #nodestate{id = Id, hostname = Hostname, previd = Id, nextid = Id, prevnode = Hostname, nextnode = Hostname, data = dict:new()},
            {ok, State}.

In the next node: **(node1@Machine)1>** I want to start the same module node_ring,
but I have no idea how link it with the previous item in the ring and how the next node will know which node and node_ring is started.
Can you somebody explain me, how make distributed ring in Erlang? I know that there are some implemented systems like Riak. I looked into the source code, but I am really new to distributed Erlang programming, and I do not understand it.

A: Distributed systems programming is hard.  It's hard to understand.  It's hard to implement correctly.
The source code for riak_core can be very hard to understand at first.  Here are some resources that helped me better understand riak_core:

*

*Where to Start with Riak Core (specifically, Try Try Try by Ryan Zezeski)

*Any of the riak_core projects in project-fifo.  howl is probably the smallest project built on top of riak_core that is fairly easy to understand.

*Understand that at the heart of riak_core is a consistent hashing algorithm that allows it to distribute data and work across the ring using partitions in a uniform manner: Why Riak Just Works

*

*A while ago I wrote erlang-ryng which is a generic consistent hash algorithm handler for rings.  It may be helpful for understanding the purpose of consistent hashing in the context of a ring.

*Understanding how riak_pipe works also helped me better grasp how work can be distributed in a uniform manner.

In regards to "It's hard to implement correctly", you can read the Jepsen posts by aphyr for examples and cases where major databases and distributed storage systems have or previously had issues in their own implementations.
That said, here is a very simplistic implementation of a ring in Erlang, however it still has many holes that are addressed below:
-module(node_ring).
-behaviour(gen_server).

% Public API
-export([start_link/0]).
-export([erase/1]).
-export([find/1]).
-export([store/2]).

% Ring API
-export([join/1]).
-export([nodes/0]).
-export([read/1]).
-export([write/1]).
-export([write/2]).

% gen_server
-export([init/1]).
-export([handle_call/3]).
-export([handle_cast/2]).
-export([handle_info/2]).
-export([terminate/2]).
-export([code_change/3]).

-record(state, {
    node = node()        :: node(),
    ring = ordsets:new() :: ordsets:ordset(node()),
    data = dict:new()    :: dict:dict(term(), term())
}).

% Public API
start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

erase(Key) ->
    write({erase, Key}).

find(Key) ->
    read({find, Key}).

store(Key, Value) ->
    write({store, Key, Value}).

% Ring API
join(Node) ->
    gen_server:call(?MODULE, {join, Node}).

nodes() ->
    gen_server:call(?MODULE, nodes).

read(Request) ->
    gen_server:call(?MODULE, {read, Request}).

write(Request) ->
    gen_server:call(?MODULE, {write, Request}).

write(Node, Request) ->
    gen_server:call(?MODULE, {write, Node, Request}).

% gen_server
init([]) ->
    State = #state{},
    {ok, State}.

handle_call({join, Node}, _From, State=#state{node=Node}) ->
    {reply, ok, State};
handle_call({join, Peer}, From, State=#state{node=Node, ring=Ring}) ->
    case net_adm:ping(Peer) of
        pong ->
            case ordsets:is_element(Peer, Ring) of
                true ->
                    {reply, ok, State};
                false ->
                    monitor_node(Peer, true),
                    NewRing = ordsets:add_element(Peer, Ring),
                    spawn(fun() ->
                        rpc:multicall(Ring, ?MODULE, join, [Peer])
                    end),
                    spawn(fun() ->
                        Reply = rpc:call(Peer, ?MODULE, join, [Node]),
                        gen_server:reply(From, Reply)
                    end),
                    {noreply, State#state{ring=NewRing}}
            end;
        pang ->
            {reply, {error, connection_failed}, State}
    end;
handle_call(nodes, _From, State=#state{node=Node, ring=Ring}) ->
    {reply, ordsets:add_element(Node, Ring), State};
handle_call({read, Request}, From, State) ->
    handle_read(Request, From, State);
handle_call({write, Request}, From, State=#state{node=Node, ring=Ring}) ->
    spawn(fun() ->
        rpc:multicall(Ring, ?MODULE, write, [Node, Request])
    end),
    handle_write(Request, From, State);
handle_call({write, Node, _Request}, _From, State=#state{node=Node}) ->
    {reply, ok, State};
handle_call({write, _Peer, Request}, From, State) ->
    handle_write(Request, From, State);
handle_call(_Request, _From, State) ->
    {reply, ignore, State}.

handle_cast(_Request, State) ->
    {noreply, State}.

handle_info({nodedown, Peer}, State=#state{ring=Ring}) ->
    NewRing = ordsets:del_element(Peer, Ring),
    {noreply, State#state{ring=NewRing}};
handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%% @private
handle_read({find, Key}, _From, State=#state{data=Data}) ->
    {reply, dict:find(Key, Data), State}.

%% @private
handle_write({erase, Key}, _From, State=#state{data=Data}) ->
    {reply, ok, State#state{data=dict:erase(Key, Data)}};
handle_write({store, Key, Value}, _From, State=#state{data=Data}) ->
    {reply, ok, State#state{data=dict:store(Key, Value, Data)}}.

If we start 3 different nodes with the -sname set to node0, node1, and node2:
erl -sname node0 -setcookie cook -run node_ring start_link
erl -sname node1 -setcookie cook -run node_ring start_link
erl -sname node2 -setcookie cook -run node_ring start_link

Here's how we join a node to the ring:
(node0@localhost)1> node_ring:nodes().
['node0@localhost']
(node0@localhost)2> node_ring:join('node1@localhost').
ok
(node0@localhost)3> node_ring:nodes().
['node0@localhost', 'node1@localhost']

If we run node_ring:nodes() on node1 we get:
(node1@localhost)1> node_ring:nodes().
['node0@localhost', 'node1@localhost']

Now let's go to node2 and join one of the other two nodes:
(node2@localhost)1> node_ring:nodes().
['node2@localhost']
(node2@localhost)2> node_ring:join('node0localhost').
ok
(node2@localhost)3> node_ring:nodes().
['node0@localhost', 'node1@localhost',
 'node2@localhost']

Notice how both node0 and node1 were added to node2, even though we only specified node0 on the join.  This means if we had hundreds of nodes, we would only need to join one of them in order to join the entire ring.
Now we can use store(Key, Value) on any of the nodes and it will be replicated to the other two:
(node0@localhost)4> node_ring:store(mykey, myvalue).
ok

Let's try reading mykey from the other two, first node1:
(node1@localhost)2> node_ring:find(mykey).
{ok,myvalue}

Then node2:
(node2@localhost)4> node_ring:find(mykey).
{ok,myvalue}

Let's use erase(Key) on node2 and try to read the key again on the other nodes:
(node2@localhost)5> node_ring:erase(mykey).
ok

On node0:
(node0@localhost)5> node_ring:find(mykey).
error

On node1:
(node1@localhost)3> node_ring:find(mykey).
error

Awesome!  We have a distributed decentralized ring that can act as a simple key/value store!  That was easy, not hard at all!  As long as we don't have any nodes go down, packet loss, network partitions, nodes added to the ring, or some other form of chaos, we have a near-perfect solution here.  In reality, however, you have to account for all of those things in order to have a system that won't drive you crazy in the long run.
Here's a brief example of something our little node_ring can't handle:

*

*node1 goes down

*node0 stores key a and value 1

*node1 comes back up and joins the ring

*node1 tries to find key a
First, let's kill node1.  If we check the nodes on node0:
(node0@localhost)6> node_ring:nodes().
['node0@localhost','node2@localhost']

And on node2:
(node2@localhost)6> node_ring:nodes().
['node0@localhost','node2@localhost']

We see that node1 has been removed from the ring automatically.  Let's store something on node0:
(node0@localhost)7> node_ring:store(a, 1).
ok

And read it from node2:
(node2@localhost)7> node_ring:find(a).
{ok,1}

Let's start up node1 again and join the ring:
(node1@localhost)1> node_ring:join('node0@localhost').
ok
(node1@localhost)2> node_ring:nodes().
['node0@localhost','node1@localhost',
 'node2@localhost']
(node1@localhost)3> node_ring:find(a).
error

Whoops, we have inconsistent data across the ring.  Further study of other distributed systems and CAP theorem is necessary before we can decide how we want our little node_ring to behave in these different situations (like whether we want it to behave like an AP or a CP system).


text:
Q: How can I change a QLABEL in real time with PyQt I'm creating a small macro recorder and I can't replicate the real-time coordinates in the QLabel, would anyone know how to do this?
*self.findcoordsbutton.clicked.connect(self.get_coords)
self.CoordsGeradas.setText(?what do i put here?)*
print


text:
Q: How can i display the total no of books belonging to a rack? Here is my table of books tbl_books
CREATE TABLE IF NOT EXISTS `tbl_books` (
  `book_id` int(11) NOT NULL AUTO_INCREMENT,
  `book_title` varchar(255) NOT NULL,
  `book_author` varchar(255) NOT NULL,
  `book_year` varchar(255) NOT NULL,
  `book_rack` varchar(255) NOT NULL,
  PRIMARY KEY (`book_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Here is my second table of rack tbl_rack
CREATE TABLE IF NOT EXISTS `tbl_rack` (
  `rack_id` int(11) NOT NULL AUTO_INCREMENT,
  `rack_name` varchar(255) NOT NULL,
  PRIMARY KEY (`rack_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Problem which i want to solve:
I want to display all the data of rack in a table
Id       Name  Total no books in this rack ?
How can i display the total no of of books which are belongs to a specific rack..??/
Please help

A: you can loop through your racks and count each book on that rack ( I take it tbl_books.book_rack = tbl_rack.rack_name and you know how to connect to your database with pdo and your connection is called $db)
    $rack = $db->query('select distinct rack_name from tbl_racks');
    $rack->execute(); $result = $rack->fetch_all('PDO::FETCH_ASSOC');

    foreach($result as $r){
        $books = $db->query('count(book_id) as num_books from tbl_books where book_rack = :book_rack');
        $books->execute(array("book_rack"=>$r['rack_name']));
        $b = $books->fetch('PDO::FETCH_ASSOC');
         echo $b['num_books'];
     }


text:
Q: Jasmine, clicking a div with 'button' role I have a mat-table in an angular component, it uses matSort in the headers and i would like to test that my table is changed after clicking on the sorting option.
 it('Should properly sort table', () => {
        const compiled = fixture.debugElement.nativeElement;
        const table = compiled.querySelector('table');
        const buttons = compiled.querySelectorAll('div.mat-sort-header-container');
        buttons[0].click();
        fixture.detectChanges();
        const reCompiled = fixture.debugElement.nativeElement;
        const sortedTable = reCompiled.querySelector('table');
        console.log(table === sortedTable); //Returns true
    });

Unlike other questions similar to mine, i found out that my button is not a real html button but a div with role 'button':

My suspect is that the button is not clicked because the table is not changed after the clicking.
Any tip is welcome


text:
Q: Assign Class Methods to an already established element? I'm developing some Ruby projects. I'm still learning some basic tenets of Ruby, but I need some help with a particular problem I've been having.
I need to assign some already-created elements with the methods associated with a class. How can I go about doing that?
Here's my example.
Let's say that I have an array of arrays
my_pets = ['Buddy the iguana', 'Coco the cat', 'Dawn the parakeet']

And I also have a class for which I've written a particular function that I need the my_pets array to access. Basically, this function loops through an array of strings and replaces the "a" with "@".
class Cool_Pets

    def a_replace(array)
        array.each do |string|
            if string.include?("a")
                string.gsub!(/a/, "@")
            end
        end
     puts string
   end

end

Is there a way to assign my_pets as part of the Cool_Pets class so that it can use the a_replace method?
Here's my desired result:
a_replace(my_pets) = ['Buddy the igu@na', 'Coco the c@t', 'D@wn the p@r@keet']

A: You could use Enumerable#map here:
my_pets.map{ |s| s.gsub(/a/,'@') }
#=> ["Buddy the igu@n@", "Coco the c@t", "D@wn the p@r@keet"]

Your code almost works, just remove puts array and the if statement. Then just call the function.
#Use CamelCase for class names NOT snake_case.
#Using two spaces for indentation is sensible.
class CoolPets
  def a_replace(array)
    array.each do |string|
      string.gsub!(/a/, "@")
    end
  end
end

cool = CoolPets.new
my_pets = ['Buddy the iguana', 'Coco the cat', 'Dawn the parakeet']
p cool.a_replace(my_pets)
#=> ["Buddy the igu@n@", "Coco the c@t", "D@wn the p@r@keet"]

A: Not sure if this is what you're looking for, but check out Mixins: http://ruby-doc.com/docs/ProgrammingRuby/html/tut_modules.html#S2
module CoolPet
  def a_replace(array)
    array.each do |string|
      if string.include?("a")
        string.gsub!(/a/, "@")
      end
    end

    puts array.inspect
  end
end

class MyPet
  include CoolPet
end

array = ['Buddy the iguana', 'Coco the cat', 'Dawn the parakeet']
pet = MyPet.new
pet.a_replace(array) # => ["Buddy the igu@n@", "Coco the c@t", "D@wn the p@r@keet"]


text:
Q: Demonstrate that a function is periodic knowing symmetry axis. Let
$$f:\mathbb{R}\rightarrow \mathbb{R}$$
with symmetry axis at $x = {1,2}$.
Demonstrate that the function is periodic.

A: We have for all $x\in \mathbb R$
$$f(1+x)=f(1-x)$$
and
$$f(2+x)=f(2-x)$$
by assumption.
So that gives us
$$f(2+x) = f(2-x) = f(1-(-1+x)) = f(1+(-1+x)) = f(x). $$
So we have shown periodicity with period $2$.


text:
Q: $.ajax() data parameter order Let's say my model looks like this:
public class someModel{
    public int age {get; set;}
    public string affiliation {get;set;}
    public string name {get;set;}
}

And when I post from form someForm:
var request;
$('someForm').submit(function (event) {
        if (request) {
            request.abort();
        }
        request = $.ajax({
            url: '/Home/addRecordResult',
            data: {
                affiliation: $('#affInput').val(),
                name: $('#nameInput').val(),
                age:$('#ageInput').val()
            },
            type: 'POST'
        });

in the data parameter in the Ajax method, does the order of inputs matter? Does it always have to be age then affiliation then name?

A: I would say "no", it doesn't matter


text:
Q: Getting NaN value from loss function for k-fold validation I am trying to implement MNIST using PyTorch Lightning. Here, I wanted to use k-fold cross-validation.
The problem is I am getting the NaN value from the loss function (for at least 1 fold). From below 3rd time, I was getting NaN values from the loss function.
Epoch 19: 100%|█████████████████████████████████| 110/110 [00:03<00:00, 29.24it/s, loss=0.963, v_num=287]
Testing: 100%|███████████████████████████████████████████████████████████| 28/28 [00:00<00:00, 39.94it/s]

Epoch 19: 100%|█████████████████████████████████| 110/110 [00:04<00:00, 25.69it/s, loss=0.825, v_num=288]
Testing: 100%|███████████████████████████████████████████████████████████| 28/28 [00:00<00:00, 41.19it/s]

Epoch 19: 100%|███████████████████████████████████| 110/110 [00:03<00:00, 30.19it/s, loss=nan, v_num=289]
Testing: 100%|███████████████████████████████████████████████████████████| 28/28 [00:00<00:00, 42.15it/s

Or very big loss value (terminated before completing full epocs)
Epoch 0:  44%|█████████████▉                  | 48/110 [00:02<00:02, 22.87it/s, loss=2.08e+23, v_num=295]

The code I have used for data preparation, k-fold, and trainer is given below
def prepare_data():
  transform=transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.1307,), (0.3081,))])
  mnist_train = MNIST(os.getcwd(), train=True, download=True, transform=transform)
  mnist_test = MNIST(os.getcwd(), train=False, download=True, transform=transform)
  dataset = ConcatDataset([mnist_train, mnist_test])
  return dataset

k_folds=5
epochs=20

kfold=KFold(n_splits=k_folds,shuffle=True)

dataset = prepare_data()
model = LightningMNIST(lr_rate=0.01)

for fold, (train_idx, val_idx) in enumerate(kfold.split(dataset)):
  train_subsampler = torch.utils.data.SubsetRandomSampler(train_idx)
  val_subsampler = torch.utils.data.SubsetRandomSampler(val_idx)

  train_loader = torch.utils.data.DataLoader(dataset, num_workers=8, batch_size=512, sampler=train_subsampler)
  val_loader = torch.utils.data.DataLoader(dataset, num_workers=8, batch_size=512, sampler=val_subsampler)
  model.apply(reset_weights) # reset model for every fold
  early_stopping = EarlyStopping('train_loss', mode='min', patience=5)
  model_checkpoint = ModelCheckpoint(dirpath=model_path+'mnist_{epoch}-{train_loss:.2f}',
                                        monitor='train_loss', mode='min', save_top_k=3)
  trainer = pl.Trainer(max_epochs=epochs, profiler=False, callbacks = [model_checkpoint],default_root_dir=model_path)
  trainer.fit(model, train_dataloader=train_loader)
  trainer.test(test_dataloaders=val_loader, ckpt_path=None)

The training step is given below
  def training_step(self, train_batch, batch_idx):
    x, y = train_batch
    logits = self.forward(x)
    loss = self.error_loss(logits.squeeze(-1), y.float())
    self.log('train_loss', loss)
    return {'loss': loss}

I assume, maybe I am doing something wrong in the k-fold data preparation or in the training step. Otherwise getting NaN or very big value is not expected for this simple problem and simple model.
I have gone through several posts like this, this, and that. Some of them suggested that it could happen because the dataset might contain NaN (but I think MNIST does not contain NaN as directly downloading from the module), model's learning rate is 0.01 (not too big not too small). Moreover, I believe that this post is not duplicated (because here, trying to use k-fold thought the error seems the same).
Any suggestions?


text:
Q: Rewrite for loop that is slowing down in python I have a for loop that is slowing down as it is processing a list of raster files (same operation on every file in the list). The initial items in the list are processed in a second or two, while toward the end of the 220 item list, time is ~ 30 seconds. Once the script exits the for loop and starts another list of files, it resets and the initial processing takes a second or two. So I think the issue is the loop itself.
Here is pseudo code as to what I have:
files = ['file1.tif', 'file2.tif', . . . ,'file222.tif']

for file in files:
    start_time = time.time()
    process file here
    outfile.save('out.tif')
    del all processing files
    print("--- %s seconds ---" % (time.time() - start_time))
    gc.collect()

I just can't understand why it is slowing down so much, and am wondering if there is a better way to write this loop.


text:
Q: In Windows how can I remove a word of all my folders' name? I have lots of folders (more than 500) that their name ends with a specific word. How can remove all of them at once?

A: If you just want to remove last few names then you can do the following.
Just make a .bat file from the following code and copy to the folder where you want to execute it. Run it. This example is for renaming the folder so that the first 8 characters are preserved. If you want more or less you can change as you desire.
@echo off
setlocal disableDelayedExpansion
for /d %%A in (*) do (
  set "folder=%%A"
  setlocal enableDelayedExpansion
  ren "!folder!" "!folder:~0,8!"
  endlocal
)


text:
Q: Power BI - setup day 1 based on value in another column I have table in Power BI with following columns: Country, Date and event. I would like to add measure or new column if needed with 'Start Day'. 'Start Day' assignes value '1' at the first day that value greater than 0 apears in column 'event' and  starts counting days from this date. In example below for country UK value 1 in column 'event' apears on 19/03/2020 and in column 'Start Day' value 1 is assigned. Next date 20/03/2020 has value 2 assigned and so on. What is the best way to do this in Power BI?
Robert

A: You need to create an extra column as this is static data.
You can do this by first getting the start date of that country and then take the datediff between the dates.
In the CALCULATE function, I get all rows where the country is equal and where the event = 0. From those rows, I get the max date (firstD). This was the most important step as we can now use the DATEDIFF to calculate the days.
I used the max function once more because you want to have 0 in the rows before the startdate.
Start Day =
var country = events[Country]
var firstD = CALCULATE(MAX(events[Date]);FILTER(events;events[Country] = country && events[event]=0))
return max(DATEDIFF(firstD;events[Date];DAY);0)


text:
Q: google sheets increment selected cells How would I write a script that increments the selected cells. Here is code for incrementing one selected cell. Cells will always contain natural numbers.
function increment() {

  var currentCell = SpreadsheetApp.getCurrentCell();
  var value = currentCell.getValue();
  currentCell.setValue(value+1);

}

I want something like this if possible
function increment(){
  var selectedCells = SpreadsheetApp.getSelectedCells();
  selectedCells.forEach( (e) => {
    e.setValue(e.getValue() + 1 );
  });

}

A: Selections do not need to be contiguous, so to implement this in a generic fashion, you will have to iterate a RangeList object and use range.getValues().
The getValues() call will return a 2D array. One easy way to iterate the values in the array is to use a map.map pattern. Try this:
function increment() {
  SpreadsheetApp.getActiveRangeList()
    .getRanges().forEach(range => {
      const values = range.getValues()
        .map(row => row
          .map(value => (Number(value) || 0) + 1)
        );
      range.setValues(values);
    });
}


text:
Q: how can i get profit for today, last 7 days and last 30 days using laravel I have a profit table in my database, when I retrieve data from database I need to filter profit according to date (for today, last 7 days, last 30 days).
In my controller, I tried,
$todayProfit = Profit::whereDate('created_at',today())->get();
return response()->json($todayProfit);

but it provides only 24 hours, but I need today profit.
when i retrieve data to last 30 days using,
$lastMonthProfit = Profit::whereDate('created_at',today()->subDay(30))->get();
return response()->json($lastMonthProfit );

it is not working for me,
how can I solve

A: The query for calculating all in a single one could be;
SELECT 'Today' as date, sum(profit) as total FROM profits
WHERE created_at > DATE_ADD(CURDATE(), INTERVAL -1 DAY)
UNION
SELECT 'Last 7 days', sum(profit) FROM profits
WHERE created_at > DATE_ADD(CURDATE(), INTERVAL -7 DAY)
UNION
SELECT 'Last 30 days', sum(profit) FROM profits
WHERE created_at > DATE_ADD(CURDATE(), INTERVAL -30 DAY)
UNION
SELECT 'All', sum(profit) from profits;

The query builder version;
return Profit::where('created_at', '>', DB::raw('DATE_ADD(CURDATE(), INTERVAL -1 DAY)'))
        ->select([DB::raw('"Today" as date'), DB::raw('sum(profit) as total')])
        ->union(
            Profit::where('created_at', '>', DB::raw('DATE_ADD(CURDATE(), INTERVAL -7 DAY)'))
                ->select([DB::raw('"Last 7 days"'), DB::raw('sum(profit) as total')])
        )
        ->union(
            Profit::where('created_at', '>', DB::raw('DATE_ADD(CURDATE(), INTERVAL -30 DAY)'))
                ->select([DB::raw('"Last 30 days"'), DB::raw('sum(profit) as total')])
        )
        ->union(
            Profit::select([DB::raw('"All"'), DB::raw('sum(profit) as total')])
        )
        ->get();

it prints something like these;
[
    {
        "date": "Today",
        "total": "50"
    },
    {
        "date": "Last 7 days",
        "total": "145"
    },
    {
        "date": "Last 30 days",
        "total": "360"
    },
    {
        "date": "All",
        "total": "695"
    }
]

A: You are trying to get only data of 30 days ago not from 30 days ago till now. To solve that problem maybe you should use whereBetween. Try this and let me know if it solves your problem.
$todayProfit = Profit::whereBetween('created_at', [now()->startOfDay(), now()]);

$lastMonthProfit = Profit::whereBetween('created_at', [now()->subMonth(), now()]);

A: Try this code get data to last 30 days using,
$date = Carbon::today()->subDays(30);
$lastMonthProfit = Profit::where('created_at','>=',$date)->get();
return response()->json($lastMonthProfit );

last 7 days
$date = Carbon::today()->subDays(7);
$lastSevenDayProfit = Profit::where('created_at','>=',$date)->get();
return response()->json($lastSevenDayProfit );

today
$todayProfit = Profit::whereDate('created_at', Carbon::today())->get();
return response()->json($todayProfit,200);


text:
Q: How to calculate conditional average in data frame in R? Suppose we have a data set, a snippet looks like:
count  party  gender
0      Rep    F
2      Rep    M
3      Rep    F

I'm trying to calculate the average value of the count column if party = Rep and gender = F. I.e. it should be 1.5 here. How can this be written in R code?

A: Does this work:
library(dplyr)
dat %>% filter(party == 'Rep' & gender == 'F') %>% summarise(avg = mean(count))
# A tibble: 1 x 1
    avg
  <dbl>
1   1.5

A: If you want to use base R:
mean(df[(df$party == 'Rep' & df$gender == 'F'),]$count)

A: Using data.table:
setDT(dt)
dt[, mean(count), .(party, gender)]

Output:
   party gender  V1
1:   Rep      F 1.5
2:   Rep      M 2.0

This will calculate the mean of count for all party-gender pairs, in the case that you want to include all combinations (not just only Rep/F).
Data:
dt = read.table(text = 'count  party  gender
0      Rep    F
2      Rep    M
3      Rep    F
', header = T)


text:
Q: Is there an property value named invisible? Instead using of:
if ( ! $('#XX').is(':visible) )
Is there a value called invisible ? I tried that one , but doesn't work.
Thanks !

A: There is a .not() function, that does the opposite to .is():
.not(':visible')

http://api.jquery.com/not/

A: ':hidden'

if ($('#XX').is(':hidden))

See the jQuery doc for :hidden.


text:
Q: How does a regression tree split the y variable How does a regression tree split the y variable? Is it just a case of even chunking of the range or are the chunks of variable size?

A: The target variable is not split, features are. And, this is typically done via a greedy search over the features and possible thresholds. In the end, usually, the target variable of the samples in the leaves are averaged for outputting a prediction.


text:
Q: SQL Left join Query Issue I have the following tables
Users
ID Name
1  John Smith
2  James Jones
3  Peter Brown

Purchases
USERID   NAME
1        Apple
1        Pear
1        Banana
2        Apple
2        Pear
3        Apple

How can i have a sql query that returns users that brought (apple & pear & banana)
So in the above tables it would return only 'John Smith'
Thanks

A: This is an example of a set-within-sets query.  A flexible way to solve this is using group by and having:
select userid
from purchases
where name in ('apple', 'pear', 'banana')
group by userid
having count(*) = 3;

To get the name, you would join in the Users table.
If, unlike in your sample data, duplicates are allowed in the table, then use count(distinct name) = 3 in the having clause.

A: You can JOIN both tables and COUNT products:
SELECT u.Name
FROM Purchases p
JOIN Users u
  ON p.UserID = u.ID
WHERE p.Name IN ('Apple', 'Pear', 'Banana')
GROUP BY userid
HAVING COUNT(DISTINCT p.Name) = 3;

SqlFiddleDemo
There is possibility that user has bought 2 apples and one banana so you should count distinct product names.
If you are using Postgresql/SQL Server/Oracle you need to wrap Name with aggregation function:
SELECT MAX(u.Name) AS Name
FROM Purchases p
JOIN Users u
  ON p.UserID = u.ID
WHERE p.Name IN ('Apple', 'Pear', 'Banana')
GROUP BY userid
HAVING COUNT(DISTINCT p.Name) = 3;

A: SQL Fiddle
SELECT users.name, purchased.items
FROM users
INNER JOIN (
  select userid as id, array_agg(distinct name) items
  from purchases
  group by userid
  having array_length(array_agg(distinct name),1)=3
) purchased USING(id);

This does not work if you are only looking for those specific items.  If there are other items that could be purchased and you are only looking for users that purchased those specific items, you would have to do something similar to what Gordon, with a correction for the number of times an item was purchased.


text:
Q: nested subprocess not stopping I have 3 files:
sleeper.py
import subprocess

print('start sleeper')
subprocess.run(['sleep', '10'])
print('end sleeper')

waker.py
import subprocess

print('The waker begins')
try:
    subprocess.run(['python3', 'sleeper.py'], timeout=5)
except subprocess.TimeoutExpired:
    pass
print('The waker ends')

awake.py
import subprocess

print('Awake begin')
try:
    subprocess.run(['python3', 'waker.py'], timeout=2.5)
except subprocess.TimeoutExpired:
    pass
print('Awake end')

and I run python3 awake.py.
but get the following output:
Awake begin
The waker begins
start sleeper
Awake end
end sleeper

actually to be more accurate I get the first 3 lines printer immediatly, then 2.5 seconds later the 4th line prints and I get my bash prompt, then 7.5 seconds later end sleeper appears on my bash prompt.
how do I make it so killing a subprocess via timeout also kills the subprocesses run by that subprocess?

A: run should terminate the child process when the timeout expires. Does it terminate children as well? it doesn't seem so in your case. A workaround would be to use Popen, poll for the timeout, and kill process & children.
Seems that you cannot have it both ways: use run and be sure that all subprocesses are terminated (when you get a TimeoutException the process is already killed so you lose track of children)
proc = subprocess.Popen(args, stderr=errFile, stdout=outFile, universal_newlines=False)
wait_remaining_sec = 2.5

while proc.poll() is None and wait_remaining_sec > 0:
    time.sleep(0.5)
    wait_remaining_sec -= 0.5

if proc.poll() is None:
   # process is still there: terminate it and subprocesses:
   import psutil

   parent_pid = proc.pid  # we get the process pid
   parent = psutil.Process(parent_pid)
   for child in parent.children(recursive=True):
      child.kill()
   parent.kill()

The poll loop is better than a bare time.sleep(2.5) call because if process ends before timeout, you don't want to wait 2.5 seconds. This doesn't induce more than a 0.5s delay if the process ends before.
References:

*

*Using module 'subprocess' with timeout

*how to kill process and child processes from python?


text:
Q: Trimming all leading and trailing namespaces after splitting the word I have a scenario in C#:
Input is->
Sachin.Dutta :  trimbegging space :: delete spaceafter

Expected output->
Sachin.Dutta:trimbegging space::delete spaceafter

First,I need to split the string based on : or ::
Then trim whitespaces from beginning and end of every word
Then combine the words to get expected output.
I can write code using for loop to separate words and again recombine them.But,is there any better way using LINQ or Regex for this ?

A: Use Regex with pattern @"\s*:\s*"
var input = "Sachin.Dutta :  trimbegging space :: delete spaceafter";
var result = Regex.Replace(input, @"\s*:\s*", ":");

Output
Sachin.Dutta:trimbegging space::delete spaceafter

Explanation

*

*\s* matches any whitespace character (equal to [\r\n\t\f\v ])

*

** Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

*: matches the character : literally (case sensitive)

*\s* matches any whitespace character (equal to [\r\n\t\f\v ])

*

** Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)


text:
Q: Apply style for parent element when it is focused  **CSS**

    #child:focus > #parent {
    color: white;
    }

    **HTML**

Is this the correct way to apply styles for parent when child is focused ?
Edit: My problem is I need to apply these styles for small devices. So I can't use Jquery. Thats why I am trying within media query in css.

A: You can also use jQuery for this:
$('#child:focus').parent().addClass('your_class');

A: First, you need to add a tabindex  attribute to your divs, or they can never receive the focus.
I have also included the code to remove the CSS class from the parent when the child loses focus.

$("#child").focusin(function() {
  $(this).parent().addClass("focused");
});
$("#child").blur(function() {
  $(this).parent().removeClass("focused");
});
.focused {
  background: red;
}

  Parent Top

    Child

  Parent Bottom

A: CSS have not selector for select up level ... you need solve the your problem use JS

A: For this particular need was :focus-within pseudoclass implemented in CSS. In your example following CSS would do what you try to accomplish. I added tabindex to #child to make the div focusable. It is not necessary for elements natively focusable (eg. links or form elements). However, it is not supported by IE and Edge. Edge will support it after planned switch to Blink rendering engine.
See also this CSS Tricks article.

#parent {
  padding: 0.25em;
   background-color: crimson;
}

#parent:focus-within {
  color: white;
}

Parent

Child (click me!)

A: You can do this quite simple using JQuery:

$(document).ready(function(){
if ($(window).width() < 960) {
    $('.child input').on('focus', function(){
    $('.parent').css({
    'background-color': 'blue'
    });
 });
   $('.child input').on('blur', function(){
    $('.parent').css({
    'background-color': 'lightgrey'
    });
 });
}

});
.parent {
 width: 300px;
 height: 300px;
 display: block;
 background: lightgrey;
}
input {
  width: auto;
}

<input type="text">

A: This is possible by 4th Level selecor pseudo-class that works the same as the jQuery implementation.
#parent:has(> #child) { /* styles to apply to the #parent */ }

but this is not currently supported by browsers.
why we don't have a parent selector