text:
Q: Functions.php and includes My functions.php file is getting on the long side. Is it all right to use includes to break it up (php includes I mean) or is this considered bad form?

A: Many theme frameworks and complex themes break up functions into different files and include them in one file called functions.php, sometimes within a folder called inc. If it's your own theme, you can pretty much do what you want.
If it's a theme to be released, end users typically look for a functions.php file as the default WP framework functions file.
The two latest default WP themes - twentyten http://wordpress.org/extend/themes/twentyten and twentyeleven http://wordpress.org/extend/themes/twentyeleven - use one functions.php file, as that's part of the standard WP theme file structure.
But again, many themes use multiple files for functions, and if a user wants to work with or modify the theme, they will need a certain level of proficiency anyway. Code comments are helpful.

A: I think it is down to personal preference - as far as I'm aware there are no conventions that say you should or shouldn't use includes in the functions file.
Personally, I do like to split the functions file up into separate includes - I find it a lot easier to find the section of code I'm looking for when it's in a separate file rather than trawling through 1000's of lines of code.
As long as you comment everything in a meaningful way should anyone else work on the theme in the future they'll be able to understand what you've done and why.

A: If you have anything in the functions.php file that is more of a site function than related directly to the specific theme formatting, you should consider moving to a site-specific plugin.
More on this: http://wpcandy.com/teaches/how-to-create-a-functionality-plugin


text:
Q: Nowhere dense point set I am trying to show for a complete metric space $X$ without isolated points, a set $\{x\}$ consisting of a single point is nowhere dense. I have found the following proof online, but I don't follow it exactly:
Choose an open ball $B$ $x \in B$, so that $B(x,r) \subset X$ for some $r$. Since $x$ is an accumulation point of $X$, there is a point $y \in B(x,r), y \not=x$. Since $B(x,r)$ is open we have $B(y,r_1) \subset B(x,r)$ for some $r_1 >0$. Furthermore for $r_0 = \min\{d(x,y),r_1\}$ we have $x \notin B(y,r_0) \subset B(x,r) \subset B$ which implies the result.
I don't understand where this uses completeness, and where it uses that $X$ has no isolated points

A: You don't need completeness. Nor being metric, only that singleton sets are closed.
The proof is trivial: a set $A$ is nowhere dense iff the interior of $\overline{A}$ is empty. (If you don't know it, prove it. )
And so if singletons are closed they are nowhere dense iff they have empty interior iff they are not an isolated point.
Added explaining the proof you cited:
Completeness is still not needed. There the other definition of nowhere denseness of $A$ is used: $A$ is nowhere dense iff for every non-empty open set $O$ there is some non-empty open $O' \subseteq O$ such that $O' \cap A = \emptyset$.
So $A = \{x\}$ this translates to : for every non-empty open set $O$ there is a smaller open set $O' \subseteq O$ such that $x \notin O'$. In proving this we can assume WLOG that $x \in O$, or else we take $O ' = O$ and we're done.
In a metric space we can moreover use open balls (as they form a base), so then we just have to show that for every open ball/set $B$ that contains $x$, there is a ball $B(y,r') \subseteq B$ that does not contain $x$.
So the proof starts with $B$ containing $x$, and $B(x,r) \subseteq B$. Then $B(x,r) \neq \{x\}$ (which is the same as saying that $x$ is an accumulation point of $X$), because $x$ is not an isolated point (this is where it used). So $y \neq x$ exists in $B(x,r)$.
As $B(x,r)$ is open we have some ball $B(y,r_1) \subseteq B(x,r)$ as well.
Then take $r_0 \leq r_1$ and $r_0 < d(x,y)$, so that $x \notin B(y,r_0)$ (this in fact proves that $\{x\}$ is closed, which is what I use in the short general proof), and $B(y,r_0) \subseteq B(y,r_1) \subseteq B(x,r) \subseteq B$.
So we see the closedness of singletons and the non-isolated point assumptions being used here as well. But the metric is quite irrelevant really. As is completeness.

redpajama_set_name: RedPajamaStackExchange


text:
Q: While loop with multiple IF conditions I wrote a program that receives from the user one string representing a shopping list. The program asks the user to enter a number between 1 and 9. Depending on the number received, do one of the following:
And after making a user selection, the user returns to the main menu until they select number 9 to exit.
The syntax is correct but the program does not print what is needed. How to fix it?
def shopping_list(my_str):
    my_list = my_str.split(",")
    i = input("Please choose a number between 1 and 9: ")
    while i in range(1, 10):
        if i == 1:
            print("My shopping list:", my_list)
            continue
        elif i == 2:
            print("The number of items in my shopping list:", len(my_list))
            continue
        elif i == 3:
            product = input("Please enter a product name: ")
            if product in my_list:
                print("This product is in the shopping list.")
            else:
                print("This item is not in the shopping list.")
            continue
        elif i == 4:
            product = input("Please enter a product name: ")
            print("The item", product, "shows", my_list.count(product), "in the list")
            continue
        elif i == 5:
            product = input("Please enter a product name: ")
            new_list = my_list.remove(product)
            print("The item", product, "remove from the list. The new list is", new_list)
            continue
        elif i == 6:
            product = input("Please enter a product name: ")
            my_list += product
            print("The item", product, " add to the list. The new list is", my_list)
            continue
        elif i == 7:
            new_list = []
            for product in my_list:
                if len(product) < 3 or not(product.isalpha()):
                    new_list += product
            continue
        elif i == 8:
            print(list(set(my_list)))
            continue
        else:
            break
shopping_list("Milk,Cottage,Tomatoes")

A: *

*You never ask again the user, so the loop goes infite doing the first choice given by the user.

*Also remove the continue statement, you don't need them as all code is in elif also it'll allow you to ask the user a new choice at the end of the loop.

*convert the input to int, you won't be able to enter the loop without

def shopping_list(my_str):
    my_list = my_str.split(",")
    i = int(input("Please choose a number between 1 and 9: "))
    while i in range(1, 10):
        if i == 1:
            print("My shopping list:", my_list)
        elif i == 2:
            print("The number of items in my shopping list:", len(my_list))
        elif i == 3:
        # ...
        elif i == 8:
            print(list(set(my_list)))
        else:
            break
        i = int(input("Please choose a number between 1 and 9: "))

Final Full Code

Now corrections about

*

*mode 5 : what is returned by remove is None, the modification is in-placed so do
elif i == 5:
    product = input("Please enter a product name: ")
    my_list.remove(product)
    print("The item", product, "remove from the list. The new list is", my_list)

*mode 6 the operator += does an extend on the list so it'll add all chars, do append instead
elif i == 6:
    product = input("Please enter a product name: ")
    my_list.append(product)
    print("The item", product, " add to the list. The new list is", my_list)

*mode 7 creating a new list that is a filter of the main one is useless if you forget it. Also I'd say you remove the items that are smaller than 3 or contains non-alpha, here you keep them. Finally use append
elif i == 7:
    new_list = []
    for product in my_list:
        if len(product) >= 3 and product.isalpha():
            new_list.append(product)
    my_list = list(new_list)

or just use a list comprehension
elif i == 7:
    my_list = [p for p in my_list if len(p) >= 3 and p.isalpha()]

A: I would do this: (Cut out some elifs due to too much code.)

while True:
    i = int(input("Please choose a number between 1 and 9: "))

    if i == 1:
            print("My shopping list:", my_list)
            continue
        elif i == 8:
            print(list(set(my_list)))
            continue
        elif i == 9:
            break
        else:
            print("Invalid Number! Try again.")

Is this what you want? I'm not quite getting what you're asking for.


text:
Q: useState does not changing after setstate callback? I just want to add error message in error state. But when error occurs setError does not changing means does not adding error message. Back-end giving the error message as json format { "error": "error message" } and if I console log that error that works fine but error state is not updating.
import { useState, useCallback, useRef, useEffect } from 'react';

export const useHttpClient = () => {
    const [ isLoading, setIsLoading ] = useState(false);
    const [ error, setError ] = useState();

    const activeHttpRequests = useRef([]);

    const sendRequest = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
        setIsLoading(true);
        const httpAbortCtrl = new AbortController();
        activeHttpRequests.current.push(httpAbortCtrl);
         try {
            const response = await fetch(url, {
                method,
                body,
                headers,
                signal: httpAbortCtrl.signal
            });
            const responseData = await response.json();
            activeHttpRequests.current = activeHttpRequests.current.filter(
                reqCtrl => reqCtrl !== httpAbortCtrl
            );

            if(!response.ok) {
                throw new Error(responseData.error);
            }

            setIsLoading(false);
            return responseData;
        } catch (e) {
            setError(e.message);
            setIsLoading(false);
            throw e;
        }
    }, []);

     const clearError = () => {
         setError(null);
     };

    useEffect(() => {
        //this runs as cleanup function before next time useEffect run or also when an component use useEffect unmount
        return () => {
            activeHttpRequests.current.forEach(aboutCtr => aboutCtr.abort());
        }
    }, []);

     return { isLoading, error, sendRequest, clearError };
}

A: As your backend is responding with JSON, that would mean the response status code is probably 200 (successful). Which makes "response.ok" true.
You will have to look at the returned JSON string for valid data or error message.


text:
Q: Randomly select N unique elements from a list, given a probability for each I've run into a problem: I have a list or array (IList) of elements that have a field (float Fitness). I need to efficiently choose N random unique elements depending on this variable: the bigger - the more likely it is to be chosen.
I searched on the internet, but the algorithms I found were rather unreliable.
The answer stated here seems to have a bigger probability at the beginning which I need to make sure to avoid.
-Edit-
For example I need to choose from objects with the values [-5, -3, 0, 1, 2.5] (negative values included).

A: The basic algorithm is to sum the values, and then draw a point from 0-sum(values) and an order for the items, and see which one it "intersects".
For the values [0.1, 0.2, 0.3] the "windows" [0-0.1, 0.1-0.3, 0.3-0.6] will look like this:
  1 23 456
 |-|--|---|
 |-*--*---|

And you draw a point [0-0.6] and see what window it hit on the axis.
Pseudo-python for this:
original_values = {val1, val2, ... valn}

# list is to order them, order doesn't matter outside this context.
values = list(original_values)

# limit
limit = sum(values)
draw = random() * limit

while true:
    candidate = values.pop()
    if candidate > draw:
         return candidate
    draw -= candidate

A: So what shall those numbers represent?
Does 2.5 mean, that the probability to be chosen is twice as high than 1.25? Well - the negative values don't fit into that scheme.
I guess fitness means something like -5: very ill, 2.5: very fit. We have a range of 7.5 and could randomly pick an element, if we know how many candidates there are and if we have access by index.
Then, take a random number between -5 and 2.5 and see, if our number is lower than or equal to the candidates fitness. If so, the candidate is picked, else we repeat with step 1. I would say, that we then generate a new threshold to survive, because if we got an 2.5, but no candidate with that fitness remains, we would search infinitely.
The range of fitnesses has to be known for this, too.
fitnesses [-5, -3,  0,  1, 2.5]
rand -5     x   x   x   x   x
     -2.5   -   -   x   x   x
      0     -   -   x   x   x
      2.5   -   -   -   -   x

If every candidate shall be testet every round, and the -5 guy shall have a chance to survive, you have to stretch the interval of random numbers a bit, to give him a chance, for instance, from -6 to 3.


text:
Q: Passing jQuery function to higher-order function I'm experimenting with higher-order functions in Javascript and I wrote up something like this:
function hof (setter) {
    setter("not test");
}

function hof2 (setter) {
    setter.call(window.jQuery, "not test 2");
}

var span = $("#myTest").text;
hof(span);
hof2(span);

Here's the jsFiddle version: http://jsfiddle.net/6mcYt/
However, both functions throw an error. What is the best way to pass jQuery setter functions to a higher-order function?

A: The text function actually belongs on jQuery.fn (which is also assigned to the prototype property of the jQuery constructor). If you pass that as the first argument to setter.call, it will stop throwing an error. BUT it won't work if the desired result is changing the text on #myTest, because you won't have any reference to the element anymore (you left that on $("#myTest"), which is an instance of the jQuery constructor).
Sorry if I can't offer an actual solution, I'm not sure what you're trying to accomplish here.

A: I think what you want to do (I am not 100% sure) should be like this.
function hof ($el) {
    $.fn.text.call($el, 'test1')
}

var span = $("#myTest");
hof(span);

here is the fiddle http://jsfiddle.net/6mcYt/2/
Another option is to bind the text method with context first.
function hof2 (setter) {
    setter("not test 2");
}
var spanFn = $.proxy($.fn.text, $("#myTest"));
hof2(spanFn);

Fiddle


text:
Q: There is not enough space on the disk when there is? Permissions are fine (inherited) and checking effective permissions everything is AOK.

As you can see i can make a file in the docs folder but not the pdf_docs subfolder.

The folder has a lot of files and is quite large- i wonder if i've reached a limit? I couldn't find anything on google.
Size: 51.0 GB (54,819,804,885 bytes)
Size on disk: 52.0 GB (55,925,719,040)
Contains 554,697 Files

EDIT I've just checked and i can delete files... and for every file i delete i appear to be able to create a new one. This definitely points toward a limit in terms of number of files?

A: I had a similar problem with a Windows client trying to access a Linux server. I shared a folder that had mounts from different disks. The problem and solution are described in this answer:  https://askubuntu.com/a/631977/535528
in short the solution is to share the individual disks, rather than some parent where those are mounted. This will also result in exporting multiple shares instead of one from the samba configuration.

A: It is likely that a quota has been set on the pdf_docs directory.
Directory quotas are configured using the File Server Resource Manager tool.  You must be an administrator on the file server to use it.

A: Assuming your permissions are indeed correct, and that the drive has sufficient storage space to create the file, I would check the number of characters in the full path to that folder. The maximum length for the path in Windows is 260 characters according to this answer on stackoverflow.

A: According to this image:

It looks like it's set to Read-Only. I think that any be your problem. If you deselect it probably will be fixed. If it isn't, it's something more serious.

A: In Windows a directory is implemented as an index file, and when an index file gets too fragmented it is not possible to add new entries.
To resolve the problem, defragment the index file as described here.

A: I don't know if you solved your problem or not, but I was struggling for a while with the same issue. I bought a new external hard disk 6TB WD, while copying a large folder with too many folders and files, the same issue occurs. The hard disk was formatted in exFAT file extension, reformatting it to NTFS solved the problem.

A: It just took me a month to figure out the same problem. My system saw only 1GB free out of 8GB of my SD Card on my PI, when i tried to mount Samsung 128GB. The reason was simple, I had files in the mounting directories (left over from previous sharing.) Once i removed everything from the folders, I got full 119GB free to use in Win10. :)
I hope this will help somebody in a future.


text:
Q: Topology for the pseudoconvex domain? Let $n\geq 2,$ is there a pseudoconvex domain $\Omega\subset \mathbb{C}^n$ such that $(\overline{\Omega})^c$ is disconnected?
(i) When $\Omega$ is bounded, I try to use Hartogs' Extension Theorem to prove $(\overline{\Omega})^c$ is connected. But when I take a bounded component $U$ of $(\overline{\Omega})^c,$ I cannot prove $\Omega\cup \overline{V}$ is open.
(ii) If $\Omega$ is unbounded, is there a example to show that $(\overline{\Omega})^c$ is disconnected.


text:
Q: For each and animate figures using Jquery I have 6 divs having the classname "count".
I'm trying to replicate this: http://jsfiddle.net/4v2wK/
I'm simply trying to animate figures, but nothing works, here is my code:
$('.count').each(function(){
    $({someValue: 1000}).animate({someValue: this.value}, {
        duration: 6000,
        easing: 'swing', // can be anything
        step: function () { // called on every step
            // Update the element's text with rounded-up value:
            $(this).text(commaSeparateNumber(Math.round(this.someValue)));
        }
    });
});

Thanks a lot in advance for your help,
Isabelle,

A: I was looking for the same kind of script and this one is working for me :
 $(document).ready(function(){

            $('.feature').each(function(){
                var el = $(this);
                $({someValue: 1}).animate({someValue: el.html()}, {
                    duration: 3000,
                    easing: 'swing',
                    step: function () {
                        el.html(Math.round(this.someValue));/**/
                    }
                });
            });

        });

Hope it helps ...


text:
Q: when storing image in mysql database i have error
Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES) in C:\xampp\htdocs\ramya\store.php on line 37  Could not connect localhost:Access denied for user 'root'@'localhost' (using password: YES)

<?php

    error_reporting(E_ALL);
    $server = "localhost";
    $login = "root";
    $s_password = " ";

    $hotel_name=$_POST['hotel_name'];
    $street_name=$_POST['street_name'];
    $city=$_POST['city'];
    $state=$_POST['state'];
    $country=$_POST['country'];
    $zipcode=$_POST['zipcode'];
    $phone_number=$_POST['phone_number'];
    $fax=$_POST['fax'];
    $email_id=$_POST['email_id'];
    $pass=$_POST['password'];

    foreach ($_FILES["pictures"]["error"] as $key => $error) { //used for multiple uploads

        if ($error == UPLOAD_ERR_OK) {
            $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
            }
    }

    $size = getimagesize($tmp_name);

    $width = $size[0]; // get width of the image
    $height = $size[1]; //get height of the image
    $type = $size[2]; //get type of the image
    $mime_type = $size['mime']; //get MIME of the image

    if(!$data = addslashes(@fread(@fopen($tmp_name, "r"), @filesize($tmp_name)))){
        die("\n
Cannot read temp file: $tmp_file");
    }

    $link = mysql_connect($server, $login, $s_password);
    if (!$link) {
        die("\n
Could not connect $server:" .  mysql_error());
    }

    $db_selected = mysql_select_db("test");

    if (!$db_selected) {
        die ("\n
Can\'t use Table : $db_selected" . mysql_error());
    }

    $query   = "INSERT INTO image_data ";
    $query  .= " (hotel_name,street_name,city,state,country,zipcode,phone_number,fax,email_id,password,image_type, image_width, image_height, image_data) ";
    $query  .= " values ";
    $query  .= " ('$hotel_name','$street_name','$city','$state','$country','$zipcode','$phone_number','$fax','$email_id','$pass','$mime_type', '$width', '$height', '$data') ";

    $result = mysql_query($query);

    if (!$result) {
        $message  = '
Invalid query: ' . mysql_error() . "\n";
        die($message);
    }

    $image_id = mysql_insert_id() ;
    echo "\n";

    mysql_close($link);

    exit();

?>

A: This specific error has nothing to do with your code.  You're not getting logged into MySQL in the first place.  Make sure your account has access.
Also, this entire script is extremely insecure.  Use prepared/parameterized queries to avoid SQL injection attacks.  The way you are handling the data now probably won't even work at all.  addslashes() isn't sufficient.

A: The error means exactly what it says. It's not a problem with your PHP file - it's that you don't actually have permission to connect to the MySQL server that you're trying to.

*

*Is your MySQL server really hosted on localhost?

*Do you want to connect to it as the root user?

*Do you really mean to use a single space as the password?

That being said, there are many problems with your PHP file as well. The most obvious is simply that you're using the mysql_* functions. These should not be used in new code becasue they are no longer maintained and are officially deprecated. (See the red box?)
You should be using PDO or MySQLi instead.
The second problem is that you ar extremely vulnerable to SQL injection. This could be fixed by calling mysql_escape_string() on each variable you include in your query, but a better solution is to switch to PDO or MySQLi and investigate prepared statements.

A: please check there is space in password, try removing that
$s_password = "";


text:
Q: Python String manipulation from a file and writing into a new file after checking the string I'm trying to help my partner with his Python class, but I don't know much about Python. Here's the problem he has been stuck for hours, any help would be appreciated!
Question:
The program will accept a text file of DNA sequences (1 sequence per line in the file) and determine if the sequence is valid when the following criteria is met:
1. length is a multiple of 3.
2. starts with ATG.
3. ends with TAG.
The program will then write the DNA sequence followed by 'True' or 'False' to a new file (each output on a separate line).
Example:
Input sequence: 'ATGCGCCTGCGTCTGTACTAG' from input file.
Output: 'ATGCGCCTGCGTCTGTACTAG True' to the output file.

A: def check_sequence(sequence):
    if len(sequence) % 3:
        return False
    if sequence[:3] != 'ATG':
        return False
    if sequence[-3:] != 'TAG':
        return False

def process_file(input_file_path, output_file_path):
    with open(input_file_path) as input_file:
        with open(output_file_path, 'w') as output_file:
            for map(str.rstrip, input_file):
                output_file.write(line)
                output_file.write(' ')
                output_file.write(str(check_sequence(line)))
                output_file.write('\n')


text:
Q: Customisation of PowerDesigner model I've got a DWH logical model in SAP PowerDesigner. How can I choose the properties to display on the diagram?
For example, instead of showing the Attribute's data type on the scheme, I would like to represent its description.
I've tried doing this:
Right-click on the object > Format... > Content > Attributes.
There you can choose between Stereotype, Identifier indicators, Data type, Domain or data type, Domain, Mandatory and either hide or show them. However, each Attribute has custom Comment and Description and I can't select them there.

A: Even by going through Customize Content, Tools > Display Preferences > Entity > Advanced, it seems you can only display single-line attributes, which excludes Comment, Description, Annotation. Maybe because Attributes appear as a list on the Entity symbol, so the Attribute Description would be hard to fit in this list.
As I suggested elsewhere, you could try to use a Computed Extended Attribute.


text:
Q: C++ - Class implicitly convertible to size_t I have created a simple class and I would like it to be convertible to size_t. But I don't understand how to do it.
class MyClass {
private:
    std::size_t size;
public:
    MyClass();
    ~Myclass();
};

I tried this got some errors :
Error: namespace std has no member class size_t

Thanks for your help in advance.

A: std::size_t can be found in multiple headers, for example <cstddef>
To enable the conversion, you can provide a operator std::size_t member function :
#include <cstddef>

class MyClass {
private:
    std::size_t size;
public:
    operator std::size_t() const {
        return this->size;
    }
    //...
};

the compiler will call the member function when needed:
int main() {
    MyClass foo;
    std::size_t s = foo;
}


text:
Q: Angular.js: run command on ngshow I have the following setup in an angular.js application, basically 3 of the elements in lesson.answers are show to begin with, and the 'Move Right' button scrolls the list. (I can't seem to get it to run in the example window, but the code is simple enough to grok anyway)

(function() {
  var app = angular.module('lessonEditApp');

  app.controller('LessonController', function() {
    this.answers = ['$15$', '$12$', '$10$', '$8$'];
    this.answerPos = 0;
  });
})();
<html ng-app='lessonEditApp'>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </head>
  <body ng-controller='LessonController as lesson'>
    <button ng-click='lesson.answerPos = lesson.answerPos + 1'>Move Right</button>
    <div ng-repeat='answer in lesson.answers | limitTo:3:lesson.answerPos'>
      {{answer}}
    </div>
  </body>
</html>

The trouble is that those answer elements ($15$, $12$, etc) are LaTeX, and need to be marked up by another library (MathJax) after they load, so I need to know when these elements appear.
Looking at other, similar questions, answers generally propose that any extra processing steps can be done when the state changes i.e. onclick of the 'Move Right' button, but MathJax has to be called after the element has actually been rendered in the DOM in order to take effect.
Is there any way within Angular that I can trigger a function to run when elements have actually been created? Ideally it would be attached to each specific element that is shown, but a page-wide trigger would be workable.


text:
Q: When is the storage reclaimed for a resource that is no longer owned? There is a vector resource that is allocated in line 2 of the program below.
When the program ends, the vector resource is not owned.  If a resource is not owned at all, when does it get reclaimed? Is there an explanation using the terminology of Rust ownership semantics and lifetimes that could convince a programmer that this resource is indeed reclaimed?
fn main() {
    let mut v = vec![1,2];
    v = vec![3, 4];
}

A:
when does [an unowned resource] get reclaimed?

In Rust terms, an item is dropped when it goes out of scope, which often (but not always) corresponds to the end of a block. When it is dropped, any resources that are part of the item are also released.
Resources can mean memory, as in the vector example, but it can also correspond to other things like a file handle or a lock. This is commonly referred to as Resource Acquisition Is Initialization (RAII).

convince a programmer that this resource is indeed reclaimed?

You can never convince someone who truly doesn't want to believe ^_^. However, you can implement Drop yourself to see when an item is being dropped:
struct NoisyDrop(u8);

impl Drop for NoisyDrop {
    fn drop(&mut self) {
        println!("Number {} being dropped", self.0);
    }
}

fn main() {
    println!("step 1");
    let mut nd = NoisyDrop(1);
    println!("step 2");
    nd = NoisyDrop(2);
    println!("step 3");
}

This will have the output
step 1
step 2
Number 1 being dropped
step 3
Number 2 being dropped

You can see that the first variable is dropped when its binding is replaced as there's no longer any way to get to the NoisyDrop(1) value. The second variable is dropped when it goes out of scope due to the method ending.

ownership semantics and lifetimes

Consider this example:
fn main() {
    let mut v = vec![1];
    v = vec![2];
}

Conceptually, it could be written as
fn main() {
    {
        let v = vec![1];
    }
    {
        v = vec![2];
    }
}

And this example
fn main() {
    let v1 = vec![1];
    let v2 = vec![2];
}

Could be rewritten as
fn main() {
    {
        let v1 = vec![1];
        {
            let v2 = vec![2];
        }
    }
}

These rewritings show the lifetime of each variable. Whenever you call a method with a generic lifetime parameter, the lifetime of the block will be the concrete value that gets substituted for the 'a generic.


text:
Q: Riemann-Lebesgue Integrable Show that there is no riemann integrable function $f$ on $[0,1]$ such that $f=\chi_{C}$ a.e. (almost everywhere), where $C$ is the fat cantor set.
Proof:
Would it suffice to show that $\chi_C$ is not riemann integrable??? Or am I missing something? Any suggestions?
Attempt:
Let $x$ be an element of $C$ then since $C$ contains
no intervals if we define $C_n = (x-\frac{1}{n}, x+\frac{1}{n})$ then there exists some
$x_n$ in $C_n$ such that $x_n\neq x$ and $x_n\not\in C$. Then $\forall \delta>0,\exists n$ such that $\delta>\frac{1}{n}.$ So then $$\left|x_n-x\right|<\frac{1}{n}<\delta.$$ But, if we take $\epsilon=1/2$ we get $$|f(x_n)-f(x)|=1>\epsilon$$ so $f$ is discontinuous at every $x\in C$, thus it cannot be Riemann integrable.
Would this work??

A: A Riemann integrable function has the property that its set of discontinuities has Lebesgue measure zero.  By contrast, the fat Cantor set is nowhere dense and of positive measure, so its indicator function has the property that in a neighborhood of every point of the fat Cantor set, the function takes on values of 1 and 0.  In particular the fat Cantor set is contained in the set of discontinuities of $\chi_C$.
Changing the values on any measure zero subset will not change the size of the set of discontinuities in this case. This follows from the fact that, up to removing a set of measure zero, $C$ will still be contained in the discontinuities set (it matters that $C$ is nowhere dense for this part). To see this, let $f = \chi_C$ $a.e.$ and let $M$ be the Lebesgue measure zero set on which we have changed the value of the function. Take $x \in C\cap M^c$ and observe that since $C$ is nowhere dense and since $M$ cannot contain an interval, there is a point of $C^c\cap M^c$ in any neighborhood of $x$ and so $x$ is a discontinuity point of $f$.  But $\mu(C \cap M^c) = \mu(C)$ so $f$ cannot be Riemann integrable.

A: Yes it would suffice to show $\chi_C$ is not riemann integrable. Then proceed by contradiction.


text:
Q: Finding Potential Primary Key In Tables I have tables(more than 100) that are missing primary keys. Actually, these are legacy tables. Now as per some replication requirements, we need to add primary key on each of these tables. Is there any way to find out possible primary keys on a table (ready to purchase a commercial product)?

A: You need to define the criteria for what constitutes a "possible primary key". When you have done that, you/we can search for (for instance sp_special_columns) or produce a script that uses that criteria. Such criteria could be:

*

*A unique index on the column(s) (possibly created using a unique constraint).

*The table has a column having the IDENTITY property.

*A column of the uniqueidentifier data type (but that could very well also be a foreign key).

*A column or set of columns which in the data has no duplicates.

For 3 and 4, you are gambling, since having no duplicates today is not guarantee that there should be duplicates tomorrow.
In general, there is a risk messing about in a database unless you own the database. Say that you slap on an identity column on each table, make it the PK, just so you can use replication. Now, there might be some code that does SELECT * and breaks down because it now gets this additional column that you added.


text:
Q: get IP address of local machine on c++ I want to retrieve IP address of my computer (same as I get on http://www.whatsmyip.org/)
I have a win32 project.
This is the code that I am using, as I didnt find any tutorial on this, I could get following info, but not the IP address which I saw for my computer on the whatsmyip.org :(
The IP I got on whatsmyip.org starts with 116.x.x.x

A: Your code gets adapter addresses, which are local. If you want your Internet address, you need to use the Internet, not your local network. You need to replicate the functionality of asking an external site what IP it sees you connecting from. See here for some suggestions for how to do that.
Retrieving http://icanhazip.com will do it. You can use whatever HTTP library you like.

A: The IP which assigned to your machine is not necessarily the IP that you see outside of your local network (e.g. in whatsmyip.org).
Your machine is not directly connected to the Internet with a valid and static IP. Maybe you are behind a NAT. So you can not determine your valid IP over Internet by listing your local assigned IPs in many situations.
To findout what IP address you have in Internet, you can do two ways. Ask from someone over Internet (for example, using whatsmyip.org). Or, query your local network recursivly (which is not easy task)


text:
Q: Overriding magento Models Hi i am trying to override magento admin model file
the file location is : core/Mage/Catalog/Model/Product/Type.php
i am trying to show only simple product when creating a new product but it is not working.
directory stretcher and file is given as below
local->Divum->Catalog->etc->config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Divum_Catalog>
           <version>0.1.0</version>
        </Divum_Catalog>
        <global>
            <models>
            <catalog>
                    <rewrite>
                    <product_type>Divum_Catalog_Model_Product_Type</product_type>
                </rewrite>
                </catalog>
            </models>
        </global>
    </modules>
</config>

local->Divum->Catalog->Model->Product->Type.php
class Divum_Catalog_Model_Product_Type
{
const TYPE_SIMPLE       = 'simple';
const TYPE_BUNDLE       = 'bundle';
const TYPE_CONFIGURABLE = 'configurable';
const TYPE_GROUPED      = 'grouped';
const TYPE_VIRTUAL      = 'virtual';

const DEFAULT_TYPE      = 'simple';
const DEFAULT_TYPE_MODEL    = 'catalog/product_type_simple';
const DEFAULT_PRICE_MODEL   = 'catalog/product_type_price';
static protected $_types;
static protected $_compositeTypes;
static protected $_priceModels;
static protected $_typesPriority;
public static function factory($product, $singleton = false)
{
    $types = self::getTypes();
    $typeId = $product->getTypeId();

    if (!empty($types[$typeId]['model'])) {
        $typeModelName = $types[$typeId]['model'];
    } else {
        $typeModelName = self::DEFAULT_TYPE_MODEL;
        $typeId = self::DEFAULT_TYPE;
    }

    if ($singleton === true) {
        $typeModel = Mage::getSingleton($typeModelName);
    }
    else {
        $typeModel = Mage::getModel($typeModelName);
        $typeModel->setProduct($product);
    }
    $typeModel->setConfig($types[$typeId]);
    return $typeModel;
}
public static function priceFactory($productType)
{
    if (isset(self::$_priceModels[$productType])) {
        return self::$_priceModels[$productType];
    }

    $types = self::getTypes();

    if (!empty($types[$productType]['price_model'])) {
        $priceModelName = $types[$productType]['price_model'];
    } else {
        $priceModelName = self::DEFAULT_PRICE_MODEL;
    }

    self::$_priceModels[$productType] = Mage::getModel($priceModelName);
    return self::$_priceModels[$productType];
}
static public function getOptionArray()
{
    $options = array();
    foreach(self::getTypes() as $typeId=>$type) {
         if($typeId == 'simple'):
            $options[$typeId] = Mage::helper('catalog')->__($type['label']);
        endif;
    }

    return $options;
}
static public function getAllOption()
{
    $options = self::getOptionArray();
    array_unshift($options, array('value'=>'', 'label'=>''));
    return $options;
}
static public function getAllOptions()
{
    $res = array();
    $res[] = array('value'=>'', 'label'=>'');
    foreach (self::getOptionArray() as $index => $value) {
        $res[] = array(
           'value' => $index,
           'label' => $value
        );
    }
    return $res;
}
static public function getOptions()
{
    $res = array();
    foreach (self::getOptionArray() as $index => $value) {
        $res[] = array(
           'value' => $index,
           'label' => $value
        );
    }
    return $res;
}
static public function getOptionText($optionId)
{
    $options = self::getOptionArray();
    return isset($options[$optionId]) ? $options[$optionId] : null;
}
static public function getTypes()
{
    if (is_null(self::$_types)) {
        $productTypes = Mage::getConfig()->getNode('global/catalog/product/type')->asArray();
        foreach ($productTypes as $productKey => $productConfig) {
            $moduleName = 'catalog';
            if (isset($productConfig['@']['module'])) {
                $moduleName = $productConfig['@']['module'];
            }
            $translatedLabel = Mage::helper($moduleName)->__($productConfig['label']);
            $productTypes[$productKey]['label'] = $translatedLabel;
        }
        self::$_types = $productTypes;
    }

    return self::$_types;
}
static public function getCompositeTypes()
{
    if (is_null(self::$_compositeTypes)) {
        self::$_compositeTypes = array();
        $types = self::getTypes();
        foreach ($types as $typeId=>$typeInfo) {
            if (array_key_exists('composite', $typeInfo) && $typeInfo['composite']) {
                self::$_compositeTypes[] = $typeId;
            }
        }
    }
    return self::$_compositeTypes;
}
public static function getTypesByPriority()
{
    if (is_null(self::$_typesPriority)) {
        self::$_typesPriority = array();
        $a = array();
        $b = array();

        $types = self::getTypes();
        foreach ($types as $typeId => $typeInfo) {
            $priority = isset($typeInfo['index_priority']) ? abs(intval($typeInfo['index_priority'])) : 0;
            if (!empty($typeInfo['composite'])) {
                $b[$typeId] = $priority;
            } else {
                $a[$typeId] = $priority;
            }
        }

        asort($a, SORT_NUMERIC);
        asort($b, SORT_NUMERIC);

        foreach (array_keys($a) as $typeId) {
            self::$_typesPriority[$typeId] = $types[$typeId];
        }
        foreach (array_keys($b) as $typeId) {
            self::$_typesPriority[$typeId] = $types[$typeId];
        }
    }
    return self::$_typesPriority;
}
}

When i put the same code in core file which is located in
"core/Mage/Catalog/Model/Product/Type.php" it is working but it is not working in the override file.
I think i made a mistake in config file but i don't know what is the problem. please help me to solve this.

A: Try this, you had wrapped it all in the modules tags.
<?xml version="1.0"?>
<config>
    <modules>
        <Divum_Catalog>
            <version>0.1.0</version>
        </Divum_Catalog>
    </modules>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <product_type>Divum_Catalog_Model_Product_Type</product_type>
                </rewrite>
            </catalog>
        </models>
    </global>
</config>


text:
Q: .NET REST PUT CURL API ok I have this curl statement that works
curl -i -u user:pass -H "Accept: application/json" -X POST -d "type=menu&title=HelloWorld" http://127.0.0.1:8000/api/pages/

but I cant get it to work in .net.
I have tried restsharp
   private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            var client = new RestClient("http://127.0.0.1:8000/api/pages/");
            client.Authenticator = new HttpBasicAuthenticator("user", "pass");

            var request = new RestRequest(Method.POST);
            request.AddHeader("Accept", "application/json");

            // add parameters for all properties on an object
            request.AddParameter("type", "menu");
            request.AddParameter("title", "HelloWorld");

            // execute the request
            RestResponse response = client.Execute(request);
            var content = response.Content; // raw content as string
            richTextBox1.Text = content.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

and straight .net
 Private Sub ButtonPost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPost.Click

    address = New Uri("http://127.0.0.1:8000/api/pages")

    ' Create the web request
    request = DirectCast(WebRequest.Create(address), HttpWebRequest)

    ' Set type to POST
    request.Method = "POST"
    request.ContentType = "Accept: application/json"

    ' Add authentication to request
    request.Credentials = New NetworkCredential("user", "pass")

    Dim str As String = "type=men&title=HelloWorld"
    ' Create a byte array of the data we want to send
    byteData = UTF8Encoding.UTF8.GetBytes(str)

    ' Set the content length in the request headers
    request.ContentLength = byteData.Length

    ' Write data
    Try
        postStream = request.GetRequestStream()
        postStream.Write(byteData, 0, byteData.Length)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        If Not postStream Is Nothing Then postStream.Close()
    End Try

    Try
        ' Get response
        response = DirectCast(request.GetResponse(), HttpWebResponse)

        ' Get the response stream into a reader
        reader = New StreamReader(response.GetResponseStream())

        ' Console application output
        RichTextBox1.Text = reader.ReadToEnd()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        If Not response Is Nothing Then response.Close()
    End Try

End Sub


text:
Q: Google app engine HTTP error 500 I just installed Google app engine for Python 2.7 and I wrote some code for test. Just a simple HTML form. Here is the code:
import webapp2

form = """
<form method="post">
    What is your birthday?

     Month
        <input type="text" name="month">

     Day
        <input type="text" name="day">

     Year
        <input type="text" name="year">

    <input type="submit">
</form>
"""

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.out.write(form)

    def post(self):
        self.response.out.write("Succes!")

app = webapp2.WSGIApplication([
     ('/', MainPage),
], debug=True)

And then I tried to write a separate procedure that writes out my form, like so:
import webapp2

form = """
<form method="post">
    What is your birthday?

     Month
        <input type="text" name="month">

     Day
        <input type="text" name="day">

     Year
        <input type="text" name="year">

    <input type="submit">
</form>
"""

class MainPage(webapp2.RequestHandler):
    def write_form(self):
        self.response.out.write(form)

    def get(self):
        self.write_form()

    def post(self):
        self.response.out.write("Succes!")

app = webapp2.WSGIApplication([
     ('/', MainPage),
], debug=True)

Well, the thing is that the first code is working fine, but the second one is returning the HTTP error 500. I tried this out from a course on Udacity and I simply copied the code from there. I really don't know why it's not working.
PS. I see this message in terminal (Linux): "IndentationError: unindent does not match any outer indentation level
INFO     2016-08-29 12:17:37,155 module.py:788] default: "GET / HTTP/1.1" 500 -"
Later Edit: I solved this by simply writing the "write_form" procedure after the "get" procedure inside the MainPage class.

A: You have probably mixed up tabs and spaces. See this answer for more information and hints on how to fix it: https://stackoverflow.com/a/3920674/3771575


text:
Q: How exactly do vinyl "static" clings work? My son asked me this question today, and for the life of me, I can't come up with a good answer that even convinces myself.
Vinyl "static" clings are those decorative pieces of vinyl that you can stick onto the inside surface of car windshields, windows etc. They require no adhesive (nor are they made with adhesive on their surface).
One website states they work by static electricity, which sounds plausible until you come upon another website that asks the question: if they worked by static, how is it that the vinyl can easily be folded over itself and get stuck in that position? Surely the charges on that surface of the vinyl are like and should repel? Also, these vinyl clings will stick just fine to conductive metal, which shouldn't happen if the effect is mediated by static electricity.
The problem is that no site actually seems to provide an explanation that satisfies us both. Some talk about the smooth vinyl causing "cohesive forces", and others talk about imagining thousands of "suction cups" on the surface, but clearly neither of these are adequate or precise enough to explain what's going on.
One of the sites likened the vinyl clings to plastic cling wrap, which also sticks to itself, so I guess the same mechanism also causes adhesion in this situation. Similar situations that might be explained by the same phenomenon include the way smooth glass tiles tend to stick together, but I don't know if these are all governed by the same principle.
Could someone please tell me what exactly is causing the stickiness in these instances? - vinyl on glass, plastic cling wrap on glass and other things and smooth glass on smooth glass.
At a microscopic level, I believe some form of electrical force is definitely at play. But it doesn't seem to behave like I have come to expect of "static electricity" on the macroscopic scale. Please help. Thank you.

A: Finding "how it works" pages turns out to be rather difficult indeed.  Here is one explanation from a college physics dept Q&A page.

"Surface-to-surface adhesion" is just a fancy name for things sticking
together, so it doesn't tell you much beyond what you were asking. The
main mechanism is probably vanderWaals forces between the surfaces.
These are the sort of forces that tend to make all sorts of different
materials stick to themselves and each other. They involve the
electric charges in the material doing a sort of coordinated dance, so
that even though both pieces are neutral the positives in one tend to
be close to the negatives in the other at any time. This generic
mechanism is sure to be present.


text:
Q: A question about oscilloscope and common mode noise To ask this question I needed to simulate two circuits as an example. Imagine we want to measure the voltage across a device output. Call the differential voltage across its terminals Vd. And imagine we couple a usual scope to its terminals to observe the voltage. Call AGND is the scope's own ground. And call the usual triangle reference symbol as the earth ground for this example.
Now on the left side circuit, if the scope is earth grounded and if there is a common mode interference as Vcm the simulation shows the green plot as the difference between Scope and AGND nodes. But if I cut the earth connection of the scope as on the right circuit the simulation shows the blue plot as the difference between Scope1 and AGND1 nodes.

In the simulation above, cutting the earth is hiding the common mode interference information. Is that what happens in reality? Can this be a way to check whether the noise is common mode or differential in nature?

A:
Is that what happens in reality?

Try this instead (more like reality): -

You might want to try this at a higher frequency to really get a feel for high frequency interference too.
Note - I'm unsure why you are using 10 milli ohm resistors.

A: You will see the common mode noise if your scope has even the most passing connection to earth ground.  By connecting the scope ground to AGND1, you're overriding that (presumably) high impedance to earth ground, forcing the scope to use AGND1 as a reference.
If your scope's earth ground is low impedance, your'e just shorting Vcm.


text:
Q: jQuery Events get skipped I built a slideshow-menu (using Slide JS - http://www.slidesjs.com/ ) and added a hover-event, so images will already switch when moving the mouse over the menu point. Additionally, when moving out of the whole block, there's a mouseleave event, which sets the image and menu point back to the first one.
Now when I quickly switch between menu points (hover event) and then leave the whole block (mouseleave), it usually skips the mouseleave event (- or it never reaches it because the hover events (including a fade effect) take up too long).
Is there a way to thoroughly work off each event (or at least the last one in a row - e.g. mouseleave or last hover)?
Maybe an image of the website layout helps?

Red: Hover-Event (changes green content)
Blue: Mouseleave-Event (green goes back to default)

A: If the fade effect is the culprit, then try adding a stop(true, true) function before your fade effect.
$(slideshow-menu-selector).on('mouseleave', function(){
    // Reset code here
    $(element-selector).stop(true, true).fadeOut();
})

This is just a sample code, based on your question. If you can put up a Fiddle, it would help a lot!


text:
Q: Project Fails After NUGET Packages Update Updating dependencies using NUGET creates errors in application.
Creating a new project from Visual Studio Community 2017 for C# and Web Forms with a master page. After successfully running the website inside Visual Studio, I update the project and find 24 nuget packages needs updating.
So OK, Update the packages. All 24 and restart Visual Studio as instructed.
Reload the project and run, I get a compilation error and the project fails to run or complete loading.
This compilation error is new, previously I lost my connection to twitter/bootstrap and jquery files. I fixed those by removing the references in the script and bundle manager.
Now it just kills the fresh application template. There is no programming, just the basic template fails to load. And when it did blew up most of the bootstrap and jquery routines and destroyed the navigation menu layout.
Here is the Compilation error:

C:\Program Files (x86)\IIS > Express>C:\Users\michaelw.DEESIGN\Documents\Visual Studio > 2017\Projects\WebSite2\WebSite2\bin\roslyn\csc.exe /t:library > /utf8output /nostdlib+ > /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.Web.PageInspector.Loader\v4.0_1.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Web.PageInspector.Loader.dll" /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\c9841997\00b21bea_1de6d301\AspNet.ScriptManager.bootstrap.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\2c48699e\0011ed8c_808dce01\Microsoft.AspNet.FriendlyUrls.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\ca88605b\00cb5b40_b9c3d301\Newtonsoft.Json.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activities.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\0f5ed648\00720de7_d9cccd01\Owin.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\ed6e8f5b\008a9d1a_f395d301\AspNet.ScriptManager.jQuery.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\c5b71904\002397f9_6c18cf01\WebGrease.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\7cb43f83\00d0a76d_64aece01\Antlr3.Runtime.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\6a7a0b6e\001e1df5_ebdbd301\Microsoft.AspNet.Identity.Owin.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\3cbaac25\00f1ebf3_ebdbd301\Microsoft.AspNet.Identity.Core.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\de563d64\0097c37f_224cd301\EntityFramework.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.Web.Infrastructure\v4.0_1.0.0.0__31bf3856ad364e35\Microsoft.Web.Infrastructure.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\713924f7\00c4f480_224cd301\EntityFramework.SqlServer.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\e60bcda8\00939497_11a5d301\Microsoft.Owin.Security.Twitter.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\4fffbea8\00dfcf92_11a5d301\Microsoft.Owin.Security.Google.dll" > /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Net.Http.WebRequest\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Net.Http.WebRequest.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Extensions.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\fb841881\00dfcf92_11a5d301\Microsoft.Owin.Security.Facebook.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\442f60b0\00583c8f_11a5d301\Microsoft.Owin.Security.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\56334a44\0052dd57_a7e7ce01\System.Web.Providers.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\3f088bba\00393295_11a5d301\Microsoft.Owin.Security.MicrosoftAccount.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Deployment\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Deployment.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\System.ServiceModel.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\e1ab0c9e\00e6fa3f_7827cf01\Microsoft.AspNet.Web.Optimization.WebForms.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\3b868cfc\00b29e91_11a5d301\Microsoft.Owin.Security.Cookies.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\e9625208\00e6fa3f_7827cf01\System.Web.Optimization.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\11064a60\00666396_11a5d301\Microsoft.Owin.Security.OAuth.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\a6149561\00fbad02_86f3d301\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\aa9c70b3\00fed98c_11a5d301\Microsoft.Owin.Host.SystemWeb.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_4.0.0.0__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\cb06e281\004a1588_11a5d301\Microsoft.Owin.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Net.Http\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Net.Http.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\3101006c\00d6d5b9_2dabce01\Microsoft.ScriptManager.MSAjax.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\4f6eecce\00b7cbbf_2dabce01\Microsoft.ScriptManager.WebForms.dll" > /R:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\assembly\dl3\d9915d1f\001e1df5_ebdbd301\Microsoft.AspNet.Identity.EntityFramework.dll" > /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll" > /out:"C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\App_Code.clskvtg9.dll" /D:DEBUG /debug+ > /optimize- /warnaserror- /w:4 /nowarn:1659;1699;1701;612;618 > /langversion:default /nowarn:1659;1699;1701 > "C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\App_Code.clskvtg9.0.cs" > "C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\App_Code.clskvtg9.1.cs" > "C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\App_Code.clskvtg9.2.cs" > "C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\App_Code.clskvtg9.3.cs" > "C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\App_Code.clskvtg9.4.cs" > "C:\Users\michaelw.DEESIGN\AppData\Local\Temp\Temporary ASP.NET > Files\vs\732bd14c\5c4cc4da\App_Code.clskvtg9.5.cs"

 All this from a basic template that was just "updated" in Nuget.
1) Can someone tell me what has gone wrong? And how do I fix it the right way.
1a) Can someone show me how bundles and scriptmanager is supposed to load jQuery and bootstrap?
2) Is this common for package updates to kill a project or break what was previously working?
3) Is there a way in the future for "updates" to behave correctly?
Thanks in advance for your input.

A:
1) Can someone tell me what has gone wrong? And how do I fix it the right way.

You should use NuGet Package Manager UI to update those nuget packages, the Updates tab displays packages with higher versions. You could check the checkbox Select all packages, then click update button to update all packages.

In this way, NuGet will check for dependency compatibility, if there is any issue during updating, NuGet will revert the package updates. And you can check the logs in the output window to find why the update failed. Alternatively, we can also update those packages one by one, check the log for the compatibility issues.

2) Is this common for package updates to kill a project or break what
  was previously working?

No, but it is common for package updates to break what was previously working. That because each package has its own dependencies and other restrictions. When we update one of the package, NuGet will update its dependencies, but if other package depends on the old dependencie, then it will break what was previously working. But just as I said above, NuGet will give the warning/error info in the output window when you update the package in the Visual Studio in the most case and NuGet will revert the package updates.

3) Is there a way in the future for "updates" to behave correctly?

If above two questions resolve your question, this question does not need to be answered. If above not resolve your question, please give me some steps how did update the nuget packages, I will keep follow.
Hope this helps.


text:
Q: Detach intermediate module in Pytorch with regard to part of the loss Let's say I have the following forward pass that results in two separate losses:
forward(self, input)
    x = self.layer1(input)

    y = self.layer2(x)

    z = self.layer3(y)

    return y, z

We then calculate loss1(y) and loss2(z). Then we can optimize loss = loss1 + loss2 with a single optimizer.
But I have two caveats: (1) I want d_loss1 to be calculated with regards to layer2 only (without layer1), and (2) I want d_loss2 to be calculated with regards to layer3 and layer1 - without layer2.
Essentially, I want to train non-consecutive parts of the network separately with separate losses.
I believe I can solve (1) by introducing a stop-gradient in the input to layer2 like so:
forward(self, input)
    x = self.layer1(input)

    y = self.layer2(x)
    y_stop_gradient = self.layer2(Variable(x.data))

    z = self.layer3(y)

    return y_stop_gradient, z

But how can I solve (2)?
In other words, I want loss2's gradients to "skip" layer2 while keeping layer2 trainable with regards to loss1.

A: While waiting for a proper answer I found one of my own, though it's a terribly inefficient one and I'm hoping for someone else to come up with a better solution.
My solution looks like this:
import copy
forward(self, input)
    x = self.layer1(input)

    y = copy.deepcopy(self.layer2)(x)  # create a full copy of the layer
    y_stop_gradient = self.layer2(Variable(x.data))

    z = self.layer3(y)

    return y_stop_gradient, z

This solution is inefficient because (1) I think deep copy is overkill for what I'm trying to do and too expensive and (2) the gradients for layer2 relative to z are still calculated, they're just unused.


text:
Q: Excel Lookup Help I would like to know how to perform the following lookup in Excel (Version = 2007) ...
The first sheet (sheet1) has the following 2 columns
UserID                            CreationDate
0004F9B41DEB7BED80257808003A2D45    29/12/2010 10:36
0074ACD71905583A80257730001EB114    28/01/2011 10:21
00799CCE1BEA0ACB802577AE00588A88    08/01/2011 15:36
009AD15E65AAB6008025783D00746A8B    20/02/2011 21:18

The second sheet (sheet2) has the following 2 columns
UserID                              BookingDate
003561E36C682DBE802576C1004A5962    13/01/2011 10:12
003561E36C682DBE802576C1004A5962    13/01/2011 07:51
0051D119847371F1802576210035B302    15/01/2011 12:28
005FF7CD6C0416E38025760D006B81C7    22/02/2011 12:07
005FF7CD6C0416E38025760D006B81C7    22/02/2011 09:33
005FF7CD6C0416E38025760D006B81C7    22/02/2011 09:28

What I need to do is take a userID from the first sheet and find out if its present on the second sheet BUT I need to only find ones where the BookingDate on sheet2 is after the CreationDate on sheet1. I don't need any information / columns from the second sheet - just a TRUE would be perfect.
Thanks !

A: Formula for cell Sheet1!C2, copy down as far as required
=IF(ISNA(MATCH(A2,Sheet2!A:A,0)),FALSE,IF(VLOOKUP(A2,Sheet2!A:B,2,0)>B2,TRUE,FALSE))


text:
Q: Comparing "better" and "best"
Possible Duplicate:
Use of the superlative when only two items are present

Is the word better used in comparing two things, or do you use the word best?
Example used in a conversation:

A: Is there any way to get over the anxiety?
B: Drink a shit ton of alcohol or caffeine.
A: I like the first suggestion better/best.

Are they both correct to say?

A: Usually, when there are two options, one of them is better than the other. If there are multiple options, you can choose the best among them. I think the underlying reason for this is that when there are only two options, the better of them is also the best.

Who's better at math: Beth or Seth? Seth's better. He's the best in class.

I think this is true for all adjectives. Imagine there are two boxes. Someone asks you which one you want. You say:

I want the larger one.

On the other hand, if there were 10 boxes, you could say

I want the largest one.

Although technically you could say I want the largest one in the first scenario, don't be surprised if the other person starts looking around to see if there aren't any other boxes apart from these two.

A: When you use best, you say it in absolute terms. While better is used in relative terms.
When something is best, its position is uncontested. While better suggests 'compared to others, this is one is good'

A: "Better" is a comparative, i.e. it is a relationship between two things. "Best" is a superlative, i.e. it states the position of this one thing compared to all the other things under discussion.
If I have three choices, A, B, and C, all the following statements could be true: A is better than B. B is better than C. A is better than C. A is the best. If one thing is better than another, others could be better still. But if one thing is the best, than nothing can be better.
Note: The above assumes that "better" is a rating on some sort of scale. Of course A might be better than B in some contexts but not as good in others, for example an orange is better than a flashlight if I'm hungry but the flashlight is better if I'm stumbling in the dark. And one can imagine relationships like rock/paper/scissors where there is no best, just pairs of non-transitive relationships.


text:
Q: Identifying that a variable is a new-style class in Python? I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out.
import types

class oldclass:
  pass

def test():
  o = oldclass()
  if type(o) is types.InstanceType:
    print 'Is old-style'
  else:
    print 'Is NOT old-style'

But I haven't been able to find anything that works for new-style classes. I found this question, but the proposed solutions don't seem to work as expected, because simple values as are identified as classes.
import inspect

def newclass(object):
  pass

def test():
  n = newclass()
  if inspect.isclass(n):
    print 'Is class'
  else:
    print 'Is NOT class'
  if inspect.isclass(type(n)):
    print 'Is class'
  else:
    print 'Is NOT class'
  if inspect.isclass(type(1)):
    print 'Is class'
  else:
    print 'Is NOT class'
  if isinstance(n, object):
    print 'Is class'
  else:
    print 'Is NOT class'
  if isinstance(1, object):
    print 'Is class'
  else:
    print 'Is NOT class'

So is there anyway to do something like this? Or is everything in Python just a class and there's no way to get around that?

A: I think what you are asking is: "Can I test if a class was defined in Python code as a new-style class?".  Technically simple types such as int are new-style classes, but it is still possible to distinguish classes written in Python from the built-in types.
Here's something that works, although it's a bit of a hack:
def is_new_style(cls):
    return hasattr(cls, '__class__') \
           and \
           ('__dict__' in dir(cls) or hasattr(cls, '__slots__'))

class new_style(object):
    pass

class old_style():
    pass

print is_new_style(int)
print is_new_style(new_style)
print is_new_style(old_style)

Output from Python 2.6:
False
True
False

Here's a different way to do it:
def is_new_style(cls):
    return str(cls).startswith('<class ')

A: I believe this suffices:
def is_new_style_class(klass):
    return issubclass(klass, object)

def is_new_style_class_instance(instance):
    return issubclass(instance.__class__, object)

Typically, you only need the is_new_style_class function for your purposes. Everything not a class will throw a TypeError, so you might want to update it to:
def is_new_style_class(klass):
    try:
        return issubclass(klass, object)
    except TypeError:
        return False

Examples:
>>> class New(object): pass
...
>>> is_new_style_class(New)
True
>>> class Old: pass
...
>>> is_new_style_class(Old)
False
>>> is_new_style_class(1)
False
>>> is_new_style_class(int)
True

int, being a type, is by definition a new-style class (see Unifying types and classes in Python 2.2 ), or —if you prefer— new-style classes are by definition types.

A: It's not that "everything is a class": what you're bumping into is that "everything is an object" (that is, every (new-style) thing descends from "object").
But new-style classes are a "type" themselves (actually, the were introduced to bring classes and types together). So you can try checking for
import types

type(o) == types.TypeType

Does that solve your problem?

A: Checking for old-style classes is really easy. Just check type(cls) is types.ClassType. Checking for new-style classes is also easy, isinstance(cls, type). Note that the built-in types are also new-style classes.
There seems to be no trivial way to distinguish built-ins from classes written in Python. New-style classes with __slots__ also don't have __dict__, just like int or str. Checking if str(cls) matches the expected pattern fails if the classes metaclass overrides the __str__ method.  Some other ways that also don't work:

*

*cls.__module__ == '__builtin__' (you can reassign __module__ on classes)

*not any(value is cls for value in vars(__builtins__).values()) (you can add stuff to the __builtin__ module).

The fact that unification of builtin and userdefined types is so good that distinguishing them is non-trivial problem should imply to you the underlying point. You really shouldn't have to distinguish between them. It doesn't matter what the object is if it implements the expected protocol.


text:
Q: How to pass headers when using SWR axios and nextjs I am attempting to switch my api usage to use SWR as it provides much more customisation options that I could very well benefit from. How ever the api GET request need to pass through 2 headers 'Authorization':Bearer ${session.accessToken}  and 'Client-Id': ${process.env.TWITCH_CLIENT_ID}  And after doing some research I found a couple of ways on how to do this but they are not working. The code below is what I have but when the page attempts to render it shows the screenshot bellow
How do I fix this or better yet can anyone show the proper way to send headers while using swr?
import axios from "axios";
import Link from "next/link";
import {
  VStack,
  Heading,
  Divider,
  Text,
  Box,
  Badge,
  Center,
} from "@chakra-ui/react";
import { useSession } from "next-auth/react"
import useSWR from 'swr'

const fetcher = (url, token) => {
const { data: session, status } = useSession()
    axios
      .get(url, {
        headers: {
          Authorization: `Bearer ${session.accessToken}` + token }})
      .then((res) => res.data);
        }

function Dash () {
  const { data, error } = useSWR([` https://api.twitch.tv/helix/streams/key?broadcaster_id=630124067`, auth.token],fetcher)

  if(error) return
Error {data.error}

  if(!data) return
loading...

  return (
    <VStack>
      <Text>{data.data.stream_key}</Text>
    </VStack>
  )

}

export default Dash


text:
Q: how to change jquery script for responsive iframe I have a Blogger website : http://ildesign-blogger-demo-1.blogspot.fr
I have two problems with a script which would be very useful but i seems i did not understand its function. What i want : it should resize the youtube and vimeo iframes only in the .post-body.
The problems :

*

*On the article page (type item page) it resizes all video iframes which are not only in the .post-body but on the page, for example in the footer. The page : http://ildesign-blogger-demo-1.blogspot.fr/2014/04/1st-article.html

*On the list of the archive type of pages (archives by date), the video is not resized in the .post-body (but it should be), in the footer neither (that is ok). The page : http://ildesign-blogger-demo-1.blogspot.fr/2014_04_01_archive.html
Summary :
So, it seems that my script works only on one type of page (item) in spite of the fact that i inserted the script just before the </body> tag and not in if conditions.
Also it seems that it influence (it is valide) for all videos on the page, not for only the videos within the .post-body (what i wanted).
Can someone tell me how to re-write the script that it does what i would like ?
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {

    // Find all YouTube and Vimeo videos, all types can be added with iframe integration
    var $allVideos = $('iframe[src^="http://player.vimeo.com"], iframe[src^="//www.youtube.com"], object, embed'), $fluidEl = $('.post-body');

    // Figure out and save aspect ratio for each video
    $allVideos.each(function() {

        $(this)
            .attr('data-aspectRatio', this.height / this.width)
            .removeAttr('height')
            .removeAttr('width');

    });

    // When the window is resized
    $(window).resize(function() {

        var newWidth = $fluidEl.width();

        // Resize all videos according to their own aspect ratio
        $allVideos.each(function() {

            var $el = $(this);
            $el
                .width(newWidth)
                .height(newWidth * $el.attr('data-aspectRatio'));

        });

    // Kick off one resize to fix all videos on page load
    }).resize();

});
//]]>
</script>

A: Well, i think that the script i had is not well-built because it effected the videos and resized to the size of an element of the website... if you indicated 'body', it resized the videos for the body width, if post body, then all of them have been resized to post body width... it is not what i was looking for...
If you are looking for the same thing i was looking for : resize your youtube and vimeo video iframe to its parent div width for 100%, this is a good script which works also in Blogger (source : http://toddmotto.com/fluid-and-responsive-youtube-and-vimeo-videos-with-fluidvids-js/) :
(function ( window, document, undefined ) {

  /*
   * Grab all iframes on the page or return
   */
  var iframes = document.getElementsByTagName( 'iframe' );

  /*
   * Loop through the iframes array
   */
  for ( var i = 0; i < iframes.length; i++ ) {

    var iframe = iframes[i],

    /*
       * RegExp, extend this if you need more players
       */
    players = /www.youtube.com|player.vimeo.com/;

    /*
     * If the RegExp pattern exists within the current iframe
     */
    if ( iframe.src.search( players ) > 0 ) {

      /*
       * Calculate the video ratio based on the iframe's w/h dimensions
       */
      var videoRatio        = ( iframe.height / iframe.width ) * 100;

      /*
       * Replace the iframe's dimensions and position
       * the iframe absolute, this is the trick to emulate
       * the video ratio
       */
      iframe.style.position = 'absolute';
      iframe.style.top      = '0';
      iframe.style.left     = '0';
      iframe.width          = '100%';
      iframe.height         = '100%';

      /*
       * Wrap the iframe in a new <div> which uses a
       * dynamically fetched padding-top property based
       * on the video's w/h dimensions
       */
      var wrap              = document.createElement( 'div' );
      wrap.className        = 'fluid-vids';
      wrap.style.width      = '100%';
      wrap.style.position   = 'relative';
      wrap.style.paddingTop = videoRatio + '%';

      /*
       * Add the iframe inside our newly created <div>
       */
      var iframeParent      = iframe.parentNode;
      iframeParent.insertBefore( wrap, iframe );
      wrap.appendChild( iframe );

    }

  }

})( window, document );

Important : you must insert the iframe with its original width and height in pixel (width="560" height="315") that the script could calculate the aspect ration !


text:
Q: Why is my merge sort not working? It compiles fine, but when it runs, it adds random high numbers to the list, as well as duplicates of existing numbers. I've had a couple of people look over this, and none of them can figure it out.
void mergeSort(int list[], int length) {
    recMergeSort(list, 0, length - 1);
}

void recMergeSort(int list[], int first, int last) {

    if (first < last) {
        int mid = (first + last) / 2;
        recMergeSort(list, first, mid);
        recMergeSort(list, mid + 1, last);
        merge(list, first, last, mid);
    }
}

void merge(int list[], int first, int last, int mid) {

    int arraySize = last - first + 1;
    int* tempList = new int[arraySize];
    int beginPart1 = first;
    int endPart1 = mid;
    int beginPart2 = mid + 1;
    int endPart2 = last;

    int index = beginPart1;

    while (beginPart1 <= endPart1 && beginPart2 <= endPart2) {
        if (list[beginPart1] < list[beginPart2]) {
            tempList[index] = list[beginPart1];
            beginPart1++;
        }
        else {
            tempList[index] = list[beginPart2];
            beginPart2++;
        }
        index++;
    }

    while (beginPart1 <= endPart1) {
        tempList[index] = list[beginPart1];
        index++;
        beginPart1++;
    }

    while (beginPart2 <= endPart2) {
        tempList[index] = list[beginPart2];
        index++;
        beginPart2++;
    }

    for (int i = first; i <= last; i++) {
        list[i] = tempList[i - first];
    }

    delete[] tempList;
}

A: In function merge(), you're incorrectly calculating the index variable:
Assuming begin = 10, mid = 14, end = 19 (for a total array size of 0 .. 19, and you're recMergeSort()ing the higher half), your index = 10, but the tempList array is indexed 0..9 (because arraySize = last - first + 1 == 10).
So you're overflowing your tempList array, and when you "merge", you get data corruption.
Fix your index variable to be 0-based (rather than beginPart1 based).

A: I think problem is here:
int index = beginPart1;

It should be
int index = 0;

A: If I run this in C# I get an IndexOutOfRangeException on the following line:
                    tempList[index] = list[beginPart1];

I reckon if you trace it through you are probably running off the end of a buffer somewhere hence the random numbers.


text:
Q: correlation and covariance of two random variables I have two continuous random variable X and Y. In U- shape region we have  $P_{XY}(X,Y)=\frac{1}{12}$ in other regions we have $P_{XY}(X,Y)=0$.
How the correlation and covariance of these two variable behave?


text:
Q: c++ template partial specialization this might be question that someone asked before but i can't find it...
i have a class in a .hpp file :
class A{
    public:
        A(){//constructor}
        ~A(){//destructor}
        //some public methods and arguments

        template<typename Type>
            void func(Type t){//do something for numbers}

    private:
        //some private methods and arguments
}

The template method should work for int, double... but not for string. Thus in my .hpp file, I defined what func does for numbers and in my .cpp file I wrote :
template<>
void A::func(std::string t){ // do something in that case}

But when I use the function func with std::string, the program calls the methods for numbers... So I replaced the .hpp file by :
class A{
    public:
        A(){//constructor}
        ~A(){//destructor}
        //some public methods and arguments

        template<typename Type>
            void func(Type t){//do something for numbers}
        void func(std::string s);

    private:
        //some private methods and arguments
}

and my .cpp file became :
void A::func(std::string t){ // do something in that case}

and then everything works !
my question is, is this the correct way to do that ?

A: That's not a partial specialization (there are no template parameters left un-specialized) it's an explicit specialization.
Templates must be visible to the code that uses them, if you don't declare the specialization in the header file then code that tries to call A::func with a string will instantiate the primary template (the one for numbers) and use that, because they don't know the `string specialization even exists.
So you must (at least) declare the specialization in the header in order for it to be usable outsde the .cpp file:
template<>
void A::func(std::string t);

However your alternative using an overload is simpler and is perfectly acceptable. It works because the overload for string is declared in the header, so code that calls it knows which function to call.

A: Overloading is a good approach for many purposes. However, I suspect your original template approach could be made to work too if you add a specialization for const char * as well. That way, you could pass in string literals without it resolving to the numbers version.


text:
Q: Does the execute bit grant any security for a readable binary file? If a user of a UNIX system has permission to read (but not to write or execute) a binary file can't they just make an executable copy of it?
If a file is readable by a user that either

*

*owns at least one accessible directory (and can, therefore, set its permissions freely) or

*owns at least one accessible file (and can, therefore, set its permissions freely) or

*has access to at least one file that is writable and executable,

is there anything preventing this user from making an executable copy of the file they want to execute and then executing it?
Assuming the user satisfies neither (1) nor (2) nor (3), can they still somehow execute a binary file they can only read?

A: Yes. But they can't escalate their privileges in any way do to that. Most critically, they can't make use of the setuid bit.
What is more interesting is the converse, which is that a file can be executable but not readable. That creates a security difference, provided you're on a system that does not permit you to always read memory of processes you launch.


text:
Q: How to read SSM parameter value of type SecureString in AWS CDK Typescript? I am trying to retrieve SSM parameter value of type SecureString using below code in AWS CDK typescript(v2). SSM parameter is pre-existing and key value will be used to invoke an API.
    const key = SecretValue.unsafePlainText('/CodeBuild/key').unsafeUnwrap();

It doesn't resolve to its value as seen from the console. Instead it just shows name of the SSM parameter.
Thanks for your help.


text:
Q: SQL Help 'pivoting' a table in chunks My database table is such that each entry is listed in a new row for each chart. I want to 'pivot' and group by ID. Do I need to use a bunch of CASE WHEN statements or is this a succinct way of doing this?
Here's a simplified table:

Chart_ID
Rule
Action

A1
R1
Y

A1
R3
N

B4
R1
N

C1
R1
Y

C1
R2
N

C1
R3
Y

I'd like a table like this:

Chart_ID
R1
Action1
R2
Action2
R3
Action3
R4
Action4

A1
R1
Y

R3
N

B4
R1
N

C1
R1
Y
R2
N
R3
Y

A: You can use conditional aggregation:
select chart_id,
       max(case when rule = 'R1' then rule end) as r1,
       max(case when rule = 'R1' then action end) as action1,
       max(case when rule = 'R2' then rule end) as r2,
       max(case when rule = 'R2' then action end) as action2,
       max(case when rule = 'R3' then rule end) as r3,
       max(case when rule = 'R3' then action end) as action3,
       max(case when rule = 'R4' then rule end) as r4,
       max(case when rule = 'R4' then action end) as action4
from t
group by chart_id;

Note that the columns R1, R2, R3, and R4 are suspicious because they are redundant.  As you have defined the data, action1 is for rule 'R1'.


text:
Q: Will this be a valid base class for IDisposable IDisposable pattern is expensive to implement. I've counted 17 lines of code before even starting to actually dispose resources.
Eric Lippert recently wrote a blog post bringing up an interesting point: any time a finalizer runs, it is a bug. I think it make perfect sense. If the IDisposable pattern is always followed, Finalizer should always be suppressed. It will never have a chance to run. If we accept that finalizer run is a bug, then does it make sense to have a guideline to force developers to derive from the following abstract class and forbid directly implementing the IDisposable interface.
public abstract class AbstractDisaposableBase: IDisposable
{
    ~AbstractDisaposableBase()
    {
        ReportObjectLeak();
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected abstract void Dispose(bool disposing);

    [Conditional("DEBUG")]
    private void ReportObjectLeak()
    {
        //Debug.Assert(false, "leaked instance");
        //throw new Exception("leaked instance");
    }
}

The benefits are clear:

*

*Implementing dispose becomes easy and error free like below:

class MyClass1 : DisablableBase
{
    protected override void Dispose(bool disposing)
    {
        //dispose both managed and unmamaged resources as though disposing==true
    }
}

*Not disposed object got reported

*Disposable pattern is always followed
But, is there any problem with such a guideline?
One possible problem is that all disposable object will have a finalizer defined. But since the finalizer is always suppressed, there should not be any performance penalties.
What are your thoughts?

A:
does it make sense to have a guideline to force developers to derive from the following abstract class

No, solely for the reason that C# doesn't have multiple inheritance. Interfaces describe behavior, inheritance dictates "is-a". You'll thoroughly limit the object-oriented design of your classes if you enforce this rule.
For example you can't introduce base classes for business objects that are not disposable, where a derived class would be.

A:
But since the finalizer is always suppressed, there should not be any performance penalties.

Instances of the AbstractDisaposableBase subclasses will still be participating in the finalization queue management, so there will be a performance impact for this.


text:
Q: How do I split an array (or csv string) into separate columns in the db, in Rails 3? I have a model (share) in which I save who can edit a lesson.
It is separated from the user model, and from the lesson model.
The data is currently saved as
|share_id | lesson_id | shared_ids |
|    2    |     23    | "45,66,21" |

Where "shared_ids" are the user ids that can edit the lesson
I would like to split it into
|share_id | lesson_id | shared_ids |
|    2    |     23    |    "45"    |
|    3    |     23    |    "66"    |
|    4    |     23    |    "21"    |

I have managed to split the shared_ids, but it is currently saved as one array inside the table :
|share_id | lesson_id |   shared_ids   |
|    2    |     23    | "45","66","21" |

Thanks for your help.
---- Edit ----
The Share class looks like that:
class Share < ActiveRecord::Base
  attr_accessible :shared_token, :shared_ids
  belongs_to :lesson

  attr_reader :shared_token
  serialize :shared_ids
  # @Todo: save each seperately #
  def shared_token=(ids)
    self.shared_ids = ids.split(",")
  end
end

---- Edit 2 -----
The form for shared_token in the lesson view:
<%= f.fields_for :shares do |builder| %>
  <%= builder.label :shared_token, "Type the user names you wish to share the lesson with:" %>
  <%= builder.text_field :shared_token, "data-pre" => @shared_ids %>
<% end %>

A: Since Shares are children of Lessons, I think you might want to write a methed in your Lesson model that would iterate through the ids in a list (which you've already figured out how to generate) and create a Share for each id. something like...
def build_shares_from_list(ids)
    ids.each do |id|
        @share = self.shares.build({:share_ids => id})
        @share.save
    end
end

Then call that from your Lesson controller, and point your form to the appropriate controller action.

A: how about a pure SQL solution (havent tested the code, just a general direction)

*

*remove the quotes
update shares set share_ids = replace(share_ids, '"', '');

*create a temp table which will replace the old one once we're done
create table _shares (share_id, lesson_id, shared_ids);

*add the first shared_id from existing lists:
insert into _shares select share_id, lesson_id, substring(shared_ids, 0, locate(shared_ids, ",")) from shares where shared_ids like '%,%';

*remove the first shared_id from the existing lists:
update shares set shared_ids = substr(shared_ids, locate(shared_ids, ",") + 1) where shared_ids like '%,%';

*repeat 3, 4 until 0 records updated - no more shared_ids with "," - all are single values

*add the remaining values - last value in the original ids list, or values which had just one value to begin with:
insert into _shares select share_id, lesson_id, shared_ids from shares;

*replace tables
drop table shares; alter table _shares rename shares;
(or, if there are constraints there: truncate table shares, insert into shares select * from _shares;


text:
Q: How not to display all the boxes when I refresh the page This is a portion of a website I am building and I am finding it a little bit to solve this problem. I wanna make a kind of filter but my problem is that I don't want all the boxes to display first when I refresh the page or when the page is loaded. I dont want to display all the boxes, but instead boxes in their category.
<!DOCTYPE html>

<meta charset="UTF-8">
<title></title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css'>

<link rel="stylesheet" href="./loader.css">

Recharger son compte

Packet Data

Token PLN

Project 1

Brand

Project 2

Design

Project 3

Photos

Project 4

Brand

Project 5

Photos

Project 6

Design

// Digital filter
$(function () {
'use strict';
$('#digital ul.digital-filter li').on('click', function () {
// var linkValue = $(this).attr()
$(this).addClass('active').siblings().removeClass('active');
});
});

$(function () {
'use strict';
$('#digital ul.digital-filter li:first-of-type').on('click', function () {
$('#digital .digital-items .item').hide(0).fadeIn(0);
});
});

$(function () {
'use strict';
$('#digital ul.digital-filter li:not(:first-of-type)').on('click', function () {
$('#digital .digital-items .item').hide(0);
$('.' + $(this).data('value')).show(0);
});
});

*,
*:after,
*:before {
box-sizing: border-box;
padding: 0;
margin: 0;
}

.container {
margin: 0 auto;
padding-right: 15px;
padding-left: 15px;
}

@media (min-width: 1200px) {
.container {
width: 1170px;
}
}

.clear-fix,
.clear-fix:after,
.clear-fix:before {
content: '';
display: table;
clear: both;
}

.active a {
color: #007BFF;
}

ul,
li {
list-style: none;
}

li {
display: inline-block;
}

a,
a:hover {
text-decoration: none;
}

.rotate {
transform: rotate(90deg);
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-o-transform: rotate(90deg);
}

.section {
padding: 100px 0;
}

#digital .section-heading .section-subtitle {
margin: 30px 0;
}

#digital .digital-content .digital-filter li {
padding: 5px 10px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
}

#digital .digital-content .digital-filter li.active {
color: #007BFF;
}

#digital .digital-content .digital-items {
margin: 30px 0 0 0;
}

#digital .digital-content .digital-items .item {
position: relative;
display: block;
float: left;
width: calc(100% / 3 - 20px);
margin-left: 10px;
margin-right: 10px;
margin-bottom: 20px;
border: 3px solid #000000;
}

#digital .digital-content .digital-items .item:nth-child(1){
border: 3px solid #FF1A1A;
}

#digital .digital-content .digital-items .item:nth-child(2){
border: 3px solid #33CC00;
}

#digital .digital-content .digital-items .item:nth-child(3){
border: 3px solid #1A1AFF;
}

#digital .digital-content .digital-items .item:nth-child(4){
border: 3px solid #FF1A1A;
}

#digital .digital-content .digital-items .item:nth-child(5){
border: 3px solid #1A1AFF;
}

#digital .digital-content .digital-items .item:nth-child(6){
border: 3px solid #33CC00;
}

#digital .digital-content .digital-items .item:before {
content: '';
position: absolute;
display: block;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 90%;
height: 90%;
background-color: rgba(0, 123, 255, .7);
z-index: 1;
opacity: 0;
transition: all .4s ease-in-out;
-webkit-transition: all .4s ease-in-out;
-moz-transition: all .4s ease-in-out;
-ms-transition: all .4s ease-in-out;
-o-transition: all .4s ease-in-out;
}

#digital .digital-content .digital-items .item-data {
position: absolute;
left: 50%;
top: 30%;
transform: translate(-50%);
-webkit-transform: translate(-50%);
-moz-transform: translate(-50%);
-ms-transform: translate(-50%);
-o-transform: translate(-50%);
transition: all .4s ease-in-out;
-webkit-transition: all .4s ease-in-out;
-moz-transition: all .4s ease-in-out;
-ms-transition: all .4s ease-in-out;
-o-transition: all .4s ease-in-out;
z-index: 2;
opacity: 0;
}

#digital .digital-content .digital-items .item-data .title {
font-size: 16px;
font-weight: 400;
color: #fff;
}

#digital .digital-content .digital-items .item-data .subtitle {
font-size: 14px;
font-weight: 400;
color: #fff;
}

#digital .digital-content .digital-items .item:hover:before {
opacity: 1;
}
#digital .digital-content .digital-items .item:hover .item-data {
top: 50%;
opacity: 1;
}
#digital .digital-content .digital-items .item img {
display: block;
max-width: 100%;
}

A: $(function () {
'use strict';
  // Initial setup:
  // set the name of the starting category
  var startingCategory = "brand";
  // add the active class to the li item in the menu:
  $('#digital ul.digital-filter li[data-value="' + startingCategory + '"]').addClass('active');
  // hide everything apart from the startingCategory (using the :not() css selector):
  $('#digital .digital-items .item:not(.' + startingCategory + ')').hide();
  //
  $('#digital ul.digital-filter li').on('click', function () {
    // store the name of data-value
    var value = $(this).data("value");

    // add active to clicked li, remove from all others:
    $(this).addClass('active').siblings().removeClass('active');
    // Hide All boxes first
    $.when($('#digital .digital-items .item').fadeOut(0)).then(function () {
      // after all boxes are hidden show only the ones you want
      // uses $.when to check the animation has finished on all boxes
      $('#digital .digital-items .item' + '.' + value).show();
   });
  });
});

You can see it working on JSFiddle
Another way you can just trigger the click() event on one of the menu items, but depending on the animation speed/delays will show all boxes at page load and then animate "away", whereas this way, it should hide the unneeded boxes swiftly.


text:
Q: How to parse a file sent to Flask with a POST request into json? I have a python backend to which i send an xml or h5 files from the front.
Those xml\h5 's are huge lists of datapoints about a patient. I need to extract certain datapoints(subfields of the object) to feed to the next thing in this pipeline, but am not sure how to operate on a "request" file in python so that it is anything close to a json object im familiar with.
I have tried xmltodict library for converting the xml to json
Say, this is more or less how the POSTed file looks like
  <patdata>
      <id>MPS_2782</id>
      <lastname/>

....

And this is the api
from flask import jsonify
import requests, os, json, xmltodict
app = Flask(__name__)
api = Api(app)
CORS(app)
#VCG scripts are under Software/Matlab/Transfroms

@app.route('/api/upload', methods = ['POST'])
def upload_file():
    file = request.files['file']
    contents = xmltodict.parse(file)
    # xmltodict is XML to JSON parser
    print(">> The XML contents. <<<\n")
    print(json.loads(jsonify(contents)))
    return jsonify(contents)

if __name__ == '__main__':
    app.run(debug=False)

How do i get, say, the patient's id for example from 'file'?

A: If you are able to convert the XML file to dictionary then it's easy to get different attributes from the dictionary.
patient_id = contents['patient_id']
print(patient_id)

will fetch you the value.