text:
Q: Get image post ID in media upload I am developing a plugin that adds a Custom Post Type to my theme.  It's a retail directory and the post type is a retail listing.
Everything is working fine. I can upload content to the DB and then print in a customized CSS framework I have developed.  However, when i want to upload and display an image, that's when I have problems.
The problem occurs when the image is uploaded.  I use the update_post_meta() to update the meta information of the image which is related it to the post ID and post it to the database table "wp_postmeta" under column "meta_value".  I also use the WP media upload JQuery Code to select the image.  I'm not sure where the problem is exactly, but I know it's with the upload because when the image goes into the "meta_value" column has value NaN and not the ID value that it should be.
Here's the upload code:
add_action( 'save_post', 'process_image_meta', 10, 2 );

function process_image_meta( $post_id, $post ) {
        update_post_meta( $post_id, '_image_id', $_POST['upload_image_id'] );
    }

And the wp media uploader code:
And finally, the display code:
function display_retail_listing_meta_box($retail_listing) {
    // Retrieve current shop details based on retail lisitng ID

    global $post;

        $image_src = '';
    $image_id = get_post_meta( $post->ID, '_image_id', true);
    $image_src = wp_get_attachment_url( $image_id );
?>

Image Upload
<img id="shop_image" src="<?php echo $image_src; ?>" style="max-width:100%;" />
<input type="text" name="upload_image_id" id="upload_image_id" value="<?php echo $image_id; ?>" />
<a title="<?php esc_attr_e( 'Upload Image' ) ?>" href="#" id="upload-image"><?php _e( 'Upload Image' ) ?>
<a title="<?php esc_attr_e( 'Remove Image' ) ?>" href="#" id="remove-image" style="<?php echo ( ! $image_id ? 'display:none;' : '' ); ?>"><?php _e( 'Remove Image' ) ?>

Followed by the WP Media Upload Code:
jQuery(document).ready(function($) {

        // save the send_to_editor handler function
        window.send_to_editor_default = window.send_to_editor;

        $('#upload-image').click(function(){

            // replace the default send_to_editor handler function with our own
            window.send_to_editor = window.attach_image;
            tb_show('', 'media-upload.php?$post_id=<?php echo $post->ID ?>&type=image&TB_iframe=true');

            return false;
        });

        $('#remove-image').click(function() {

            $('#upload_image_id').val('');
            $('img').attr('src', '');
            $(this).hide();

            return false;
        });

        // handler function which is invoked after the user selects an image from the gallery popup.
        // this function displays the image and sets the id so it can be persisted to the post meta
        window.attach_image = function(html) {

            // turn the returned image html into a hidden image element so we can easily pull the relevant attributes we need
            $('body').append('
' + html + '
');

            var img = $('#temp_image').find('img');

            imgurl   = img.attr('src');
            imgclass = img.attr('class');
            imgid    = parseInt(imgclass.replace(/\D/g, ''), 10);

            $('#upload_image_id').val(imgid);
            $('#remove-image').show();

            $('img#shop_image').attr('src', imgurl);
            try{tb_remove();}catch(e){};
            $('#temp_image').remove();

            // restore the send_to_editor handler function
            window.send_to_editor = window.send_to_editor_default;

        }

    });
    </script>

A: The action sends the $post_id just like you have so that's not the problem.
Have you tried a var_dump of $_POST to make sure it's actually posting something other than null?
Also, using the save_post action is going to be called every time a post is saved, so you probably need to use the save_post_{custom_post_type} action, replacing {custom_post_type} with your actual custom post type (if it is one).
You could try this:
function process_image_meta( $post_id, $post ) {
        error_log('POSTED: ' . $_POST['upload_image_id']);
        $result = update_post_meta( $post_id, '_image_id', $_POST['upload_image_id'] );
        error_log('Image Meta Added: ' . $result);
    }

Make sure you have this in your wp-config.php:
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

Then check the /wp-content/debug.log file for the output

A: i think the problem is in your save meta values function, try with global $post;
function process_image_meta() {
    global $post, $post_id;
    update_post_meta( $post_id, '_image_id', $_POST['upload_image_id'] );
}


text:
Q: Does $\lim_{n\to \infty}\sigma_n=0\implies \lim_{n\to \infty} a_n=0$? Let $\{a_n\}$ be a sequence of positive real numbers such that $\lim_{n\to \infty} \sigma_n=0$ where $\sigma_n=\left(\sum_{k=1}^n a_k\right)/n$.

Does $\lim_{n} \sigma_n=0\implies \lim_n a_n=0$?

I feel that this should be true but I cannot find a proof for this nor can I find a counterexample. I tried my hand at the proof in the following way:
Since $a_n=n\sigma_n-(n-1)\sigma_{n-1},\ n\ge 2$, we have $\lim_n a_n/n=0$. Also, it is not difficult to prove that $\lim\inf_n a_n=0,\ L:=\lim\sup_n\ge 0$. But then I am stuck.
I will really appreciate short hints, rather than a full answer. Thanks in advance.

A: Hint:
Consider $a_n = 1$ when $n$ is a perfect square, and $a_n=0$ when $n$ is not a perfect square.
Show that in this case you have
$$\sigma_n =\frac{\lfloor \sqrt{n} \rfloor}{n}$$
Note that if by positive you mean strictly positive, then you can add $a_n$ to any positive sequence converging to 0 : $\frac{1}{n}+a_n$ will do.

A: This is called Cesàro convergence.  For a sequence $a_n$, define
$\sigma_n = \frac{1}{n}\sum_{k=1}^n a_k$.  Then (I) implies (II):
$$
{\rm(I)}\qquad a_n \to L
\\
{\rm(II)}\qquad \sigma_n \to L
$$
But "in general" (II) does not imply (I).  [See the other answers.]  But under "some conditions", (II) does imply (I).  Such a condition may be known as a Tauberian condition.
Ref: https://en.wikipedia.org/wiki/Abelian_and_tauberian_theorems

redpajama_set_name: RedPajamaStackExchange


text:
Q: Onenote Api calls return internal server error 500 we have developed a web app for add students in class notebooks for an academy. I recently noticed  the API is returning a 500 error when we make a call:
"error": {
"code": "10001",
"message": "An unexpected server error has occurred. Please try again later."

And this is our POST call:
https://www.onenote.com/api/v1.0/myorganization/siteCollections/{site collection id}/sites/{site id}/notes/classNotebooks/{notebook id}/Students

Site id and notebook id changes depending of the SharePoint Team Site.
We have not applied any change recenlty in this function and was working fine...
Can someone help me? it's a problem of the service?
thanks in advance.

A: This was an incident on our side and has been since resolved - please let us know if you are still seeing this. In the future, feel free to open a ticket to us here: https://aka.ms/edusupport


text:
Q: Using conditionally compiled functions in rust benchmarks Before I begin, let me note that I think there have been many related questions and answers, all of which proved useful to me. However, I couldn't find anyone who thoroughly described a method to do everything I wanted, so I thought I would document the problem and my solution and ask if there were better approaches.
Let's suppose that I have some slow--but definitely correct--code to perform a certain task that I keep in my project to test a faster implementation. For concreteness, define:
pub fn fast(x: T) -> U {
  // does stuff and eventually returns a value `out`
  // ...
  debug_assert_eq!(out, slow(x))
  out
}

#[cfg(any(test, debug_assertions))]
pub fn slow(x: T) -> U { ... }

This is all fine and good. However, now suppose that I would like to add some benchmarks to demonstrate how good my fast implementation is...
Attempt 1: Criterion
I think that a standard way to set up benchmarking is to put a benches/ directory in the project, add a [[bench]] to Cargo.toml with the harness disabled, and use the criterion crate. However, if I understand correctly, if we then run cargo bench, the benchmark will have to take the position of a user that cannot access crate features defined only during testing. Thus, slow will not be resolved and the command will fail.
A Quick Aside: Another thing that derailed me for a while is that I kept wanting to use bench as a cfg flag but couldn't find anything about this. As it turns out, I think that test also covers the benching case. (I think all the seasoned rustaceans will be laughing at me, but this seems like a useful thing to note for anyone in a similar situation).
Attempt 2: The Nightly Test Crate
Since the previous method didn't seem fruitful, another popular option seemed to be to use the unstable test crate. This results in a project structure that looks like:
Cargo.toml
src/
  lib.rs
  bench.rs

Our original file is then revised to be:
// Include the unstable feature
#![feature(test)]

pub fn fast(x: T) -> U { ... }

#[cfg(any(test, debug_assertions))]
pub fn slow(x: T) -> U { ... }

#[cfg(test)]
mod bench;

And then bench.rs should look something like:
extern crate test;
use test::Bencher;

#[bench]
fn bench_it(b: &mut Bencher) {
  b.iter(|| {}) // gotta go fast
}

This seemed to do everything I wanted upon running cargo +nightly bench. However, it is also super desirable for the project to be compilable outside of testing without the use of nightly or extra feature flags. That is, I still want to be able to run cargo build and cargo test and not get yelled at for requesting unstable features on a stable channel.
Attempt 2.5: Enter Build Scripts
(Once again, each of the parts is well-documented in other questions, I'm just collecting everything here for fun). Using a bunch of other posts, I learned that we can check for nightly and conditionally enable features by way of a build script. Our project now looks like this:
Cargo.toml
build.rs
src/
  lib.rs
  bench.rs

And we need to add rustc_version to our [build-dependencies] in Cargo.toml. We then add the following build script:
use rustc_version::{version_meta, Channel};
fn main() {
    // Set feature flags based on the detected compiler version
    match version_meta().unwrap().channel {
        Channel::Stable => {
            println!("cargo:rustc-cfg=RUSTC_IS_STABLE");
        }
        Channel::Beta => {
            println!("cargo:rustc-cfg=RUSTC_IS_BETA");
        }
        Channel::Nightly => {
            println!("cargo:rustc-cfg=RUSTC_IS_NIGHTLY");
        }
        Channel::Dev => {
            println!("cargo:rustc-cfg=RUSTC_IS_DEV");
        }
    }
}

Finally, if we update lib.rs to be the following:
// Include the unstable feature
#![cfg_attr(RUSTC_IS_NIGHTLY, feature(test))]  // <-- Note the change here!

pub fn fast(x: T) -> U { ... }

#[cfg(any(test, debug_assertions))]
pub fn slow(x: T) -> U { ... }

#[cfg(all(RUSTC_IS_NIGHTLY, test))]  // <-- Note the change here!
mod bench;

I think we get everything we want.
So... thanks for joining me on this adventure. Would appreciate commentary on whether or not this was the right approach. Also, you might ask "why keep the benchmark around once we know it's slower?" I suppose this might be fair, but perhaps the test could be changed or I'd like to prove the new implementation is faster to a third party that won't just trust me.


text:
Q: More readable way to extract keys of a type, where the types of the values for said key conform to an interface? My app has a bunch of services at the boundary between the front-end and back-end that are called over Electron IPC using string names. To aid typechecking and editor support, I have an interface which maps service names to the interface type:
interface IFooService {
    aaa(): void;
    search(query: string): any;
}

interface IBarService {
    bbb(): void;
}

interface IAllServices {
    foo: IFooService,
    bar: IBarService,
}

On the front-end there's a generic search component that can search any of the services, and I was trying to get rid of the any type of the input property used to set which service to call.
For this I need to extract all keys on IAllServices, where the type of the key's value has a search method, into a type SearchableServiceKey. I.e. in the above example, IFooService has it, and IBarService does not, so I want the extracted type to be equivalent to type SearchableServiceKey = 'foo'.
The point of the exercise being that the type checker doesn't accept this:
function search(services: IAllServices, service: string, query: string) {
    services[service].search(query);
}

because services[service] only has the empty intersection of the keys of IFooService and IBarService; but should accept this:
function search(services: IAllServices, service: SearchableServiceKey, query: string) {
    services[service].search(query);
}

I managed to get this working using this construction:
type ServiceKey = keyof IAllServices;

interface ISearchable {
    search(query: string): any;
}

type IsSearchable<SK extends ServiceKey> = IAllServices[SK] extends ISearchable
    ? SK
    : never;

type ValuesOf<T> = T[keyof T];

type SearchableServiceKey = Exclude<
    ValuesOf<{ [SK in ServiceKey]: IsSearchable<SK> }>,
    never
>;

but it's kind of a mouthful with the detour through mapping a key to its own type or never to express a predicate. Is there a simpler way to express this in TypeScript?

A: What you've got is correct, and the only strictly unnecessary part is where you manually try to remove never types as constituents of a union.  The compiler already automatically eliminates never from unions:
type Foo = never | string | never | number | never | boolean | never;
// IntelliSense shows: type Foo = string | number | boolean;

The only other thing I'd suggest is that you don't need to give type alias names to all the intermediate steps of your type if you're not going to reuse them.  The idea of "give me the keys of an object type T whose properties are assignable to a value type V" comes up often enough that I usually define the following type alias:
type KeysMatching<T, V> =
    { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T];

And then you can derive the type you're looking for as
type SearchableServiceKey =
    KeysMatching<IAllServices, {search(q: string): any}>;
// IntelliSense shows: type SearchableServiceKey = "foo"

Playgound link to code
Okay, hope that helps.  Good luck!


text:
Q: How to include a document made with Rmd into an HTML page I'm making an interactive document with Rmd (ggplot and some text) and need to include it into my website.
Can I export an HTML file from R only like a div tag and not like a full file with a head, body etc?
or should I export a full HTML file and create an iframe?

A: I ended up using <object> and it works well.


text:
Q: Error installing Perforce plugin (P4WSAD) to Zend Studio 7 I am running Zend Studio build 20090901
I am trying to install the Perforce plugin but I receive this error:
An error occurred while collecting items to be installed
  session context was:(profile=studioProfile, phase=org.eclipse.equinox.internal.provisional.p2.engine.phases.Collect, operand=, action=).
  No repository found containing: osgi.bundle,org.eclipse.pde,3.4.100.v200909170800
  No repository found containing: osgi.bundle,org.eclipse.pde.api.tools,1.0.101.v20090714
  No repository found containing: osgi.bundle,org.eclipse.pde.api.tools.ui,1.0.101.v20090820
  No repository found containing: osgi.bundle,org.eclipse.pde.build,3.5.1.R35x_20090820
  No repository found containing: osgi.bundle,org.eclipse.pde.core,3.5.100.v20090821
  No repository found containing: osgi.bundle,org.eclipse.pde.doc.user,3.5.0.v20090818
  No repository found containing: org.eclipse.update.feature,org.eclipse.pde,3.5.1.R35x_v20090811-7Z7_F9zFDX-aT6Ywvh8_S93
  No repository found containing: osgi.bundle,org.eclipse.pde.runtime,3.4.100.v20090731
  No repository found containing: osgi.bundle,org.eclipse.pde.ui,3.5.0.v20090821
  No repository found containing: osgi.bundle,org.eclipse.ui.views.log,1.0.100.v20090731

I have searched the forums and can't seem to find anyone else with this issue. Any help would be greatly appreciated!

A: Since I posted this question, a couple new versions of Zend Studio have been released, which fixed this issue.
Installing P4WSAD now installs without issues.


text:
Q: while loop termination in Dafny I am trying to verify an algorithm using Dafny. I am struggling to fix the error message "decreases expression might not decrease (timed out)". The basic structure of my algorithm is as follows:
while (U != {})
    decreases |S| - |B - U|;  // S is a constant and |B| <= |S|
    invariant U < B;  // U is a subset of B
{
    var u :| u in U;  // pick an element of u
    U := U - {u};  // remove the element

    while (...)
        invariant U < B;  // U is a subset of B
    {
        // modifies B and U but does not modify |B - U|
    }
}

S, B and U are all sets. S is not modified at all in the algorithm. I have proved that the cardinality of B is less than or equal to the cardinality of S, so the decreases clause is bound by zero.
After each assignment to either B or U (in the inner while loop), I can prove that |B - U| remains the same. However, this is not enough, I need a loop invariant in the inner while loop that states this, but I do not know how to express this in Dafny. I have tried the following but it did not solve the problem:
invariant |old(B) - old(U)| == |B - U|;

(Note: This is the first time I am using Dafny and I have been stuck on this problem for around a week, any suggestions will be helpful).

A: To express that the inner loop has no effect on the value of |B - U|, you can save the value of |B - U| in a ghost variable just before the inner loop. Then, mention that ghost variable in the inner loop invariant. Like this:
ghost var previousCardinalityOfBminusU := |B - U|;
while (...)
  invariant |B - U| == previousCardinalityOfBminusU
{
  // ...
}

Here are some other comments:

*

*If the inner loop does not add any elements to U, then a simpler termination metric for the outer loop is just |U|. You'll then want to add a loop invariant like |U| <= prev to the inner loop, where prev is a ghost variable that you set to |U| just before the inner loop.

*Do you also have a plan for proving the termination of inner loop?

*The expression U < B says that U is a proper subset of B, but maybe that is already what you meant by the comment "U is a subset of B"?

*You error message also says "timed out". Sometimes, there may be more than one cause of the time out, and it could be that fixing one also takes care of the other. To make sure that everything else is fine, I suggest you temporarily let the verifier assume termination works out.
One way to do that is to (temporarily) mark each loop with decreases *, which tells the verifier that you're okay with the loop not terminating. (This will also require you to mark any enclosing loop and the enclosing method with decreases *.)
Another way to temporarily let the verifier assume termination works out is to use an assumestatement. For example, for the outer loop, you can do:
while U != {}
  // as before
{
  ghost var prev := |S| - |B - U|;
  // as before
  // inner loop as before
  assume |S| - |B - U| < prev; // give verifier the (possibly incorrect) assumption that the termination metric has gone down
}

This may discover if there are other problems as well (that were previously masked by the time out), and those could be another cause of the time out. If, however, your program verifies correctly with these assumptions, then it is indeed termination proof that's causing the time out. You'll then need to try to provide more of the correctness argument to the verifier (my hunch is that some additional invariant on the inner loop will do the trick).


text:
Q: How to pass 2 sets as parameters for a function? Create a Python program that asks the user to enter two sets of comma-separated values. Use the string split() method to parse the line and then use the set() function to covert the lists to sets. Demonstrate set theory for the two sets by displaying the two sets and their relationship to each other as subset, superset, union, intersection, and difference.
Im not sure how to pass two sets in a function?
print(two_set(set(1,2,3,4), set(2,3,4,5,6)))

TypeError: set expected at most 1 arguments, got 4

A: You should convert it into set and then pass them:
def two_set(set_a, set_b):
        return (set_a, set_b)

set_a = set([1,2,3,4])
set_b = set([2,3,4,5,6,6,6,6])

print(two_set(set_a, set_b))

OUTPUT:
({1, 2, 3, 4}, {2, 3, 4, 5, 6})

A: this is one of the solutions.
class Settherory:
    def __init__(self, set1,set2):
        self.set1 = set1
        self.set2=set2
    def subset(self):
        if self.set1.issubset(self.set2):
            return '{} is subset of {}'.format(self.set1,self.set2)
        elif self.set2.issubset(self.set1):
            return '{} is subset of {}'.format(self.set2,self.set1)
        else:
            return 'not a subset'

    def superset(self):
        if self.set1.issuperset(self.set2):
            return '{} is superset of {}'.format(self.set1,self.set2)
        elif self.set2.issuperset(self.set1):
            return '{} is superset of {}'.format(self.set2,self.set1)
        else:
            return 'not a superset'
    def union(self):
        return 'union of sets is {}'.format(self.set1 | self.set2)

    def difference(self):
        return 'difference of set is {}'.format(self.set1 - self.set2)

    def intersection(self):
        return 'intersection of two sets is {}'.format(self.set1 & self.set2)

set_1 = set(map(int,input('enter the data in set 1 ').strip().split(',')))
set_2 = set(map(int,input('enter the data in set 2').strip().split(',')))

x= Settherory(set_1, set_2)
print(x.subset(), x.difference(), x.superset(),x.union(),x.intersection(),sep='\n')

'''
enter the data in set 1 1,2,3,4,5

enter the data in set 23,4,5
{3, 4, 5} is subset of {1, 2, 3, 4, 5}
difference of set is {1, 2}
{1, 2, 3, 4, 5} is superset of {3, 4, 5}
union of sets is {1, 2, 3, 4, 5}
intersection of two sets is {3, 4, 5}
'''

another way to do is
# take input as single line seperated by ','
set_1 = set(map(int,input('enter the data in set 1 :').strip().split(',')))
set_2 = set(map(int,input('enter the data in set 2 : ').strip().split(',')))

# for finding the subset or other set operation you can use direct inbuilt function on set like:

print(set_1.issubset(set_2))
print(set_1.issuperset(set_2))
print(set_1.union(set_2))
print(set_1.difference(set_2))

# output
'''
enter the data in set 1 : 1,2,3,4

enter the data in set 2 : 2,3
False
True
{1, 2, 3, 4}
{1, 4}
'''

A: the set class takes an array for initializing but you are giving multiple integers instead. Change your code to
print(two_set(set([1,2,3,4]), set([2,3,4,5,6])))

to solve your problem


text:
Q: Can we stop closing the application when iOS App crash I have implemented iOS App, In that if we get any unknown crash i want to show one message like "sorry some thing went wrong". Meanwhile the App did not close. It still open if we get crash. Its a requirement from client.

A: Short answer: This is not a good idea and should be avoided at all cost. Convince the person who provided that requirement that this should not be done.
Long answer: When your app crashes, this means something went horribly wrong. It got into a state where nothing can be guaranteed any longer and it is better (even for the app user) to quit the app right away. The reasons for a crash could be:

*

*an unhandled error

*you are trying to access some memory that you don't have access to

*accessing memory that is already de-allocated, but your app code thinks it is still allocated to a specific object

*and many many more reasons

For the first case you could setup unhandled error handlers across your app or globally; this is what crash reporting SDKs do. For the other reasons you need to set up signal handlers (or even Mach exception handlers) to get those. One rule in those cases is that at crash time you should NOT allocate new memory, simply because you have no guarantee that will work or would not overwrite memory used by other parts of your app which then could cause major corruption of the user's data, or deadlock the device which means the device owner has to restart it.
Not being allowed to allocate any memory at crash time means you can't use any Swift or Objective-C code, because allocating a new object WILL allocate new memory. And showing an alert will just do that as having the app continue to run will do as well. You can only use a subset of (async-safe) C methods at crash time!
So the end of the story is:

*

*detecting a crash is hard

*not causing possible damage to user data after a crash is even harder

*guaranteeing the app will continue to run without causing damage to user data or being usable to the user at all without more problems is in the area of luck

If the operating system decides that your app should exit (crash) because of such an unsafe scenario, you as an app developer should not decide otherwise.


text:
Q: How to Automatically redirect website IE browser to Chrome browser? Recently we migrated to latest version of application which allows the user to open application in any browser.
Earlier it use to support Only IE browsers.
After migration many users still open the application in old browser.
Since the application is very slow in IE browser.We are looking for a solution that will automatically open the URL/Login Page  in Chrome browser when user opens in IE browser.
i.e., when a user open URL in IE browser it automatically open the same URL in Google chrome browser.

A: Google Chrome Legacy Browser support allows this.  Under the "Hosts to open in Alternative Browser" policy, put in an entry for the site you want to force to open in Chrome, preceding it with an "!".  Example:
!https://www.somesitetoopeninChromeonly.com.

A: If i understand it correctly, the users open a page in IE and when they click an url on that page, it will open that URL in Chrome.
I guess, you can't do this. You can use target="_blank" to open a new tab in the same browser.
If you want to open a link from an application in chrome and not in IE, you can change the default browser to chrome. Click on Start, type the "default app settings" and change the default browser to chrome.

A: I think the best solution is to let the user open Google Chrome manually by informing about it.
It is possible however, to make a document called "chrome.hta" for example, with the contents shown below, and then link to it on another page. (This will only work in Internet Explorer, not Edge)

The user now has to press "open" and "allow" after they click the link referring to the .hta file.
Now, on the page where you link to the .hta document, you can make the page detect the browser and adjust the link accordingly:
My Application

A: A bit late, but we have two different solutions for this:

*

*We use a javascript: link to use ShellExecute to run a small exe helper application that checks if Chrome is installed, and if it is, open Chrome to the URL parameter, optionally with switches (e.g. --use-system-default-printer and on shared logon PCs, --incognito). This requires configuring special permissions for the site in Internet Options|Security.

*Now we can also use the microsoft-edge: protocol to open sites in Edge.
You could also install your own protocol for opening sites in Chrome but you would need a helper application to re-write the URL. I have one written to add microsoft-edge-private: to open links in Edge in InPrivate mode.

A: To open the webpage in Microsoft Edge you can try the below code.

 TEST


text:
Q: Scraping multiple pages using beautiful soup I have got the code to scrape the first page, but the url changes from:
https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/index.html --> https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/2.html
import requests

from bs4 import BeautifulSoup

url = "https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/index.html"

page = requests.get(url)

soup = BeautifulSoup(page.content, "html.parser")

lists = soup.select("div#simulacion_tabla ul")

for lis in lists:

    title = lis.find('li', class_="col1").text

    location = lis.find('li', class_="col2").text

    province = lis.find('li', class_="col3").text

    info = [title, location, province]

How can I create a loop that would run from page 2 - page 65? Many thanks!

A: Here is the working solution:
import requests
from bs4 import BeautifulSoup
for page in range(1,65):
    url = "https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/{page}.html".format(page =page)
    #print(url)
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")
    lists = soup.select("div#simulacion_tabla ul")

    for lis in lists:
        title = lis.find('li', class_="col1").text
        location = lis.find('li', class_="col2").text
        province = lis.find('li', class_="col3").text
        info = [title, location, province]
        print(info)

A: First of all please be sure to format your code in the correct way so everyone can read it. Here you can find more.
This one could be a potential solution. Far from being optimized code, but you can take some inspiration.
import requests
from bs4 import BeautifulSoup

def scrape_page(url):
    """ Scrape the give url and return the bs4 ResultSet """
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")
    table = soup.select("div#simulacion_tabla ul")
    print(type(table))
    return table

def extract_rows(table):
    """ Extract rows """
    rows = []
    for row in table:
        title = row.find('li', class_="col1").text
        location = row.find('li', class_="col2").text
        province = row.find('li', class_="col3").text
        rows.append([title, location, province])
    return rows

big_table = []
index = scrape_page("https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/index.html")
for row in extract_rows(index):
    big_table.append(row)

for x in range(2, 66):
    index = scrape_page("https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/" + str(x) + ".html")
    for row in extract_rows(index):
        big_table.append(row)

print(big_table)


text:
Q: Get substring between first and nth occurence of pattern I am attempting to extract a substring between the first and nth occurence of a pattern in a linux shell (using sed, awk, ...).
Example string:
AAA_BBBB__CCC__GGGG___fffffffffffffff_hhhh

I need the substrig after the first occurence of "*_" (n concatenated underscores) until the nth occurence of "*_".
E.g., the result for substring between 1st and 4th occurence would be
BBBB__CCC__GGGG

Using sed, or awk or other tools what would be the best way to do this?

A: Here's one way using sed. This will select the substring between the 1st and nth occurrence. The number present is in the form n - 1:
sed 's/^[^_]\+_\+\(\(_*[^_]\+\)\{3\}\).*/\1/'

or if you have GNU sed:
sed -r 's/^[^_]+_+((_*[^_]+){3}).*/\1/'

Testing:
echo "AAA_BBBB__CCC__GGGG___fffffffffffffff_hhhh" | sed -r 's/^[^_]+_+((_*[^_]+){3}).*/\1/'

Results:
BBBB__CCC__GGGG

For fun, let's say you'd like to find the substring between any number of groups starting from the beginning of the line for any length. For example, if you're trying for an offset of 4, for a length of 1, try:
sed -r 's/^([^_]+_+){4}((_*[^_]+){1}).*/\2/'

Results:
fffffffffffffff

Pretty cool huh?


text:
Q: Install Fonts with Inno Setup - Replacing fonts that are locked I'm using Inno Setup to install the Fontawesome font for a desktop application on Windows. First install usually works fine as the fonts aren't installed, but on subsequent installs I frequently run into locking problems:

In order to install the font I'm using:
Source: "FontAwesome.ttf"; DestDir: "{fonts}"; FontInstall: "FontAwesome";\
        Flags: uninsneveruninstall

Now I know I can use Flags: onlyifdoesntexist to install the fonts only if they don't exist and that does work. However, on occasion I need to update the Font due to a version change and new fonts that have been added.
The error apparently occurs only if something is using the font. Besides the main installed application, I'm using Chrome and have pages open that use FontAwesome and apparently that's also locking the installed font.
Ideally what I need to have happen is if the font is locked have it replaced after the next reboot or after the font becomes unblocked.
It also looks like Inno is trying to replace the font each and every time even though the the font version is the same. According to the docs (bottom of the document) files are only supposed to be replaced if the install version is higher, but that doesn't appear to be happening with the font wanting to install each time.
Is there any way to make Inno properly deal with Font Updates if the font in question is in use?

A: You can try to add the *.ttf to the CloseApplicationsFilter.
CloseApplicationsFilter=*.exe,*.dll,*.chm,*.ttf

It should make Inno Setup check, if the font is locked, and offer an user to close Chrome (or other application) to allow the replacement.


text:
Q: Updating Progress bar in listview while downloading a file How can we update a progress bar in ListView. When each progress bar is associated download of a file and which is done via AsyncTask.

*

*So where to update ProgressBar

*

*In update progress (I have tried this is not working)

*In the View Inflation process of ListView. (This is also not working)

Basically i whenever i get an file like .mp3 in browser, i call this asynctask, so there can be n instance of asynctask. but then how to update a particular progress bar with particular Aysnctask task.
            public class CopyOfDownloadsListActivity extends ListActivity {
            /** Called when the activity is first created. */

            //  static ArrayList<String> pthreads = new ArrayList<String>();
            static ImageView bt;
            static ProgressBar pb;
            static ListView allList;
            static TextView tv;
            String fileName;
            String mp3URL;
            URL url2;
            int myProgress;
            static int filecount  = 0;
            MyCustomAdapter adapter;

            private class DownloadFile extends AsyncTask<String, Integer, Void>{
                int count = 0;
                ProgressDialog dialog;
                int myProgess = 0;
                ProgressBar progressBar;

                @Override
                protected Void doInBackground(String... u) {

                    try {
                        URL ul = new URL(u[0]);
                        Log.i("UI",ul.toString());
                   //   int len = CopyOfMusicDownloader.mp3urls.size();
                   //   URL url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
                        HttpURLConnection c = (HttpURLConnection) ul.openConnection();
                        c.setRequestMethod("GET");
                        c.setDoOutput(true);
                        c.connect();

                        int lengthOfFile = c.getContentLength();

                        String PATH = Environment.getExternalStorageDirectory()
                                + "/download/";
                        Log.v("", "PATH: " + PATH);
                        File file = new File(PATH);
                        file.mkdirs();

                        fileName = "Track";
                        filecount++;

                        fileName =  fileName + Integer.toString(filecount) + ".mp3";

                        File outputFile = new File(file, fileName);
                        FileOutputStream fos = new FileOutputStream(outputFile);
                        InputStream is = c.getInputStream();

                        byte[] buffer = new byte[1024];
                        int len1 = 0;
                        while ((len1 = is.read(buffer)) != -1) {
                            myProgress = (int)(len1*100/lengthOfFile);
                            //myProgress = (int)(len1);

                            Log.i("My Progress", Integer.toString(myProgress));
                            publishProgress(myProgress);
                            //  publishProgress((int)(len1*100/lengthOfFile));
                            fos.write(buffer, 0, len1);
                        }
                        fos.close();
                        is.close();

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

                protected void onPostExecute() {

                }

                @Override
                protected void onPreExecute() {
                      setListAdapter(new MyCustomAdapter(CopyOfDownloadsListActivity.this, R.layout.row, CopyOfMusicDownloader.mp3urls));

                }

                @Override
                protected void onProgressUpdate(Integer... values) {
                     pb.setProgress(count);// HERE IS THE PROBLEM

                     count++;
                     Log.i("Values", Integer.toString(values[0]));
                }
             }

            @Override
            public void onCreate(Bundle savedInstanceState) {
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                super.onCreate(savedInstanceState);

                int len = CopyOfMusicDownloader.mp3urls.size();
                try {
                    url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
                    new DownloadFile().execute(url2.toString());
                    Log.i("url",url2.toString());
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

             }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                 MenuInflater myMenuInflater = getMenuInflater();
                 myMenuInflater.inflate(R.menu.menu, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                 switch(item.getItemId()){
                 case(R.id.browsermenu):
                 Intent i = new Intent(CopyOfDownloadsListActivity.this, MusicDownloader.class);
                 startActivity(i);
                 break;
                 case(R.id.downloaderrmenu):
                 break;
                 case(R.id.playermenu):
                 Intent j = new Intent(CopyOfDownloadsListActivity.this, Players.class);
                 startActivity(j);
                break;
          }
             return true;
            }

            public class MyCustomAdapter extends ArrayAdapter<String> {
                public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<String> pthreads) {
                super(context, textViewResourceId, pthreads);
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        LayoutInflater inflater = getLayoutInflater();
                        View row = inflater.inflate(R.layout.row, parent, false);
                        bt =(ImageView)row.findViewById(R.id.cancel_btn);
                        tv =(TextView)row.findViewById(R.id.filetext);
                        pb = (ProgressBar)row.findViewById(R.id.progressbar_Horizontal);
                        return row;
                    }
                }

        }

A: Children of a list view are built by an adapter. This adapter has some underneath data that is 'transformed' to views in getView() method. This means you have to change that data in update progress method of async task and call adapter.notifyDataSetChanged(). And your getView method should just 'transform' data to the list view child.
AsyncTask:
protected void onProgressUpdate(final int... values) {
  data[i].progress = values[0];
  adapter.notifyDataSetChanged();
}

Adapter:
public View getView(final int position, final View convertView, final ViewGroup parent) {
  ...
  progress.setProgress(getItem(position).progress);
  ...
}


text:
Q: How can I hide/remove ScrollBar in ScrollView in SwiftUI? If the content of the ScrollView is bigger than the screen, while scrolling, the scrollbar on the side appears. I couldn't find anything to help me hide it.

A: You just have to use the scrollView initializer and set the parameter showsIndicators property to false within the initializer only.
ScrollView(.vertical, showsIndicators: false) {
     //your content for scrollView
}

Hope this has resolved your query.

A: You can use showsIndicators: false to hide the indicator:
ScrollView(showsIndicators: false) {
    // ...
}

A: if you need to hide both scrollers:
ScrollView(showsIndicators: false) {
  //your code
}

__
If you need to hide only one scroller, but to have ability to scroll in both directions:
need to use Introspect:
ScrollView() {
    // Some Content
}
.introspectScrollView{
    $0.hasHorizontalScroller = false
    $0.hasVerticalScroller = true
}

as result:

*

*horisontal scroller invisible

*vertical scroller visible;

A: Show / Hide Indicators in ScrollView SwiftUI
Hide Indicators in ScrollView SwiftUI
  ScrollView(.horizontal,showsIndicators: false) {
  //your code
  }

Show Indicators in ScrollView SwiftUI
 ScrollView(.horizontal,showsIndicators: true) {
  //your code
  }


text:
Q: Forms with two buttons, only one works I have a page with two buttons for creating a pdf and an excel. But only one of them will work. The forms are nearly the same. How can I make both buttons work. Maybe with an id for the forms? Javascript?
<portlet:actionURL var="createExcel">
<portlet:param name="action" value="createExcelorConstrainSearch" />
</portlet:actionURL>
<portlet:actionURL var="createPdf">
<portlet:param name="action" value="createPDForConstrainSearch" />
</portlet:actionURL>

<form:form commandName="tg35FormBackingModel" action="${createExcel}" method="post">
<form:form commandName="tg35FormBackingModel" action="${createPdf}" method="post">

....
</form:form>
</form:form>

<button type="submit" name="PDF"></button>
<button type="submit" name="EXCEL"></button>

A: You can add a name property to the form, which will make them both work (but not at once). You can check which one was pressed server-side, by reading which name value was sent along with the form data.


text:
Q: Java - base url after 302 redirect I've came up with the following problem. In my application I need to post an XML file to a server and wait for it's reply. I've achieved the above by using Apache HttpClient:

*

*create the xml

*using HttpClient and Post to post it to the server

The server initially responded with a 302 (Object moved), so I used LaxRedirectStrategy to be able to follow the redirect. I wrap the response in a StringBuffer and then push it into a new tab of the browser. Everything works fine, the tab shows the complete response from that server but every action in that page is not associated to the URL of the server response but to my main application. So, for example, if my application is on https://myapplication.com and the server is on https://theotherserver.com (+ /redirect for the redirect), each action on the page (i.e. /action) leads to https://myapplication.com/action and not to https://theotherserver.com/action.
In my page I have a button where this process starts. When you click it, it executes:
   jQuery('input#button').on
            (
                'click',
                function ()
                {
                    jQuery.ajax
                    (
                        {
                            url: 'myURL.do',
                            data: {data: mydata},
                            method: 'POST',
                            success: function(data)
                            {
                                if (data.success == 'true')
                                {
                                    var w = window.open('tab', windowname');
                                    w.document.write(data.result);
                                    w.document.close();
                                    w.focus();
                                }
                                else
                                {
                                    alert(data.error);
                                }
                            }
                        });
                    });

the .do executes the following:
public ResponseEntity<Map<String, String>> myMethod(HttpServletRequest request, HttpServletResponse response) throws ParserConfigurationException
    {
        Map<String, String> respData = new HashMap<String, String>();
        try
        {
            String myXML = prepareMyXMLFile();

            String result = sendMyXMLFile(myXML);

            respData.put("success", String.valueOf(true));
            respData.put("result", result);
            return new ResponseEntity<Map<String, String>>(respData, HttpStatus.OK);
        }
        catch (Exception e)
        {
            respData.put("success", String.valueOf(false));
            respData.put("error", String.valueOf(e));
            return new ResponseEntity<Map<String, String>>(respData, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

and finally sendMyXMLFile():
private String sendMyXML(String myXML)
{
    try
    {
        HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        HttpPost post = new HttpPost("myURL");
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("xml", myXML));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);

        BufferedReader rd = new BufferedReader(new
        InputStreamReader(response.getEntity().getContent()));

        StringBuffer responseResult = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
        {
            responseResult.append(line);
        }
        return responseResult.toString();
     }
     catch (IOException | TransformerException e)
     {
         //log error
     }
     return null;
 }

What do I need to do to use the response URL as the base URL in the other tab?
Any help is appreciated. Thanks


text:
Q: Find point in the image of a linear function that is closest to some other point I have a linear function $f: \mathbb{R}^m\rightarrow\mathbb{R}^n$ with $n>m$ of the form:
$$
y \equiv f(x) = M\cdot x
$$
where $M$ is some coefficient matrix of shape $(n,m)$. For example, for $m=2, n=3$ the image would be a 2d plane embedded in 3d space.
Now I have another point $p\in\mathbb{R}^n$ and I want to find the value of $x$ that corresponds to the point in the image of $f$ which has the smallest Euclidean distance to $p$.
So I figured out, since $m<n$, there must be a line in $\mathbb{R}^n$, described by $y_l = m\cdot t + b \;\; (m,b\in\mathbb{R}^n, t\in\mathbb{R}$), that is perpendicular to the image of $f$ in a sense that:
$$
(mt + b)^T \cdot (Mx)  = 0 \quad \forall x\in\mathbb{R}^m, t\in\mathbb{R}
$$
i.e. the dot product between any two vectors corresponding to, respectively, the line and the image of the function $f$, is zero.
Secondly, the line must pass through the point $p$, i.e.
$$
mt_p + b = p
$$
for some value of $t_p$.
Using these relations together gives
$$
(m(t-t_p) + p)^T \cdot Mx = 0
$$
which is equivalent to
$$
(mt + p)^T \cdot Mx = 0
$$
since the equation must hold for all $t\in\mathbb{R}$.
At this point, however, I'm stuck in deriving the value of $m$, in dependence on $x$ and $p$, so that the equation is satisfied. It seems I could first compute the product $(mt + p)^T \cdot M$ which gives me some vector in $\mathbb{R}^m$ depending on the choice of $m$, but that can't be perpendicular to all vectors $x\in\mathbb{R}^m$; this seems to contradict the initial assumption, but I can't see why it wouldn't be valid (consider for example the $m=2,n=3$ case).
Once the line equation is known, the point $x$ can be derived via
$$
\begin{aligned}
Mx &= mt + b \\
Mx - mt &= b
\end{aligned}
$$
which can be solved by constructing a new matrix by augmenting $M$ with a new column $m$:
$$
\begin{pmatrix} M & | & m \end{pmatrix}
\begin{pmatrix} x \\ t \end{pmatrix}
= b
$$
However, as mentioned above, I'm stuck with deriving the parameters of the line equation, so any help is greatly appreciated.

A: The vector $x$ that you are looking for is known as the least squares solution to the equation $M \cdot x = p$. It turns out that there is a very straightforward solution to this problem. A vector $x$ is a least solution if and only if we have
$$
M^TMx = M^Tp.
$$
Thus, if the columns of $M$ are linearly independent, the (unique) solution is
$$
x = (M^TM)^{-1}M^Tp.
$$
If $M$ has linearly dependent columns, then the solution is no longer unique. If we want the vector $x$ among these solutions for which the Euclidean norm $\|x\|$ is minimized, then we could use the MP pseudoinverse $M^+$ of $M$ to get
$$
x = M^+p.
$$

Claim: If $x$ is a least squares solution to $Mx = p$, then $M^TMx = M^Tp$.
Proof: Let $x$ denote the least squares solution. As you note, the line connecting $Mx$ to $p$ must be perpendicular to the image of $f$. On the other hand, for $z \in \Bbb R^n$
$$
z^T My = 0 \quad \forall y \in \Bbb R^m \iff z^TM = 0 \iff (z^TM)^T = M^Tz = 0.
$$
That is, a vector $z$ is orthogonal to the image of $f$ iff $M^Tz = 0$.  Now, the vector $p - Mx$ points from $p$ to the closest point within the image of $f$, so this vector is orthogonal to the image of $f$. That is, we have
$$
0 = M^T(p - Mx) \implies 0 = M^Tp - M^TMx \implies M^TMx = M^Tp,
$$
which was what we wanted.


text:
Q: Перевод из десятичной в шестнадцатеричную систему в PHP Есть функция перевода чисел из десятичной в шестнадцатеричную систему счисления.
void ConvertNumber(__int64 nNum, char* szText)
{
    sprintf(szText,"%02I64X%012I64X",nNum&(__int64)0x00000000000000FF,(nNum>> (__int64)8));
}

Пример работы:

10-ная:4501598728   на выходе 16-ная:080000010C50F2

Нужно всё это дело реализовать на php. Как думаете реально? Кто что посоветует? Заранее спасибо.
Думаем дальше.
Функция sprintf форматирует и запоминает наборы символов и значений в переменную в нашем случае szText. "%02I64X%012I64X"  - строка управления форматом. Честно говоря, хз как это понимать.
A: А вам необходимо самому решить данную задачу или пойдет готовая функция?
Если готовая, то вот: string dechex ( int $number ), взята здесь.
И еще оттуда же, только из комментариев:
//I was confused by dechex's size limitation. Here is my solution to the problem. It
//supports much bigger values, as well as signs.

<?php
function dec_to_hex($dec)
 {
     $sign = ""; // suppress errors
     if( $dec < 0){ $sign = "-"; $dec = abs($dec); }

     $hex = Array( 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,
                   6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 'a',
                   11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e',
                   15 => 'f' );

     do
     {
         $h = $hex[($dec%16)] . $h;
         $dec /= 16;
     }
     while( $dec >= 1 );

     return $sign . $h;
 }
?>

A: // преобразование в десятичную систему
 print bindec(11011); // 27
 print octdec(33);    // 27
 print hexdec('1b');  // 27
 // преобразование из десятичной системы
 print decbin(27);    // 11011
 print decoct(27);    // 33
 print dechex(27);    // 1b

здесь можно почитать подробней


text:
Q: USB ports not responding in Xubuntu 12.04 I'm running Xubuntu 12.04 on an Asus X83V Laptop and a couple days ago, all my USB ports stopped responding, with neither my mouse nor flash drives or any usb devices responding. When I connect my phone to any USB port it does charge, but does not connect to my laptop. The same goes with my mouse, which lights up but doesn't respond.
My lsusb output with or without any devices connected is:
~$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

Running dmesg gives me the following recurring output:
[125505.972198] hub 8-0:1.0: unable to enumerate USB device on port 1
[125507.896116] hub 2-0:1.0: connect-debounce failed, port 1 disabled
[125509.816165] hub 2-0:1.0: connect-debounce failed, port 2 disabled
[125510.128196] hub 7-0:1.0: unable to enumerate USB device on port 2
[125512.048136] hub 2-0:1.0: connect-debounce failed, port 1 disabled
[125513.968164] hub 2-0:1.0: connect-debounce failed, port 2 disabled
[125514.152160] hub 8-0:1.0: unable to enumerate USB device on port 1
[125516.076064] hub 2-0:1.0: connect-debounce failed, port 1 disabled
[125517.996146] hub 2-0:1.0: connect-debounce failed, port 2 disabled
[125518.308109] hub 7-0:1.0: unable to enumerate USB device on port 2
[125520.228063] hub 2-0:1.0: connect-debounce failed, port 1 disabled
[125522.148148] hub 2-0:1.0: connect-debounce failed, port 2 disabled
[125522.332195] hub 8-0:1.0: unable to enumerate USB device on port 1
[125522.644068] hub 7-0:1.0: unable to enumerate USB device on port 2
[125526.168137] hub 2-0:1.0: connect-debounce failed, port 2 disabled
[125526.480203] hub 7-0:1.0: unable to enumerate USB device on port 2
[125526.720130] usb 8-1: new full-speed USB device number 51 using uhci_hcd
[125527.128105] usb 8-1: device not accepting address 51, error -71
[125527.240157] usb 8-1: new full-speed USB device number 52 using uhci_hcd
[125527.648158] usb 8-1: device not accepting address 52, error -71
[125527.760051] usb 8-1: new full-speed USB device number 53 using uhci_hcd
[125527.824202] hub 8-0:1.0: unable to enumerate USB device on port 1
[125529.748164] hub 2-0:1.0: connect-debounce failed, port 1 disabled
[125531.668058] hub 2-0:1.0: connect-debounce failed, port 2 disabled
[125531.980148] hub 7-0:1.0: unable to enumerate USB device on port 2
[125532.164198] hub 8-0:1.0: unable to enumerate USB device on port 1
[125534.084123] hub 2-0:1.0: connect-debounce failed, port 1 disabled
[125536.004170] hub 2-0:1.0: connect-debounce failed, port 2 disabled
[125536.316167] hub 7-0:1.0: unable to enumerate USB device on port 2
[125538.240057] hub 2-0:1.0: connect-debounce failed, port 1 disabled
[125540.160128] hub 2-0:1.0: connect-debounce failed, port 2 disabled
[125540.400157] usb 8-1: new full-speed USB device number 55 using uhci_hcd
[125540.808153] usb 8-1: device not accepting address 55, error -71

I'm running kernel 3.2.0-34-generic and have tried updating it to 3.6 but to no avail. SOS?


text:
Q: Why $Z(A)$ is an equivalence relation on $A$? For every algebra $A$, the center $Z(A)$ is a congruence on $A$.
Why is $Z(A)$ an equivalence relation on $A$?

A: Since you referred to the center of an algebra (rather than the center of a group), I believe you mean Definition 5.1 on page 35 of the commutator book.  But by that definition it is obvious that the center is an equivalence relation.
So perhaps your confusion arises from talking about the center of a group rather than a general or "universal" algebra.  In that case, for a group $G$, the center $Z(G)$ is not really a congruence relation of $G$.  However, as a normal subgroup, $Z(G)$ is a single class of a congruence relation of $G$ -- namely, the class containing the identity element of $G$.
In general, each normal subgroup $N$ of a group $G$ can be identified with a congruence relation, $\theta_N$, of $G$.  The congruence classes of $\theta_N$ are the cosets of $N$.  Thus, the lattice of normal subgroups of $G$ is isomorphic to the lattice of congruence relations of $G$. It is because of this identification that a normal subgroup is sometimes loosely referred to as a "congruence" of the group.
See also this answer.


text:
Q: Defining $n$ for $\lim_{x\to \pm \infty}\frac{1}{x^{n}}=0$.
Defining $n$ for $\lim_{x\to \pm \infty}\frac{1}{x^{n}}=0$.

My notes say that $n$ must be a positive integer, yet there are questions that involve radicals, or answers to some limit questions that make me believe $\lim_{x\to \pm \infty}\frac{1}{x^{\frac{1}{r}}}=0$ where $r$ is a positive integer. Is this limit true though? Can $n$ be instead a positive real number such as $n=\frac{1}{r}$?

A: You should make sure that the expression makes sense for your choice of $n$. Especially $\lim_{x\to -\infty}1/x^n$ is a bit troublesome if $n$ isn't an integer. I think that's what your notes are referring to.
(You can make sense of $x^n$ for $n\notin \Bbb Z$ and $x<0$, but it takes some work using complex numbers, and there is no canonical way of doing it.)
Once we have limited ourselves to $n\in \Bbb Z$, the answer $n = 1$ is pretty immediate.


text:
Q: Common Ribbon Control in Windows Forms I want to develop windows forms application in which i want same ribbon control to appear on top with same Click Functions associated. Is there any solution to add same ribbon to all forms? I tried MDI, but i dont have requirement of multiple documents to be opened at same time. I tried adding same ribbon to all forms one by one, but then , i need to create click methods for all buttons in all forms seperately, that is tedious and time waste.
Also, i need to know any solution for smoothing transition between form change. When i use code:
Form f1=new Form();
f1.show();
this.hide();

This works correctly for switching between forms, but the problem is it creates a jerk on screen. So, is there any solution for smooth transitioning of forms?

A: You could create a base class that implements the ribbon. Just reuse (that is: derive from) that control for every form you have.
Create a container under the ribbon where you can put your actual form content in.
A problem might be that the designer often doesn't like this, so it might be quite some work to smooth thing out.


text:
Q: Spring Data JPA transaction custom isolation level Given the following scenario:
I have an app running with Spring Boot @SpringBootApplication and setup with Spring Data JPA datasource in application.properties:
spring.datasource.url=jdbc:mysql://foo.bar.com:12345
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

and no additional java/xml configs.
I have a couple of services:
@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    ProjectRepository projectRepository;

    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public Project save(Project project) {
        // there might be some additional logic here, besides the action on repository
        return projectRepository.save(project);
    }
}

and repositories:
@Repository
public interface ProjectRepository extends CrudRepository<Project, Long> {}

As it's in the code above, I found myself in need of, let's say, SERIALIZABLE level of isolation due to the app being scaled up horizontally and occasionally saving conflicting data to DB (simply @Transactional was no enough). Now, when trying I try to perform projectService.save(project) action I get an exception:
"exception": "org.springframework.transaction.InvalidIsolationLevelException",
"message": "JtaTransactionManager does not support custom isolation levels by default - switch 'allowCustomIsolationLevels' to 'true'",

Is it possible to enable those custom isolation levels with a java config?

A: You can enable allowCustomIsolationLevels by setting below in TransactionManager
transactionManager.setAllowCustomIsolationLevels(true);


text:
Q: How pointer know the end of the pointed element? I'm a noob of C++, and I'm tripping about pointers.
An int can express -2147483647 to 2147483647 values, thus 4294967296 total values.
This require 32bit (2^32), thus 4 byte.
I see that if I do a ptr+1 (pointer arithmetic) from a ptr "pointer" to a int, it correctly move of 4 memory addresses (4 byte).
But these "4 byte" are all used to express 4294967296 values.
Where are stored the data that define the type "pointer to int"? I guess the pointer itself should know whick kind of data its pointing, i.e. whick kind of pointer it is. Where are stored these informations? Alongside the address of the pointed data? If I "print" the pointer, I get only the address, not other informations...

A: The compiler has type information available to know how to generate the underlying machine code necessary to evaluate something like ptr + 1. At the machine level it's the equivalent of saying ptr + sizeof(*ptr). So, if you've got code like this:
int *ptr = // some address;
ptr++;

Then the compiler (on x86) will emit something a bit like this for the ptr++:
mov eax,dword ptr [ptr]  ; Load the pointer
add eax,4                ; Add 4 to the address as sizeof(*ptr) is 4
mov dword ptr [ptr],eax  ; Write the new value back

The fact that the compiler has the type information means that the evaluation of ptr + 1 is static, rather than dynamic and can cause you problems when you've got arrays of derived types that you pass by pointer to base types. Take this example:
struct Base
{
  int x;
};

struct Derived : Base
{
  int y;
};

void PrintAll(Base *p, int numberOfItems)
{
  while(numberOfItems--)
  {
    std::cout << p->x << std::endl;
    p++; // Oops!!!
  }
}

Derived data[10];
Derived *ptr = data;
PrintAll(ptr, 10);

The line marked "Oops!!!" doesn't work as expected. Although ptr actually points to objects of type Derived it will only actually try to move ptr to point to the next Base rather than Derived as that all the compile time (ie static) information the compiler has available to it. This causes undefined behaviour. If ptr had actually pointed to an array of Base then we'd have been ok. Bugs like this are hard to detect at compile time and this is why you're better of using a container such as std::vector for this sort of thing.

A: Firstly, the C standards do not require that an int can represent values outside the rage -32767 to 32767.    And there are real-world compilers that do only support a 16-bit int.     Compilers are allowed to support a larger range but are not required to.
To answer your question, a declaration of the form
int *x;

tells the compiler that x is a pointer to an int.    The compiler itself is implemented with knowledge (either hard-coded, or a configuration option, depending on how the compiler is implemented) about the size of all native types (like int) - and is also implemented to produce that value in any code which uses a sizeof expression (like sizeof(int)).   Therefore the compiler can implement pointer arithmetic to suit.
The compiler - since it has parsed and interpreted your code - also knows what type every value and variable has - including pointers and ints.
Printing is another story - printing a pointer prints the address in memory, without the type information, unless you write code to explicitly output the type information as well.

A: The compiler knows what the size of int is on the target processor architecture (and in fact, the size of all defined types - even those defined by the user of the compiler).
The compiler decides where to store the increment size of the pointer arithmetic operation of your compiled program. Typically, it could be embedded in the instruction stream.


text:
Q: python - sending byte arrays via UDP without lists or pickling? I am working on a project in which a UDP connection must be used to send an arbitrary file between two unix machines. The main crux of the project is to encode data into byte arrays and send them between the two machines. My original plan was to take byte arrays, form a list out of them, and then serialize them with pickle and send. However, I was just told today by my instructor that using lists and serializing with pickle was not an acceptable solution to the problem. To quote his words:
"You have to encode and decode integer, string, and file objects by yourself, so that you obey the protocol defined in the handout." [this protocol refers to creating segments out of byte arrays, each segment holding 4-byte array for file size, 2-byte array for file name, and 1-byte array for ID flag, as well as a 'payload' byte array which varies in length based on what is being sent.]
I'm not really sure to go with it at this point. I have byte arrays that I need to send to the other machine, but my first two ideas to do so have been disallowed. I can make the byte arrays and the UDP connections (both of which I have tested independently), but sending them is tripping me up. Is there a good solution to my python problem?

A: A byte array in Python is best represented by a str (a simple string).  Your work will probably be to create that byte array according to that protocol specification you got.  Take care that it is a str then, and send it via the network functions for accessing sockets.
To convert a list of integers (bytes) into a str, use the following:
''.join(chr(c) for c in integer_list)

Or maybe you can build the str right in the first place (without going via a list of numbers).


text:
Q: Static libraries linked against other static libraries with CMake - one works, one doesn't. Why? Background
I have a project that uses other smaller projects. These projects themselves are made of other projects. A lot of this is legacy or has other managerial-fiat reasons for being arranged as is, so rolling everything into a single project is not an option. Some libraries are pre-compiled on remote shares.
I have 2 main subprojects that are giving me a headache:

*

*Project Foo is an executable and library that links several static subprojects (foo_subproject_1, foo_subproject_n). These subprojects are further linked against static libraries in remote locations (some_lib, some_other_lib). Project Foo's executable compiles, links, and runs correctly

*Project Bar is an executable that links several other projects, including libFoo. Linking fails with "undefined reference to " foo_subproject functions
As far as I can tell, the two projects are arranged similarly with their linkage instructions. Looking on SO, I discover that linking static libraries against static libraries shouldn't work, but then I'm confused as to how Project Foo is compiled successfully.
gcc and g++ 4.9.2 are the compilers (extern "C" problems of having some parts in C and some in C++ have already been checked for)

Question
I have misunderstood something about either or both how CMake add_subdirectory works, or about how the linker works. Can someone please explain how Project Foo works successfully, and Project Bar (doesn't) works as expected?
Update I looked closer at foo_lib.a and foo_runtime.
I should have determined that something was off to start with, because foo_runtime is nearly 100MB in size, and foo_lib is only 10KB.
nm reveals that foo_lib.a references a few dozen symbols, most of which are undefined. foo_runtime meanwhile references everything.
Equally confusing is that foo_subproject_1.a is similarly mostly undefined. Again, this is what I expect to see; but I don't understand how foo_runtime can be built from this?
I'm still unclear as to why some_library -> subproject -> foo_runtime is successful, but some_library -> subproject -> foo_lib -> bar isn't. At this stage of my investigations, I am expecting both commands to fail.

Project Foo is arranged (using CMake) thusly:
cmake_minimum_required(VERSION 2.6)
project(foo)

set(FOO_SRCS
    # source and headers for main foo project
)

# Project Foo libraries are subdirectories within this project
add_subdirectory(subs/foo_subproject_1)
add_subdirectory(subs/foo_subproject_2)

# Runtime executable
add_executable(foo_runtime main.c ${FOO_SRCS})
target_link_libraries(foo_runtime foo_subproject_1 foo_subproject_2)

# Library version (static library)
add_library(foo_lib STATIC ${FOO_SRCS})
target_link_libraries(foo_lib foo_subproject_1 foo_subproject_2)

Project Foo's subdirectories loosely have the following architecture:
cmake_minimum_required(VERSION 2.6)
project(foo_subproject_<n>)

set(FOO_SUBPROJECT_<N>_SRCS
    # source and headers for subproject
)

# foo_subproject's remote libraries are all static
add_library(some_lib STATIC IMPORTED)
set_target_properties(some_lib PROPERTIES IMPORTED_LOCATION /path/to/libsome_lib.a)

add_library(some_other_lib STATIC IMPORTED)
set_target_properties(some_other_lib PROPERTIES IMPORTED_LOCATION /path/to/libsome_other_lib.a)

include_directories(/paths/to/libs/include/)

# Static library for foo_subproject_N, links against static libs above
add_library(foo_subproject_<N> STATIC ${FOO_SUBPROJECT_<N>_SRCS})
target_link_libraries(foo_subproject_<N> some_library some_other_library)

Project Bar is arranged thusly:
cmake_minimum_required(VERSION 2.6)
project(bar)

set(BAR_SRCS
    # source and headers for main bar project
)

# Project Bar libraries are remote from Bar's perspective
add_library(foo_lib STATIC IMPORTED)
set_target_properties(foo_lib PROPERTIES IMPORTED_LOCATION /path/to/foo/libfoo_lib.a)

include_directories(/path/to/foo/include/)

# Runtime executable
add_executable(bar main.c ${BAR_SRCS} foo_lib)

Project Bar fails to link (compiles ok) with multiple errors of the form:
bar_frobulator.cpp:123: undefined reference to 'foo_subproject_1_init_frobulation'

where foo_subproject_1_init_frobulation lives in foo_subproject_1

A:
Can someone please explain how Project Foo works successfully, and Project Bar (doesn't) works as expected?

In short: Creating STATIC library doesn't involve linking step!
Details
In the Foo project you have an executable foo_runtime, which "works" because it is linked with proper libraries (e.g. with library foo_subproject_1 which defines foo_subproject_1_init_frobulation symbol).
An executable bar from Bar project doesn't perform that linking, so it fails. The line
target_link_libraries(bar foo_lib)

links with foo_lib, but this library doesn't defines the needed symbol foo_subproject_1_init_frobulation.
Note, that the line
target_link_libraries(foo_lib foo_subproject_1 foo_subproject_2)

in the Foo project doesn't perform actual linking: in general, building a static library doesn't involve linking step.
Given line just propagates include directories (and other compile-features) from foo_subproject_* libraries to the foo_lib one.
How to make it work
Because static library foo_lib doesn't track its dependency, you need to link bar with a library, which knows that. E.g., make foo_lib shared, or combine foo_subproject_* libraries into archive library, as suggested by the referenced question How to combine several C/C++ libraries into one?.
Alternatively, you may build Foo subproject within Bar one and, instead of creation of IMPORTED foo_lib target, use "normal" foo_lib target, created within Foo project. In that case, line
target_link_libraries(bar foo_lib)

would mean for CMake to (actually) link bar with foo_subproject_* libraries, because those libraries are "linked" (in CMake sense) into foo_lib. Again, the last "linking" has a meaning only for CMake: the file foo_lib.a doesn't aware about needing of foo_subproject_* libraries.

A: Tsyvarev's answer described well-enough what I was actually doing (rather than what I thought I was doing) to get me to look up the right things to answer the root question that I had ("Why does foo_runtime work but bar_runtime doesn't, when both link against static libraries linked against static libraries?")
From the CMake documentation for target_link_libraries:

Library dependencies are transitive by default with this signature. When this target is linked into another target then the libraries linked to this target will appear on the link line for the other target too.

target_link_libraries does not cause linking in the static libraries foo_subproject_1 and foo_subproject_2 (static libraries don't invoke the linker). What is does is makes the list of required libraries available for anything that tries to link with foo_subproject_1 or foo_subproject_2
So, effectively, my foo_runtime and foo_lib target_link_libraries command is, as far as CMake is concerned:
target_link_libraries(foo_runtime foo_subproject_1 some_library some_other_library foo_subproject_2 some_library some_other_library)
target_link_libraries(foo_lib foo_subproject_1 some_library some_other_library foo_subproject_2 some_library some_other_library)

foo_lib, being static, doesn't invoke the linker. foo_runtime, being an executable, does.
bar is a totally different project, so doesn't get to take advantage of the transitive dependencies (and linking fails, because I'm missing all the symbols from the lower-level libraries).
This behaviour of target_link_libraries wasn't expected, as such the behaviour of the project as a whole was somewhat misleading (since it looked like I was bundling a bunch of libraries at the subproject level, and then bundling those at the upper level. In reality, I had just told the upper level what all the libraries it needed were).
To summerise:

Q "Why does foo_runtime work but bar_runtime doesn't, when both link against static libraries linked against static libraries?"
A "foo_runtime is not linking against static libraries linked against static libraries. foo_runtime is linked against more static libraries than you originally thought it was linking against.
bar_runtime doesn't work because your foo_lib is basically empty"


text:
Q: How to extract link anchor text with a certain keyword from a string I want to extract the url of all links in a string with certain anchor text.
I saw a previously post on doing this in javascript - can anyone help me do this in PHP?
javascript regex to extract anchor text and URL from anchor tags

A: If you're parsing HTML to extract href attribute values from anchor tags, use an HTML/DOM Parser (definitely don't use regex).
PHP Simple HTML DOM Parser
PHP XML DOM

A: preg_match_all('#]*>([^<]+)#i', $subject, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    echo $match[0]; // text
    echo $match[1]; // url
    echo $match[2]; // text
}

This is how I'd do it with regex. There may be more efficient ways but this should be the simplest one.
EDIT: Noticed that you wanted to match all URLs, therefore changed to preg_match_all
preg_match_all


text:
Q: Every 1 second increase the value with a random number using decimal numbers So I'm trying to increment the value of a number in an interval of 1 second with a decimal number between (0.01 and 0.05) and I can't seem to figure this out.
The only thing that it does is to show me numbers between 0.01 and 0.05 instead of adding them up to be an integer.
setInterval (function myFunction() {
  var number = 0;
  document.getElementById("computerScore").innerHTML = number +
  Math.floor((Math.random() * 5) + 1)/100;
}, 1000)

computer score:
0

A: You need to retrieve the previous value from your score and add your random Number to it :
PS: I added .toFixed(2) to limit your result to two decimals.

let score = document.getElementById("computerScore");

setInterval (function myFunction() {
  score.innerHTML = (+score.innerHTML + Math.floor((Math.random() * 5) + 1)/100).toFixed(2);
}, 1000)
computer score:
0

A: You set number to 0 every time you call the function, you should define number outside of the interval
var number = 0;
setInterval(function myFunction() {
    document.getElementById("computerScore").innerHTML = number +
        Math.floor((Math.random() * 5) + 1) / 100;
}, 1000)

A: You need to declare number outside the setTimeout:
var number = 0;
setInterval (function myFunction() {
  number = number +
  Math.floor((Math.random() * 5) + 1)/100;
  document.getElementById("computerScore").innerHTML = number;
}, 1000)

JSFiddle

A: you can try something like this. You forgot to set the number to 0. Then you have to increment your number with the random value you're getting.
https://codepen.io/anon/pen/dgJpep
JS :

  var number = 0;

function check(){

  setInterval(function(){
    number = number + Math.floor((Math.random() * 5) + 1)/100;
  }, 3000);
}

check();

setInterval(function(){
  document.getElementById('computerScore').innerHTML = number;
});

Let me know if it works for you !

A: Your problem is that you are setting number to 0 in each execution, while it should be the current value.
You need to assign Number(document.getElementById("computerScore").textContent) to it, so it keeps updating with the added random number.
Note that I used textContent which is recommended here as it holds only the text content of the element avoiding HTML elements.
setInterval (function myFunction() {
  var number = Number(document.getElementById("computerScore").textContent);
  document.getElementById("computerScore").textContent= number +
  Math.floor((Math.random() * 5) + 1)/100;
}, 1000)

Demo:

setInterval (function myFunction() {
  var number = Number(document.getElementById("computerScore").textContent);
  document.getElementById("computerScore").textContent = number +
  Math.floor((Math.random() * 5) + 1)/100;
}, 1000)
computer score:
0


text:
Q: Codeception4: GroupManager reports missing test file I upgraded Codeception to v4 (according to THIS) and then Symfony to v5 (according to THIS). Now, when I try to run tests I get an error about missing test file:

root@blabla: vendor/bin/codecept run
In GroupManager.php line 129:
GroupManager: File or directory /var/www/html/tests/unit/SomeFileCest.php does not exist

This file does NOT exist in current branch. It exists in another branch of the project, but current should not know anything about this file!
This problem happens no matter which branch I switch to. So somehow Codeception remembers, that one branch has additional test and demands that test in other branches. Looks like some sort of cache.
If I switch to the branch WITH the missing file, everything looks OK (I do get an error, but because of the old framework expected).
Error appears if I do vendor/bin/codecept run or vendor/bin/codecept run tests/functional for example (note that the missing test is a unit test).
I tried deleting /var and /vendor and running composer install/update. I also tried removing the branch completely and pulling from remote, but no joy.
Anybody has any idea why this would happen and how to fix this?

A: EDIT:
After some simple testing it looks like it's related to old references in tests/_support/failed (as @Naktibalda mentioned in his/her comment).

I still don't fully understand what happened, but this can be fixed by running:
vendor/bin/codecept clean

From Codeception help:

clean                 Recursively cleans log and generated code

I will try to investigate further to understand why this happens, but for now this is what I have.
I hope this helps someone avoid the frustrations I went through ;)

A: For my case we were using paracept, to run stuff in parallel. This generated group files in /tests/_data
Once I removed the group files in this folder my test suite ran normally.
Worth noting that codecept clean doesn't clear this _data folder.


text:
Q: How to JOIN on the closest record that is less than a value in T-SQL In this example, I have a table table with 1,3,4,8 in its value column, and a table lookup with the even numbers in its starting column.
I want to run a query that looks something like this
SELECT
    value, starting
FROM
    table
LEFT JOIN
    lookup ON lookup.starting < value

but only joins the row with the highest starting less than value.
The expected output looks like this
value | starting
------+-------
 1    |  null
 3    |  2
 4    |  2
 8    |  6

A: I would recommend this:
SELECT value, starting
FROM table
CROSS APPLY (select top 1 starting from lookup where lookup.starting < value order by value desc) as subquery(starting)

The top and order parts will work together to make sure you get only one, the suitable, result.

A: SELECT  value,
        starting
FROM    (
            SELECT  value,
                    starting,
                    ROW_NUMBER() OVER (PARTITION BY value ORDER BY starting DESC) as cnt
            FROM    #Table t
                    LEFT JOIN #Lookup l
                        ON l.starting < t.value
        ) a
WHERE   cnt = 1


text:
Q: Return records for current and previous year with year passed in a WHERE clause for Acumatica report Suppose I have a SQL view called INForecastTotalSales.
This view contains the following columns:
InventoryID, FinYear, TotalSales
I would like to create another view INForecastTotalSalePrevCurr, which would have the following columns:
InventoryID, FinYear, CurrentYearTotalSales, PreviousYearTotalSales
so that when I query
SELECT * FROM INForecastTotalSalePrevCurr i WHERE i.FinYear = 2020
the view would populate CurrentYearTotalSales, PreviousYearTotalSales with TotalSales data for 2020 and 2019 respectively. The catch if we have to join the original view on itself, it would have to be FULL OUTER JOIN, since we need data from both tables for all inventory id's.
I have tried using OUTER APPLY and putting the same view into a table valued function, but this would essentially work as LEFT JOIN.
The view would have to be used in Acumatica Report, so can't really pass parameters, if I were to use a function or stored procedure. I am limited to using WHERE clause, unless someone has some other suggestions.

A: Why do you need 2 views?
Better approach would be to create a single view with columns:
InventoryID, FinYear, CurrentYearTotalSales, PreviousYearTotalSales, TotalSales
Where I think you are going wrong is the assumption that you have to use SELCT * FROM ....  In fact this a poor approach and it is bettwe to explicitly state the columns as in:
SELECT InventoryID, FinYear, TotalSales FROM INForecastTotalSales
or
SELECT InventoryID, FinYear, CurrentYearTotalSales, PreviousYearTotalSales FROM INForecastTotalSales
That will likely simplify your view creation and also make your queries more robust.


text:
Q: Python: Issue with plotting time series (date and values) - weird looking plots w image for reference im getting this issue with plotting timeseries data where indexing the date produces weird plots. I have also tried plot(x='Date', y='values') but produced weird plots.
# splitting the column to account for date time.
new = df["Gmt time"].str.split(" ", n = 1, expand = True)
df["Date"]= new[0]
df["Time"]= new[1]

df['Date'] = pd.to_datetime(df['Date'])

head of data values
df.plot(x='Date', y='Close')

Output of code above
df = df.set_index(df['Date'])

Output of code after setting the date as index.
really appreciate if you could let me know where my code has gone wrong or an issue to fix the following.

A: Problem solved by adding dayfirst=True in read_csv().
Data was taken from dukascopy as a csv file.


text:
Q: How to identify in selenium IDE an input followed by a label? I have to identify a check-box using the label which follows it.
the code is the following:
<input type="checkbox" checked="" value="1" id="email-100-100" name="email-100-100">
Email me when someone asks me to set a flag

I tried
Target://following-sibling::label[text()="Email me when someone asks me to set a flag"]
Target://preceding-sibling::label[text()="Email me when someone asks me to set a flag"]
but in both cases selenium finds the text of label but not the check-box.
Could somebody help me in this?
Thank you in advance

A: Try
Target://label[text()="Email me when someone asks me to set a flag"]/../input[@type='checkbox']

It will work as long as the containing element of the label and checkbox only has one checkbox in it.

A: You can also find a label that contains text, which is useful for a partial match.    In my case I had something like this:

     <input name="blah" id="blah" type="checkbox" />
     Store Locator Plus

The accepted solution worked for the specific example cited but requires an exact match.  Since this comes up on the top of search results I figured I'd present the partial-match solution here as well.
For Selenium IDE you can set a target like this:
//label[contains(text(),'Store Locator Plus')]//input[@type="checkbox"]

The contains function was required because the label text had an HTML element as well which thwarted the //label[text()='Store Locator Plus'] target.


text:
Q: How can my application code know whether the app is being tested with testcafe? I have a suite of tests running with TestCafe. In one component, I need to know whether to expose some data to the window based on whether the application is running in testcafe or not, i.e.
if (window.Testcafe === true) {
    window.property = data;
}

This is possible with Cypress, another test framework, which exposes window.Cypress.
I've tried setting a property on window from the testcafe tests/fixtures, using code to the effect of
test('Test 1', async t => {
    await t.eval(() => {window.Testcafe = true});
    const val = await t.eval(() => window.Testcafe);
    // val === true
})
// In component window.Testcafe is false

I'm open to other approaches (besides window properties). Has anyone else done something similar?

A: TestCafe adds some properties to the window object which can help you determine that your site is working with TestCafe. For example, you can check the window['%hammerhead%'] property. If it exists, it means that TestCafe works.
However, I need to mention that it's not a public API. It's hardly will be changed in the future, but it is still not a 100% solid solution.
Could you please describe your scenario in detail? If many users find it helpful, we can consider implementing this feature in the future.
In addition, I want to mention that you can create feature requests in the TestCafe repository using the following form

A: The component has already loaded when the test starts its execution.
So setting the TestCafe variable inside the test is too late.
One workaround to test TestCafe hosting is:
if ( window.localStorage.nativeStorageKey && window.localStorage.nativeStorageKey.startsWith('hammerhead')) {
    window.property = data;
}


text:
Q: Find n given that $\lim\limits_{x\rightarrow0} \frac{1-\sqrt{\cos2x}.\sqrt[3]{\cos3x}.\sqrt[4]{\cos4x}...\sqrt[n]{\cos{nx}}}{x^2} = 10$ I'm trying to solve this rather interesting problem. We have been given that $\lim\limits_{x\rightarrow0}  \frac{1-\sqrt{\cos2x}.\sqrt[3]{\cos3x}.\sqrt[4]{\cos4x}...\sqrt[n]{\cos{nx}}}{x^2}$ = 10   and we are required to find n.
This is the $\frac{0}{0}$ form, so we can use L'Hôpital's rule. After taking the derivatives of the numerator and the denominator separately, the problem becomes-
$\lim\limits_{x\rightarrow0}  \frac{-\frac{d}{dx}\sqrt{\cos2x}.\sqrt[3]{\cos3x}.\sqrt[4]{\cos4x}...\sqrt[n]{\cos{nx}}}{2x}$ = 10
$\lim\limits_{x\rightarrow0}  \frac{-\frac{d}{dx}\prod_{i = 2}^{n} (\cos ix)^\frac{1}{i}}{2x}$ = 10
Now, the numerator looks like a pretty difficult expression to differentiate. Here, I decided to simplify the expression in the numerator first.
Let y= $\prod_{i = 2}^{n} (\cos ix)^\frac{1}{i}$
Now, we can simplify the expression by taking the natural logarithm of both sides.
$\log(y)$= $\log(\prod_{i = 2}^{n} (\cos ix)^\frac{1}{i})$
Now we can use the property of logarithms to simplify the expression, $\log(xy)=\log(x)+\log(y)$
$\log(y)$= $\sum_{i = 2}^{n} \frac{1}{i}.\log(\cos ix)$
This is where I ran out of ideas to simplify this expression any further. Any ideas would be appreciated.

A: You proceed further by implicitly differentiating: $\dfrac{dy}{dx}(\log y)=\dfrac1y \dfrac{dy}{dx}$.
$$\dfrac1y \dfrac{dy}{dx}=\sum_{i=2}^n\frac1i\frac{1}{\cos ix}(-i\sin ix)=-\sum_{i=2}^n\tan ix.$$ Therefore, $\dfrac{dy}{dx}=y'=-y\sum_{i=2}^n\tan ix.$
Now, as $x\to 0$, $\sum_{i=2}^n\tan ix\to 0$ and $y\to 1$, so $y'\to 0$.
Thus, we have again got a $\dfrac00$ form, $\displaystyle \frac{y\sum_{i=2}^n\tan ix}{2x}$, on our hands. Differentiating again, we get $$\lim_{x\to 0}\frac{y'\sum_{i=2}^n\tan ix+y\tfrac{d}{dx}\left(\sum_{i=2}^n\tan ix\right)}{2}=\lim_{x\to 0}\frac{-y\left(\sum_{i=2}^n\tan ix\right)^2+y\left(\sum_{i=2}^ni\sec^2 ix\right)}{2}$$$$=\dfrac{\sum_{i=2}^ni}{2}=\dfrac{n^2+n-2}{4}=10 \ (given).$$ Therefore, we get $n=6, -7.$ But since $n$ is the index of a sum, it must be a natural number. Thus, $n=6$.
EDIT: As per user @Vishu's comment, $\displaystyle \lim_{x\to 0}\frac{y\sum_{i=2}^n\tan ix}{2x}$ can be simplified more easily as $\displaystyle \lim_{x\to 0}\dfrac y2\sum_{i=2}^n\frac{\tan ix}{x}=\displaystyle \lim_{x\to 0}\dfrac y2\sum_{i=2}^ni\frac{\tan ix}{ix}=\displaystyle \lim_{x\to 0}\dfrac y2\sum_{i=2}^n i$ by using the fact that $\lim_{u\to 0}\dfrac{\tan u}{u}=1.$

A: Using the fact that:
$$\cos(nx)\sim 1-\frac{n^2}{2}x^2$$
we have:
$$\frac{1-\sqrt{\cos2x}.\sqrt[3]{\cos3x}.\sqrt[4]{\cos4x}...\sqrt[n]{\cos{nx}}}{x^2}\sim\frac{1-\left((1-2x^2)^{\frac12}\dots\left(1-\frac{n^2}{2}x^2\right)^{\frac{1}{n}}\right)}{x^2}$$
Now, remember that:
$$(1-f(x))^{\alpha}\sim1-\alpha f(x)$$
when $f(x) \to 0$, so:
$$\frac{1-\left((1-2x^2)^{\frac12}\dots\left(1-\frac{n^2}{2}x^2\right)^{\frac{1}{n}}\right)}{x^2}\sim\frac{\left(\sum_{i=2}^{n}\frac{1}{i}\cdot\frac{i^2}{2}\right)x^2}{x^2}=\sum_{i=2}^{n}\frac{i}{2}=\frac12\cdot\sum_{i=2}^{n}i=$$ $$=\frac{n\cdot(n+1)}4-\frac12$$
Thus, we have:
$$\frac{n\cdot(n+1)}{4}-\frac12=10 \leftrightarrow n=6$$

A: Note : I realized that this answer is probably not recommended in an exam, but in any case it's useful to know.
One can use the "multiple product" rule for differentiation. Let's write $f'$ for $\frac{df}{dx}$ for this answer. We know that $(fg)' = f'g+fg'$ is the product rule, but as an extension (by induction), one can show that $$(f_1f_2\ldots f_m)' = \sum_{j=1}^m f_1f_2\ldots f_{j-1}f_j'f_{j+1}\ldots f_m$$ for functions $f_1,\ldots,f_m$. This rule is usable in your situation, instead of taking the logarithm. (Roughly, you sum over all possible products of $m$ functions where exactly one of the functions is differentiated and the others are not).
However, you need to look ahead. When you get to $$
\lim_{x \to 0} \frac{-\frac {d}{dx} \prod_{j=2}^{n} (\cos jx)^{\frac 1j}}{2x}
$$
You know that, in hindsight, this needs to equal $10$. However, the denominator evaluates to $0$ at $x=0$, so you actually need to differentiate the numerator once more as well, because you need another round of L'Hospital's rule to make the $2x$ into $2$ and make the denominator well defined and get a limit which is not equal to $0$ or $+\infty$, but some finite number.
It turns out that, similar to the multinomial theorem, one has a rule for differentiating a product of functions as many times as necessary. It's the "ultimate" product rule.

"Product rule" : If $f_1,\ldots,f_m$ are functions and $L$ is the number of times you need to differentiate $F = f_1\ldots f_m$ then the $L$th derivative of $f$ equals $$
F^{(L)} = \sum_{k_1+k_2+\ldots+k_m = L, k_i \geq 0} \binom{L}{k_1,k_2,\ldots,k_m}f_1^{(k_1)}f_2^{(k_2)}\ldots f_m^{(k_m)}
$$
where $\binom{L}{k_1,k_2,\ldots,k_m}$ is the multinomial coefficient.

See here for details on this rule.
What you need is to differentiate the numerator $\prod_{j=2}^{n} (\cos jx)^{\frac 1j}$ two times. According to this rule, you will obtain $$
\sum_{k_1+k_2+\ldots+k_n = 2, k_i \geq 0} \binom{2}{k_1,k_2,\ldots,k_n}\left((\cos 2x)^{\frac 12}\right)^{(k_1)}\ldots \left((\cos nx)^{\frac 1n}\right)^{(k_n)}
$$
Thankfully, this is not too difficult when you realize that only one of two things can happen.

*

*Either there are two different $i \neq j$ such that $k_i=k_j=1$ and the others are $0$.

*There is a single $i$ for which $k_i=2$ and the others are $0$.
In the first case, the first derivative of $(\cos ix)^{\frac{1}{i}}$ is $$
\left((\cos ix)^{1/i}\right)' = (\sin ix)(-\cos^{1/(i-1)}(ix))
$$
which equals $0$ when evaluated at $0$. So this case gives $0$.
In the second case, we differentiate again using the product rule to get $$
\left((\cos ix)^{1/i}\right)'' = (\cos^{1/(i-2)}(ix))(-(i-1)\sin^2(ix)-i \cos^2(ix))
$$
at $0$, this equals $-i$. The multinomial coefficients are all equal to $1$ in this case, so we land up with $$
\left(\prod_{j=2}^{n} (\cos jx)^{\frac 1j}\right)'' (0) = -2-3-\ldots-n = 1-\frac{n(n+1)}{2}
$$
Plugging this back into the original L'Hospital rule, the limit of the quantity you want as a function of $n$, is then equal to $$
\frac{\frac{n(n+1)}{2}-1}{2}
$$
(the $2$ denominator comes from differentiating the $2x$ at the bottom during the $2$nd L'Hospital round).
If this is equated to $10$, then you get that $$
\frac{n(n+1)}{2} = 21 \implies n=6
$$
as desired.
This method is the "brute force" way of extending the original post's approach. It requires one heavy tool, but that tool finds a lot of usage in analysis of products in the future (and can be made slightly easier if one uses the cosine Taylor series) and I think it's a nice thing to know at the high school level.

A: Using $y=e^{\ln(y)}$, you can differentiate
$$y'=(e^{\ln(y)})'=e^{\ln(y)}\cdot (\ln(y))'=y\cdot(\sum_{i=2}^n \frac{1}{i}\ln(\cos(ix)))'=(\sum_{i=2}^n \frac{1}{i}\frac{-i\sin(ix)}{\cos(ix)})\cdot y$$
$$=-y\cdot \sum_{i=2}^n \tan(ix)$$
So now your limit becomes
$$\lim_{x\to 0} \frac{y\cdot \sum_{i=2}^n \tan(ix)}{2x}$$
Applying L'Hospital's rule once more (as this limit is still of type $\frac{0}{0}$) gives a derivative of $2$ in the denominator. For the numerator the drivative is
$$y'\cdot \sum_{i=2}^n \tan(ix)+y\cdot (\sum_{i=2}^n \tan(ix))'=y'\cdot \sum_{i=2}^n \tan(ix)+y\cdot (\sum_{i=2}^n \frac{i}{\cos^2(ix)})$$
Plugging in our expression for $y'$, we get
$$-y\cdot \sum_{i=2}^n \tan(ix)\cdot \sum_{i=2}^n \tan(ix)+y\cdot (\sum_{i=2}^n \frac{i}{\cos^2(ix)})$$
As $x\to 0$, it is easy to see that $y\to 1$, and that the entire first term here goes to $0$. $\cos(ix)\to 1$ for $x\to 0$, and thus we are overall left with:
$$\frac{\sum_{i=2}^n i}{2}=10 \implies \frac{\frac{1}{2}\cdot(n^2+n-2)}{2}=10\implies n^2+n-42=0 \implies n=6 \space\text{or}\space n=-7$$
$n\in \mathbb{N}$, so we have $n=6$.


text:
Q: Count Unique in each list column I have a dataframe with a list column that was created by str_extract_all(). I'm trying to identify cases where there are more than 1 unique value
#Input =
#                         List
#1:                apple,apple
#2:               apple,banana
#3: apple,orange,orange,banana``

dat<-data.table::data.table(
          List = list(c("apple","apple"),
                   c("apple","banana"),
                   c("apple","orange","orange", "banana")),
  Count_Unique = c(1L, 2L, 3L),
  Multi = c(FALSE, TRUE, TRUE)
)

I tried dplyr::mutate(Count_Unique = length(unique(List)), but this just gives me the number of unique variables for the entire dataset. I'm sure its very simple I just can't figure how to do this in a rowwise fashion using tidyverse methods if possible.
#Expected Output =
#                         List Count_Unique Multi
#1:                apple,apple            1 FALSE
#2:               apple,banana            2  TRUE
#3: apple,orange,orange,banana            3  TRUE

dat<-data.table::data.table(
          List = list(c("apple","apple"),
                   c("apple","banana"),
                   c("apple","orange","orange", "banana")),
  Count_Unique = c(1L, 2L, 3L),
  Multi = c(FALSE, TRUE, TRUE)
)

A: You can use map_dbl :
library(dplyr)
library(purrr)

dat %>% mutate(Multi = map_dbl(List, n_distinct) > 1)

#                         List Count_Unique Multi
#1:                apple,apple            1 FALSE
#2:               apple,banana            2  TRUE
#3: apple,orange,orange,banana            3  TRUE

Using base R :
dat$Multi <- sapply(dat$List, function(x) length(unique(x))) > 1

Or in data.table :
library(data.table)
setDT(dat)[, Multi := sapply(List, function(x) length(unique(x))) > 1]

A: Using data.table
library(data.table)
setDT(dat)[, multi := unlist(lapply(List, uniqueN)) > 1]


text:
Q: Override itemrender in block - Magento I'm new to Magento, so sry if it's a newbie question
Basically there is a block declared as follows in a layout.xml file:
<block type="checkout/cart" name="checkout.cart">
     <action method="setCartTemplate"><value>checkout/cart.phtml</value></action>
     <action method="setEmptyTemplate"><value>checkout/cart/noItems.phtml</value></action>
     <action method="chooseTemplate"/>
     <action method="addItemRender"><type>simple</type><block>checkout/cart_item_renderer</block><template>checkout/cart/item/default.phtml</template></action>
     <action method="addItemRender"><type>grouped</type><block>checkout/cart_item_renderer_grouped</block><template>checkout/cart/item/default.phtml</template></action>
     <action method="addItemRender"><type>configurable</type><block>checkout/cart_item_renderer_configurable</block><template>checkout/cart/item/default.phtml</template></action>

I would like to override <action method="addItemRender"><type>simple</type><block>checkout/cart_item_renderer</block><template>checkout/cart/item/default.phtml</template></action> with a custom template.
Since a method is being called over here, how could the template be changed?
Thanks a lot!
Krt_Malta

A: In you module layout file or local.xml
<reference name="checkout.cart">
   <action method="addItemRender">
      <type>simple</type><block>checkout/cart_item_renderer</block><template>path/to/your/item/default.phtml</template>
   </action>
</reference>

The path to template file is relative to your theme template folder
You may want to check
http://www.classyllama.com/development/magento-development/the-better-way-to-modify-magento-layout