text:
Q: You won't want to go in there for a while! I already apologize for taking such ugly sentence but I have no other choice as that's what brought the question to my mind. Just read this in Urban Dictionary:

I don't know what he ate, but man, he blew up the bathroom! You won't want to go in there for a while.

1st, I know it's possible to put "don't" in place of "won't" here, but don't know how that would affect the meaning.
2nd, is using "in" optional here or it adds some meaning to the sentence?

A: For what concerns the first part of your question (won't want vs. don't want), you may find useful this answer.
 In there is referred to a closed place, e.g. a bathroom; there would not be appropriate (see @J.R.'s comment below).

A: Won't is a contracted form of will not.  Don't is a contracted form of do not.
You do not want to take that course. Trust me, you will find his lectures vague and rambling.
The first statement, in the present tense,  you do not want,  is a statement cast as present fact. The second, in the future tense, you will find, is a statement cast as a prediction.

You do not want to go in there.
You will not want to go in there.

These statements are admonitory; they warn another person what not to want.
It seems to me that the do-form is the more emphatic of the two.
go in = enter
go  =  walk/travel to a destination; also, in the context of the original question, to urinate or move one's bowels.  Get outta my way, I really gotta go!
So, in that sense where go means to answer one of nature's calls:
You don't want to go (in) there; you want to go somewhere else. There's another up on the second floor.

A: I think that most people would use "won't" if they thought that there was a  possibility of the person doing it in the future. But if a person looked like they were about to do it, most people would probably say "don't" do it.
Whether to say "don't" or "won't" to another person is partially dependent on the people involved. Saying to someone else you "won't" want to do something is more formal than saying to someone else you "don't" want to do something. However this is not done by all people in all areas due to differences in the formality of how they speak to each other. For example, people I used to be around who knew each other well wouldn't think twice about saying "don't" to each other, but now I am around more formal people who may think that is rude, even among immediate family.

A: Ardy - I'd like to butt in as a native speaker. To me, use of "don't" implies certainty, i.e. "You don't want to go in there, because I know for a fact that you will not be happy if you do." "Won't" implies a degree of uncertainty: "You won't want to go in there (unless you are a normal human and not one of those freaky people who likes that sort of thing)."  If the speaker were expressing a preference, the "you" would be dropped:  "Don't go in there" or "Please don't go in there".


text:
Q: How do I add different types conforming to a protocol with an associated type to a collection? As an exercise in learning I'm rewriting my validation library in Swift.
I have a ValidationRule protocol that defines what individual rules should look like:
protocol ValidationRule {
    typealias InputType
    func validateInput(input: InputType) -> Bool
    //...
}

The associated type InputType defines the type of input to be validated (e.g String). It can be explicit or generic.
Here are two rules:
struct ValidationRuleLength: ValidationRule {
    typealias InputType = String
    //...
}

struct ValidationRuleCondition<T>: ValidationRule {
    typealias InputType = T
    // ...
}

Elsewhere, I have a function that validates an input with a collection of ValidationRules:
static func validate<R: ValidationRule>(input i: R.InputType, rules rs: [R]) -> ValidationResult {
    let errors = rs.filter { !$0.validateInput(i) }.map { $0.failureMessage }
    return errors.isEmpty ? .Valid : .Invalid(errors)
}

I thought this was going to work but the compiler disagrees.
In the following example, even though the input is a String, rule1's InputType is a String, and rule2s InputType is a String...
func testThatItCanEvaluateMultipleRules() {

    let rule1 = ValidationRuleCondition<String>(failureMessage: "message1") { $0.characters.count > 0 }
    let rule2 = ValidationRuleLength(min: 1, failureMessage: "message2")

    let invalid = Validator.validate(input: "", rules: [rule1, rule2])
    XCTAssertEqual(invalid, .Invalid(["message1", "message2"]))

}

... I'm getting extremely helpful error message:

_ is not convertible to ValidationRuleLength

which is cryptic but suggests that the types should be exactly equal?
So my question is... how do I append different types that all conform to a protocol with an associated type into a collection?
Unsure how to achieve what I'm attempting, or if it's even possible?
EDIT
Here's it is without context:
protocol Foo {
    typealias FooType
    func doSomething(thing: FooType)
}

class Bar<T>: Foo {
    typealias FooType = T
    func doSomething(thing: T) {
        print(thing)
    }
}

class Baz: Foo {
    typealias FooType = String
    func doSomething(thing: String) {
        print(thing)
    }
}

func doSomethingWithFoos<F: Foo>(thing: [F]) {
    print(thing)
}

let bar = Bar<String>()
let baz = Baz()
let foos: [Foo] = [bar, baz]

doSomethingWithFoos(foos)

Here we get:

Protocol Foo can only be used as a generic constraint because it has
  Self or associated type requirements.

I understand that. What I need to say is something like:
doSomethingWithFoos<F: Foo where F.FooType == F.FooType>(thing: [F]) {

}

A: Protocols with type aliases cannot be used this way. Swift doesn't have a way to talk directly about meta-types like ValidationRule or Array. You can only deal with instantiations like ValidationRule where... or Array<String>. With typealiases, there's no way to get there directly. So we have to get there indirectly with type erasure.
Swift has several type-erasers. AnySequence, AnyGenerator, AnyForwardIndex, etc. These are generic versions of protocols. We can build our own AnyValidationRule:
struct AnyValidationRule<InputType>: ValidationRule {
    private let validator: (InputType) -> Bool
    init<Base: ValidationRule where Base.InputType == InputType>(_ base: Base) {
        validator = base.validate
    }
    func validate(input: InputType) -> Bool { return validator(input) }
}

The deep magic here is validator. It's possible that there's some other way to do type erasure without a closure, but that's the best way I know. (I also hate the fact that Swift cannot handle validate being a closure property. In Swift, property getters aren't proper methods. So you need the extra indirection layer of validator.)
With that in place, you can make the kinds of arrays you wanted:
let len = ValidationRuleLength()
len.validate("stuff")

let cond = ValidationRuleCondition<String>()
cond.validate("otherstuff")

let rules = [AnyValidationRule(len), AnyValidationRule(cond)]
let passed = rules.reduce(true) { $0 && $1.validate("combined") }

Note that type erasure doesn't throw away type safety. It just "erases" a layer of implementation detail. AnyValidationRule<String> is still different from AnyValidationRule<Int>, so this will fail:
let len = ValidationRuleLength()
let condInt = ValidationRuleCondition<Int>()
let badRules = [AnyValidationRule(len), AnyValidationRule(condInt)]
// error: type of expression is ambiguous without more context

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why java.lang.Object can not be cloned? When i try to clone a generic Object i get compile time error . why?
    Object obj=new Object();
    obj.clone();  // Here compile time error "The method clone() from the type Object is not visible"

Every class extends Object class and clone method is protected in Object class.
protected methods can be accessed in same package as well as by subclasses and all classes are child of java.lang.Object.

A: Because clone is protected in the Object class.  It's not public.
The only way to get access to an object's clone() method is to know it has a compile-time type that has a public clone() method.

A: This will be the minimum to get clone working:
public class SubObj implements Cloneable {
  public Object clone() { return super.clone(); }
}

A: Per the Java SE docs:

The class Object does not itself implement the interface Cloneable, so
  calling the clone method on an object whose class is Object will
  result in throwing an exception at run time.

A: protected fields can be accessed only from inside the same package, thus clone() method of Object class can be accessed only from any class that is located in java.lang package.

A: You must explicitely implements Cloneable interface.
see this thread which give explanations.

A: If you use Groovy so that you can bypass the java compilation error, you get this:
Exception in thread "main" java.lang.CloneNotSupportedException: java.lang.Object
    at java.lang.Object.clone(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:86)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:230)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:912)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:756)
    at org.codehaus.groovy.runtime.InvokerHelper.invokePojoMethod(InvokerHelper.java:766)
    at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:754)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodN(ScriptBytecodeAdapter.java:170)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethod0(ScriptBytecodeAdapter.java:198)
    at regexTests.main(regexTests.groovy:19)
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820]

If you read the clone API (I will link it) it says that if the Interface isn't implemented, then calling *.clone() will throw a CloneNotSupportedException.
Link to the clone API for java.lang.Object
http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone%28%29
[EDIT]
The Original Question™ asked for why this method is visible in the way it is.  This is because it only accessible to methods within the java.lang package.  It isn't intended for a programmer to be able to clone an Object.  Throwing a CloneNotSupportedException is exactly what you want to do if you don't want your OWN object cloned.

A:  void method() {

    Object obj=new Object(); //Object is a parent class, it's not inherit from any other class...
    obj.clone();        //  compile time error

}

We can't access the protected method of "Has A" relationship from different package, because your Class package is (com.xxx.yyy) and an Object class package is (java.lang) both the classes are in different package.
protected methods can be accessed in same package as well as by subclasses(IS A relationship)

A: I tried this code :
public final class User {

    private String name;
    private boolean isActive;
    private String userId;
    private Address address;

    // can be constructed using this constructor ONLY !
    public User(String name, boolean isActive, String userId, Address address) {
        this.name = name;
        this.isActive = isActive;
        this.userId = userId;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public boolean isActive() {
        return isActive;
    }

    public String getUserId() {
        return userId;
    }

    public Address getAddress() {
        return address;
    }

    protected Object cloneMe() throws CloneNotSupportedException {
        return super.clone(); // throws CloneNotSupportedException
    }
}

public class CloneNotSupportedException
    extends Exception

Thrown to indicate that the clone method in class Object has been
  called to clone an object, but that the object's class does not
  implement the Cloneable interface. Applications that override the
  clone method can also throw this exception to indicate that an object
  could not or should not be cloned.

Object doesn't implement any interface and to make my User class work it must implement Cloneable

A: Object class clone() method has modified by protected access modifier in the API level. So we can't access it anywhere without inheritance. So before we invoke object class clone() method you need to implements Cloneable interface. Then Code will run at runtime properly. Otherwise it will generate CloneNotSupportedException at runtime.
/*Subclass is my implementing class */

public class SubClass implements Cloneable {

    @Override
    public SubClass clone() throws CloneNotSupportedException {
        return (SubClass) super.clone();
    }
}

A: import java.util.Scanner;
import java.util.jar.Attributes.Name;
import java.util.Arrays;
public class Main{
    public class man{
        protected void name() {
            System.out.println("hei");
        }
    }
    public class people extends man{
        public int age;

        public int getAge() {
            name();
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "people [age=" + age + "]";
        }

        public Object myclone() throws CloneNotSupportedException {
            return this.clone();
        }
    }

    public void test() throws CloneNotSupportedException {

        people p1 = new people();
        p1.setAge(10);
        System.out.println(p1);
//      NG:
        people p2 = (people)p1.clone();
//      Ok
        people p3 = (people)p1.myclone();
        p1.setAge(10);
        System.out.println(p1);
        System.out.println(p2);
    }
    public static void main(String args[]) throws CloneNotSupportedException{
        new Main().test();

    }
}

see the NG code and ok code.
//      NG for:The method clone() from the type Object is not visible
        people p2 = (people)p1.clone();
//      Ok
        people p3 = (people)p1.myclone();

why?
cause test() is not belong to the subclass.
so even though call clone() by peopel object p1,it is not the place of peopel object.
The myclone() is the exactly the place of people object.


text:
Q: Set image inside png transparency As the title suggests I have a PNG image that has some transparency. I'd like to fill that transparency with a second image (which is currently a JPEG, but it's not a problem to convert it to a PNG).
Every post I have found searching on the Internet was about the "inverse" problem (from an image with a background to an image with transparency), so obviously it did not work out for my situation; for example, I tried
convert -flatten myimg.png myimg.png

(taken from here) and
convert myimg1.png  -transparent white myimg.png

(taken from here).

A: In ImageMagick 6, if the two images are the same size, then you can just flatten the transparent image over the background image.
Background (lena.jpg):

Transparent (logo_crop_trans.png):

convert lena.jpg logo_crop_trans.png -flatten lena_logo.jpg

If using ImageMagick 7, then change convert to magick.
If you want to anti-alias the transparent image so that it is not so jagged, then use some blur to smooth the outline (Unix syntax):
convert lena.jpg \( logo_crop_trans.png -channel a -blur 0x1 -level 50x100% +channel \) -compose over -composite lena_logo2.jpg

If on Windows remove the \ before the parentheses.


text:
Q: How to auto scroll chat box as messages appear? I'm animating a chat. The first function loads the blue messages one after the other each time you press the input field/button. Then a second function shows the grey messages one at a time automatically, after the last blue message appears. But now I want the chat box to scroll down automatically as the grey messages appear.

const myHTMLCollection = document.getElementsByClassName("invisible");
const HTMLElementsArr = [...myHTMLCollection];

function blueMessage() {
  if (HTMLElementsArr.length > 0) {
    HTMLElementsArr.shift().classList.remove("invisible");
  }

  if (!HTMLElementsArr.length) {
    greyMessage();
  }
}

function greyMessage() {
  setTimeout(show_second, 1000);
}

function show_second() {
  document.getElementById("msg4").style.display = "block";
  setTimeout(show_third, 1000);
}

function show_third() {
  document.getElementById("msg5").style.display = "block";
  setTimeout(show_fourth, 1000);
}

function show_fourth() {
  document.getElementById("msg6").style.display = "block";
  setTimeout(show_fifth, 1000);
}

function show_fifth() {
  document.getElementById("msg7").style.display = "block";
  setTimeout(show_sixth, 1000);
}

function show_sixth() {
  document.getElementById("msg8").style.display = "block";
  setTimeout(show_seventh, 1000);
}

function show_seventh() {
  document.getElementById("msg9").style.display = "block";
}
.messages {
  height: 500px;
  overflow-y: scroll;
}

.invisible {
  display: none;
}

    Hi! I'm looking for an old friend. She attended Martin Grove a few years ago.

    Her name is Sam. *insert pic of Sam and MC*

    Did you know her or her last name by any chance?

Hello there!

    Unfortunately, I did not have the pleasure of teaching Sam. Her last name and whereabouts are a mystery to me as well.

    However, I do know she was in the photography club. I always saw her carrying a camera, always taking pictures.

    In fact, I believe she won a contest for one of them.

    She's a super talented girl!

    Best of luck on your search. I hope you two are reunited soon!


text:
Q: How can I create a Continued Figure Caption? I have two figures with somehow the same caption, see the code:
\begin{figure}[!ht]\centering
\includegraphics[height=18cm]{pic1}
\caption{caption}
\end{figure}
\addtocounter{figure}{-1}
\begin{figure}[!ht]\centering
\includegraphics[height=18cm]{pic2}
\caption{(continued)}
\end{figure}

Is there a way to have only the first figure referenced in the list of figures?

A: You can achieve this using the caption package which gives you access to the \ContinuedFloat float command (to keep the figure number the same) and an additional field to the \caption which when used but left empty prevent the figure to be mentioned in the List of Figures:
\documentclass{article}
\usepackage{graphicx}
\usepackage{caption}

\begin{document}

\begin{figure}[!ht]
\centering
\includegraphics[height=18cm]{pic1}
\caption{caption}
\end{figure}

\begin{figure}[!ht]
\ContinuedFloat
\centering
\includegraphics[height=18cm]{pic2}
\caption[]{caption (continued)}
\end{figure}

\end{document}

If you use the subfig package as well, you can also include the graphics inside a subfloat which would enable you to give each graphic it own caption in addition to the main figure one:
\subfloat[][]{\includegraphics[height=18cm]{pic2}}

this would then use an alpha counter within the figure to differentiate between the parts. The second [] can contain the subfloat caption.


text:
Q: Getting the real background-color of an element? Currently I want to get the real background-color of a specified object, here, the real means what the people see, for instance, given the following code:

    I am red

         I have no background, but I am red

The real background-color of #bar should be rbg(255,0,0).
Here's what I have so far:
function color_visible(color_str) {
  return color_str && !(color_str.substr(0, 4) == "rgba" && color_str.substr(-2, 2) == "0)");
}

function get_bgcolor (obj) {
  var ret = $(obj).css("background-color");
  if (!color_visible(ret)) ret = $(obj).css("bgcolor");
  if (color_visible(ret)) return ret;
  if (!$(obj).is("body")) return get_bgcolor($(obj).parent());
  return "rgb(255, 255, 255)";
}

But is there a better way to do it?
Demo in Stack Snippet and jsFiddle

function color_visible(color_str) {
  return color_str && !(color_str.substr(0, 4) == "rgba" && color_str.substr(-2, 2) == "0)");
}

function get_bgcolor (obj) {
  var ret = $(obj).css("background-color");
  if (!color_visible(ret)) ret = $(obj).css("bgcolor");
  if (color_visible(ret)) return ret;
  if (!$(obj).is("body")) return get_bgcolor($(obj).parent());
  return "rgb(255, 255, 255)";
}

console.log(get_bgcolor($("#bar")));
console.log(get_bgcolor($("#baz")));
console.log(get_bgcolor($("#foo")));
console.log(get_bgcolor($("body")));
body {
  background-color: yellow;
}

.bg_white {
  background-color: #FFF;
}

    I am red

      I have no background

      I am white

  I am yellow

A: Try window.getComputedStyle:
window.getComputedStyle(element, null).getPropertyValue("background-color")

This approach is simple and native, but doesn't support IE8

A: Try this:
var get_bgcolor = function(obj) {
    var real = obj.css('background-color');
    var none = 'rgba(0, 0, 0, 0)';
    if (real === none) {
        return obj.parents().filter(function() {
            return $(this).css('background-color') != none
        }).first().css('background-color');
    } else {
        return real
    }
}

http://jsfiddle.net/bqkwN/

A: This is a difficult thing to get right :( and I believe a 100% correct result in all cases is impossible.
background-color is not inherited. getComputedStyle only returns what is in elem.style.backgroundColor if there, or otherwise what is derived from the css stylesheets loaded. If these two still don't return a value, it returns rgba(0, 0, 0, 0) in which case you need to climb up the DOM to see what parents elements have. And this is further complicated in the case of frames which may derive their background from the (ie top) frame behind them.
Here is an attempt:
const getCbgcolor = (elem) => {
  if (!getCbgcolor.top) getCbgcolor.top= (() => {
    try { return window.top.document.documentElement; } catch(e) { return null; /* CORS */}})()
  });

  while (true) {
    let cbg=window.getComputedStyle(elem).getPropertyValue('background-color');
    if (cbg && cbg!='rgba(0, 0, 0, 0)' && cbg!='transparent') return cbg;
    if (elem===getCbgcolor.top) return 'initial';
    elem = elem.parentElement;
    if (!elem) return '';
  }
}

(An issues with this is that if someone explicitly set an element's background to rgba(0, 0, 0, 0) in the element's style or a css stylesheet you may want that value instead of the calculated value which will not work with this code.)

A: Javascript only version:
function realBackgroundColor(elem) {
    var transparent = 'rgba(0, 0, 0, 0)';
    var transparentIE11 = 'transparent';
    if (!elem) return transparent;

    var bg = getComputedStyle(elem).backgroundColor;
    if (bg === transparent || bg === transparentIE11) {
        return realBackgroundColor(elem.parentElement);
    } else {
        return bg;
    }
}
realBackgroundColor(document.querySelector('#element')); // rgb(255, 255, 255)

http://jsfiddle.net/qnLwsr7y/
Note that it does not take opacity or background images into account.

A: Try this:
function hexc(colorval) {
    var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    delete(parts[0]);
    for (var i = 1; i <= 3; ++i) {
        parts[i] = parseInt(parts[i]).toString(16);
        if (parts[i].length == 1) parts[i] = '0' + parts[i];
    }
    color = '#' + parts.join('');
}

var color = '';
$('div#foo').click(function() {
    var x = $(this).css('backgroundColor');
    hexc(x);
    alert(color);
})


text:
Q: HSV color range detection I am new to image detection techniques. I am using java openCV to detect colors in an image. I am able to detect yellow and red colors. I got there value from hit and trial method, these are working fine. But I want to detect green , orange and blue color as well from the hand image below.

Here is a part of my code .
public class ObjectPositionDetect {

    static int hueLowerR = 160;              // for red
    static int hueUpperR = 180;

//    static int hueLowerR = 20;                  // for yellow
//    static int hueUpperR = 31;

    public static void main(String[] args) {
        IplImage orgImg = cvLoadImage("3.JPG");
        IplImage thresholdImage = hsvThreshold(orgImg);
        cvSaveImage("test.jpg", thresholdImage);
        Dimension position = getCoordinates(thresholdImage);
        System.out.println("Dimension of original Image : " + thresholdImage.width() + " , " + thresholdImage.height());
        System.out.println("Position of red spot    : x : " + position.width + " , y : " + position.height);
    }

    static Dimension getCoordinates(IplImage thresholdImage) {
        int posX = 0;
        int posY = 0;
        CvMoments moments = new CvMoments();
        cvMoments(thresholdImage, moments, 1);
        // cv Spatial moment : Mji=sumx,y(I(x,y)•xj•yi)
        // where I(x,y) is the intensity of the pixel (x, y).
        double momX10 = cvGetSpatialMoment(moments, 1, 0); // (x,y)
        double momY01 = cvGetSpatialMoment(moments, 0, 1);// (x,y)
        double area = cvGetCentralMoment(moments, 0, 0);
        System.out.println("this is area "+area);
        posX = (int) (momX10 / area);
        posY = (int) (momY01 / area);
        return new Dimension(posX, posY);
    }
    public static CvScalar CV_RGB(double r, double g, double b) {
    return cvScalar(b, g, r, 0);
    //    return cvScalar(r, g, b, 0);
}

    static IplImage hsvThreshold(IplImage orgImg) {
        // 8-bit, 3- color =(RGB)
        IplImage imgHSV = cvCreateImage(cvGetSize(orgImg), 8, 3);  // creating a copy of an image
        //cvSaveImage("monochromatic.jpg", imgHSV);
        //System.out.println(cvGetSize(orgImg));
        cvCvtColor(orgImg, imgHSV, CV_BGR2HSV);
        // 8-bit 1- color = monochrome
        IplImage imgThreshold = cvCreateImage(cvGetSize(orgImg), 8, 1);

        // cvScalar : ( H , S , V, A)

        cvInRangeS(imgHSV, cvScalar(hueLowerR, 100, 100, 0), cvScalar(hueUpperR, 255, 255, 0), imgThreshold);

       // cvInRangeS(imgHSV, cvScalar(160, 218, 0, 0), cvScalar(180, 220 , 0, 0), imgThreshold);

        cvReleaseImage(imgHSV);
        cvSmooth(imgThreshold, imgThreshold, CV_MEDIAN, 13);
         cvSaveImage("monochromatic.jpg", imgThreshold);
        // save
        return imgThreshold;
    }
}

Kindly tell me how can I get the  HSV  ranges for Blue , Green and Orange colors or Just tell me the ranges for these required colors. Thanks

A: you can find a color wheel easily at internet. See the image below which tells you the Hue range of various colors. The range in color wheel given below is 0 to 360 but in openCV, the range is 0 to 180. So, just divide the values by 2, and you will get the value for openCV.

A: You can also use OpenCV version of HSV colour wheel , which I created to chose HSV value easily using trackbar while HSV-color segmentation

Code:
Mat HSV;
int H =170;
int S=200;
int V =200;
int R=0;
int G=0;
int B=0;

int MAX_H=179;
int MAX_S=255;
int MAX_V=255;
int mouse_x=0;
int mouse_y=0;
char window_name[20] = "HSV Color Plot";

//Global variable for hsv color wheel plot
int max_hue_range=179;
int max_step=3; //nuber of pixel for each hue color
int wheel_width=max_hue_range*max_step;
int wheel_hight=50;
int wheel_x=50; //x-position of wheel
int wheel_y=5;//y-position of wheel

//Global variable plot for satuarion-value plot
int S_V_Width=MAX_S;
int S_V_Height=MAX_S;
int S_V_x=10;
int S_V_y=wheel_y+wheel_hight+20;

//Global variable for HSV ploat
int HSV_Width=150;
int HSV_Height=150;
int HSV_x=S_V_x+S_V_Width+30;
int HSV_y=S_V_y+50;

void onTrackbar_changed(int, void*);
static void onMouse( int event, int x, int y, int, void* );
void drawPointers(void);

int main()
{

HSV.create(390,640,CV_8UC3); //Mat to store clock image
HSV.setTo(Scalar(200,0,200));

namedWindow(window_name);
createTrackbar( "Hue",window_name, &H, HUEMAX, onTrackbar_changed );
createTrackbar( "Saturation",window_name, &S, SATMAX,onTrackbar_changed );
createTrackbar( "Value",window_name, &V, VALMAX,onTrackbar_changed);
onTrackbar_changed(0,0); //initialoze window

setMouseCallback( window_name, onMouse, 0 );
 while(true)
  {
    int c;
    c = waitKey( 20 );
    if( (char)c == 27 )
      { break; }
   }

    return 0;
}

void onTrackbar_changed(int, void*){

//Plot color wheel.
int hue_range=0;
int step=1;
for(int i=wheel_y;i<wheel_hight+wheel_y;i++){
    hue_range=0;
    for(int j=wheel_x;j<wheel_width+wheel_x;j++){
   if(hue_range>=max_hue_range) hue_range=0;
       if(step++==max_step){
           hue_range++;
           step=1;
       }
        Vec3b pix;
        pix.val[0]=hue_range;
        pix.val[1]=255;
        pix.val[2]=255;

     HSV.at<Vec3b>(i,j)=pix;

    }

}

//Plot for saturation and value
int sat_range=0;
int value_range=255;
for(int i=S_V_y;i<S_V_Height+S_V_y;i++){
    value_range--;
    sat_range=0;
for(int j=S_V_x;j<S_V_Width+S_V_x;j++){
        Vec3b pix;
        pix.val[0]=H;
        pix.val[1]=sat_range++;
        pix.val[2]=value_range;
     HSV.at<Vec3b>(i,j)=pix;

    }

}

//Ploat for HSV
Mat roi1(HSV,Rect(HSV_x,HSV_y,HSV_Width,HSV_Height));
roi1=Scalar(H,S,V);
drawPointers();

Mat RGB;
cvtColor(HSV, RGB,CV_HSV2BGR);

imshow(window_name,RGB);
imwrite("hsv.jpg",RGB);

}

static void onMouse( int event, int x, int y, int f, void* ){
if(f&CV_EVENT_FLAG_LBUTTON){
        mouse_x=x;
        mouse_y=y;
    if(((wheel_x<=x)&&(x<=wheel_x+wheel_width))&&((wheel_y<=y)&&(y<=wheel_y+wheel_hight))){
        H=(x-wheel_x)/ max_step;
        cvSetTrackbarPos("Hue", window_name, H);
        }
    else if(((S_V_x<=x)&&(x<=S_V_x+S_V_Width))&&((S_V_y<=y)&&(y<=S_V_y+S_V_Height))){

        S=x-S_V_x;
        y=y-S_V_y;
        V=255-y;

        cvSetTrackbarPos("Saturation", window_name, S);
        cvSetTrackbarPos("Value", window_name, V);

        }

}

}

void drawPointers(){
   // Point p(S_V_x+S,S_V_y+(255-V));
    Point p(S,255-V);

    int index=10;
    Point p1,p2;
    p1.x=p.x-index;
    p1.y=p.y;
    p2.x=p.x+index;
    p2.y=p.y;

    Mat roi1(HSV,Rect(S_V_x,S_V_y,S_V_Width,S_V_Height));
    line(roi1, p1, p2,Scalar(255,255,255),1,CV_AA,0);
    p1.x=p.x;
    p1.y=p.y-index;
    p2.x=p.x;
    p2.y=p.y+index;
    line(roi1, p1, p2,Scalar(255,255,255),1,CV_AA,0);

    int x_index=wheel_x+H*max_step;
    if(x_index>=wheel_x+wheel_width) x_index=wheel_x+wheel_width-2;
    if(x_index<=wheel_x) x_index=wheel_x+2;

    p1.x=x_index;
    p1.y=wheel_y+1;
    p2.x=x_index;
    p2.y=wheel_y+20;
    line(HSV, p1, p2,Scalar(255,255,255),2,CV_AA,0);

    Mat RGB(1,1,CV_8UC3);
    Mat temp;
    RGB=Scalar(H,S,V);
    cvtColor(RGB, temp,CV_HSV2BGR);
    Vec3b rgb=temp.at<Vec3b>(0,0);
    B=rgb.val[0];
    G=rgb.val[1];
    R=rgb.val[2];

    Mat roi2(HSV,Rect(450,130,175,175));
    roi2=Scalar(200,0,200);

    char name[30];
    sprintf(name,"R=%d",R);
    putText(HSV,name, Point(460,155) , FONT_HERSHEY_SIMPLEX, .7, Scalar(5,255,255), 2,8,false );

    sprintf(name,"G=%d",G);
    putText(HSV,name, Point(460,180) , FONT_HERSHEY_SIMPLEX, .7, Scalar(5,255,255), 2,8,false );

    sprintf(name,"B=%d",B);
    putText(HSV,name, Point(460,205) , FONT_HERSHEY_SIMPLEX, .7, Scalar(5,255,255), 2,8,false );

    sprintf(name,"H=%d",H);
    putText(HSV,name, Point(545,155) , FONT_HERSHEY_SIMPLEX, .7, Scalar(5,255,255), 2,8,false );

    sprintf(name,"S=%d",S);
    putText(HSV,name, Point(545,180) , FONT_HERSHEY_SIMPLEX, .7, Scalar(5,255,255), 2,8,false );

    sprintf(name,"V=%d",V);
    putText(HSV,name, Point(545,205) , FONT_HERSHEY_SIMPLEX, .7, Scalar(5,255,255), 2,8,false );

}


text:
Q: jQuery UI sortable on slider solution I currently have implemented jQuery UI sortable on my list of items

1

2

...

To that list I have slider which shows only X number of items and rest can be shown by clicking next or previous buttons.
I tried to add sort parameter to sortable constructor and call those methods, but here is the thing. The container showNext and showPrevious methods do some jQuery animation and destroy first node etc. and I think that workaround would be easier and leave those methods for buttons.
How would you suggest to make this happen: When I start to reorder elements and moving to the end of the list, the list shows next element and places currently dragged after that, but doesn't stop dragging event.

A: I figured this by making container overflow:hidden and implemented sort(e,ui)
sort : function(e, ui) {
//move by modulus
}


text:
Q: iphone app does not display icon on ipad I'm building an app for iPhone devices ("devices" set to "iPhone" in "general" tab of mon only target). When run on an iPad simulator (or a real iPad) I do not have the correct icon (the one displayed correctly on an iphone).
Note that my AppIcon is defined in the Images.xcassets. See here screenshot of my assets.
Any ideas?

A: In that screenshot it looks like you only have iPhone icons loaded. Is your app set to both iPhone and iPad in the main settings? You may have to create a new project with "Devices" set to "Universal" for the iPad options to show up in the AppIcon file (see image below, how yours needs to look).

If you don't want to create a whole new project, open your AppIcon file in the finder, erase everything, paste the code below in, save & then add all the iPhone & iPad images in again.
{
"images" : [
{
  "idiom" : "iphone",
  "size" : "20x20",
  "scale" : "2x"
},
{
  "idiom" : "iphone",
  "size" : "20x20",
  "scale" : "3x"
},
{
  "idiom" : "iphone",
  "size" : "29x29",
  "scale" : "2x"
},
{
  "idiom" : "iphone",
  "size" : "29x29",
  "scale" : "3x"
},
{
  "idiom" : "iphone",
  "size" : "40x40",
  "scale" : "2x"
},
{
  "idiom" : "iphone",
  "size" : "40x40",
  "scale" : "3x"
},
{
  "idiom" : "iphone",
  "size" : "60x60",
  "scale" : "2x"
},
{
  "idiom" : "iphone",
  "size" : "60x60",
  "scale" : "3x"
},
{
  "idiom" : "ipad",
  "size" : "20x20",
  "scale" : "1x"
},
{
  "idiom" : "ipad",
  "size" : "20x20",
  "scale" : "2x"
},
{
  "idiom" : "ipad",
  "size" : "29x29",
  "scale" : "1x"
},
{
  "idiom" : "ipad",
  "size" : "29x29",
  "scale" : "2x"
},
{
  "idiom" : "ipad",
  "size" : "40x40",
  "scale" : "1x"
},
{
  "idiom" : "ipad",
  "size" : "40x40",
  "scale" : "2x"
},
{
  "idiom" : "ipad",
  "size" : "76x76",
  "scale" : "1x"
},
{
  "idiom" : "ipad",
  "size" : "76x76",
  "scale" : "2x"
},
{
  "idiom" : "ipad",
  "size" : "83.5x83.5",
  "scale" : "2x"
}
],
"info" : {
  "version" : 1,
  "author" : "xcode"
}
}


text:
Q: Unfailing Javascript Image Preview I have the following code that presents the user with a preview of the image they're trying to upload and works really well in FF:
var img = document.createElement('img');
img.src = $('#imageUploader').get(0).files[0].getAsDataURL();

The problem is, getAsDataURL() only works in FF. Is there something similar/a workaround for this kind of functionality in Chrome (specifically)?

A: If the browser doesn't support getAsDataURL you could make sure that the file input is instead using Gears' openFiles (scroll down) to read a file selected by the user.
Google ain't working on Gears anymore, but it will work in Chrome, at least until getAsDataURL() gets implemented.
EDIT: Changed answer to be more helpful.

A: IE does not yet support the File API. Anyhow, you need to use a FileReader to read a file. Also, the file is not its file name (your variable naming is a little ambiguous).
file = fileObj.files[0];
var fr = new FileReader;
fr.onloadend = changeimg;
fr.readAsDataURL(file)


text:
Q: add toggle to select: bootstrap I am trying to add a select input field in twitter bootstrap. I intend to display different fields when each one of these options are selected. I tried it using data-toggle. But i could only succeed that with buttons and not on select field.

                                            Payment Mode

                                                <select id="payment" class="input-xlarge">
                                                    <option value="" class="input-xlarge">Select your Payment mode</option>
                                                    <option value="1"> Cheque Deposit</option>
                                                    <option value="2">Online Transaction</option>
                                                    <option value="3">ATM Transfer</option>
                                                    <option value="4">IMPS Transfer</option>
                                                </select>

This code for button works fine -
<button data-toggle="collapse" href="#cash">
Submit
</button>

Cheers in advance
Shahzad

A: Finally got the answer! :)
Just a script did the trick.
Here is how i did it:

Payment Mode

    <select id="payment" class="input-xlarge">
        <option value="" class="input-xlarge">Select your Payment mode</option>
        <option value="cash">Cash Deposit</option>
        <option value="cheque">Cheque Deposit</option>
        <option value="online">Online Transaction</option>
        <option value="transfer">ATM Transfer</option>
    </select>

        <input class="input-xlarge focused" id="focusedInput" type="text">

        <input class="input-xlarge focused" id="focusedInput" type="text">


text:
Q: Various definitions of Galois Groups The situation for this question deals with the varying definitions of the Galois group of a field extension.
The question is how Dummit and Foote defines the Galois group. I'll list their definition after the specific example set up. In my Algebra class if $K/F$ if a field extension we define $Gal(K/F) = \{\phi \in Aut(K): \phi(f) = f,\,\,  \forall f\in F \}$. i.e. the automorphisms of $K$ that fix $F$. We were asked to find the Galois group of the splitting field of $x^3 - 10$ over $\mathbb{Q}$.
The roots of this polynomial are $\sqrt[3]{10}\zeta_i $ where $\zeta_i$ are the are the 3rd roots of unity. Thus the splitting field for this polynomial is $\mathbb{Q}(\sqrt[3]{10},\zeta_i)$. The degree of this extension ($|\mathbb{Q}(\sqrt[3]{10},\zeta_i):\mathbb{Q}|$) is 9, as can be seen by extending $\mathbb{Q}$ one root at a time.
$$|\mathbb{Q}(\sqrt[3]{10},\zeta_i):\mathbb{Q}| = |\mathbb{Q}(\sqrt[3]{10},\zeta_i):\mathbb{Q}(\sqrt[3]{10})|\cdot |\mathbb{Q}(\sqrt[3]{10}):\mathbb{Q}|$$
where each extension is degree 3. And after some work I have determined that $Aut(K/F) = S_3$ (i.e. from class definition the Galois group is $S_3$).
Now on to the main question: According to Dummit and Foote's definition a group is Galois if $|Aut(K/F)| = |K:F|$ so in our example $|Aut(\mathbb{Q}(\sqrt[3]{10},\zeta_i)| = 6 \not= 9 = |\mathbb{Q}(\sqrt[3]{10},\zeta_i):\mathbb{Q}|$. Thus by this definition our group is not a Galois group.
The very next Corollary [Cor 14.6] states: If $K$ is the splitting field over $F$ of a separable polynomial $f(x)$ then $K/F$ is Galois.
Consider the polynomial $p(x) = x^3 - 10$ again. The splitting field is the one listed above $\mathbb{Q}(\sqrt[3]{10},\zeta_i)$ according to Dummit and Foote $p(x)$ is separable since no root has multiplicity greater than 1 (they give an example where $x^2 - 2$ is separable over $\mathbb{Q}$ for similar reasonings). Thus by their definition $Aut(\mathbb{Q}(\sqrt[3]{10},\zeta_i))$ is not the Galois group but by their Corollary it is, which is very confusing.
Any clarity? Any mistakes computing degrees or Automorphism groups?
A few other optional things of note:
(i) If there has been an error in saying the splitting field of $p$ is $\mathbb{Q}(\sqrt[3]{10},\zeta_i)$ for some reason, it certainly is the splitting field of $q(x) = (x^3 - 10)(x^3 -1)$ which by their definition is still separable and seems to still break their definition.
(ii) A different book (Basic Algebra by Knapp) defines separable as being able to be split into distinct linear factors, with this definition of separable using Dummit and Foote's Corollary keeps us consistent, but it seems odd that Dummit and Foote's definitions could contradict each other.
Unfortunately I can't seem to make this any shorter, it all seems really important to the question. Any help would be appreciated, Thanks.
EDIT: Okay guys disregard this question. I was mistaken in the minpoly of $\zeta_3$ over $\mathbb{Q}$ This is a degree 6 extension.


text:
Q: Group by, count and stream individual results from mongodb query In mongodb, having a collection with sessionIds and labels, I would like to group by the sessionId where label equals 'view_item' and accomplish:

*

*Get the count of sessionId groups.

*Be able to stream each sessionId to the consumer (assuming I have limited memory resources and a large number individual sessionIds)

Assume following documents in a collection:
{ "label" : "view_item", "sessionId" : "01e5dnnpsczgfq58rmp0cjtjm0" }
{ "label" : "view_category", "sessionId" : "01e5dnnpsczgfq58rmp0cjtjm0" }
{ "label" : "view_item", "sessionId" : "01e5dnnpsczgfq58rmp0cjtjm0" }
{ "label" : "view_item", "sessionId" : "01e5g7vzx5dh0mv8m6g1zbdrnj" }
{ "label" : "view_item", "sessionId" : "01e5g7vzx5dh0mv8m6g1zbdrnj" }
{ "label" : "view_category", "sessionId" : "01e5g7vzx5dh0mv8m6g1zbdrnj" }
{ "label" : "view_item", "sessionId" : "01e5g7vzx5dh0mv8m6g1zbdrnj" }

The expected result would be something like this:
Get results somehow and...
result.count() // 2 (or some other way of getting the count)
await result.next() // { sessionId: '01e5dnnpsczgfq58rmp0cjtjm0' }
await result.next() // { sessionId: '01e5g7vzx5dh0mv8m6g1zbdrnj' }
await result.next() // null

I've been fiddling with the aggregation framework and manage to group and count. In theory I could do two queries to first get count and then the groups, but in a frequent write scenario I'm worried that doing two separate queries could lead to inconsistencies, especially since I haven't figured out how to  include any start / end ids in the result from the count query, which could be used to confine the results from the groups query.
What I have so far is:
const result = collection.aggregate([
  { $match: { label: 'view_item' } },
  { $group : { _id: { sessionId: '$sessionId' } } },
]);

await result.next() // { _id: { sessionId: '01e5g7vzx5dh0mv8m6g1zbdrnj' } }
await result.next() // { _id: { sessionId: '01e5dnnpsczgfq58rmp0cjtjm0' } }
await result.next() // null

and
const result = collection.aggregate([
  { $match: { label: 'view_item' } },
  { $group : { _id: { sessionId: '$sessionId' } } },
  { $facet: { count: [{ $count: 'count' }] } }
]);

await result.next() // { count: [ { count: 2 } ] }
await result.next() // null

Question
How can the two queries above be combined to reliably get the count and a result with the grouped sessionId that can be streamed? (I assume any solution relying on result.toArray().length needs to load the whole result in memory, which is ruled out).
Is it possible to do in one single query or more likely to get the count and start / end ids in one query and then do a second query to get the groups confined by the start / end ids?
Thanks!

A: If I understand you requirements clearly, you need to gather all the sessions that have been assigned to each label in one array, and count that sessions
if so, we may use the $group to group the sessions assigned to each label,
and $size to calculate that array length
we may do something like that
db.collection.aggregate([
  {
    $match: {} // if you need the 'View_Item' labels only, than add it here
  },
  {
    $group: {
      _id: "$label", // make the _id of the results is the label
      sessionsIds: { // array of sessions
        $push: "$sessionId"
      }
    }
  },
  {
    $project: { // use the $project as $size is available only in the $project stage
      _id: 1,
      sessionsIds: 1,
      sessionsCount: {
        $size: "$sessionsIds"
      }
    }
  }
])

you could try that here in Mongo Playground

Update, If you need to get the number of unique sessions Ids, and no duplication in sessionsIds array, use $addToSet instead of $push

update 2: If we need to group by the sessionId and count how many documents have this sessionId, we can do something like

db.collection.aggregate([
  {
    $match: {} // if you need the 'View_Item' labels only, than add it here
  },
  {
    $group: {
      _id: "$sessionId",
      count: {
        $sum: 1
      }
    }
  }
])

this will return a result
[
  {
    "_id": "01e5dnnpsczgfq58rmp0cjtjm0",
    "count": 3
  },
  {
    "_id": "01e5g7vzx5dh0mv8m6g1zbdrnj",
    "count": 4
  }
]

if you need to make the _id of the result be an object rather than ObjectId, we could do something like
db.collection.aggregate([
  {
    $match: {} // if you need the 'View_Item' labels only, than add it here
  },
  {
    $group: {
      _id: {
        sessionId: "$sessionId"
      },
      count: {
        $sum: 1
      }
    }
  }
])

this will result in
[
  {
    "_id": {
      "sessionId": "01e5dnnpsczgfq58rmp0cjtjm0"
    },
    "count": 3
  },
  {
    "_id": {
      "sessionId": "01e5g7vzx5dh0mv8m6g1zbdrnj"
    },
    "count": 4
  }
]

you can try all of that here Mongo_Playground 2


text:
Q: Doctrine_Query update with float value I need to increment User's balance, so I do:
Doctrine_Query::create()->from('User')->update('balance', 'balance + 0.15')->execute();

And I got an error "Unknown component alias 0". I think its because of 0.15
So how can I update (using DQL) balance without additional SELECT queries to User's table to fetch his balance, calculate new balance and do query like Doctrine_Query::create()->from('User')->update('balance', '?', $new_balance)->execute();

A: This solution works well for MySQL!!!
Doctrine_Query::create()->update('Users')->set('balance', 'balance + "0.15"')->execute();

A: Your assumption looks right. Doctrine thinks the 0 is a table alias. Have you tried using set()?
From the docs:
$q = Doctrine_Query::create()
    ->update('Account')
    ->set('amount', 'amount + 200')
    ->where('id > 200');
// If you just want to set the amount to a value
$q->set('amount', '?', 500);
echo $q->getSqlQuery();

// UPDATE account
// SET amount = amount + 200
// WHERE id > 200


text:
Q: .addArgument is not a function Discord bot Here is my Discord command module code, for some reason this is spitting out that .addArgument is not a function.
const Discord = require('discord.js');
const { SlashCommandBuilder } = require('@discordjs/builders');

data = new SlashCommandBuilder()
    .setName('purge')
    .setDescription('Purges a number of messages from the channel.')
    .addArgument('number', 'The number of messages to purge.')
    .addArgument('channel', 'The channel to purge messages from.')
    .setExecute(async (interaction, args) => {
        const channel = interaction.guild.channels.cache.find(c => c.name === args.channel);
        if (!channel) return interaction.reply('Channel not found.');
        const messages = await channel.messages.fetch({ limit: args.number });
        await channel.bulkDelete(messages);
        interaction.reply(`Purged ${messages.size} messages.`);
    }

);

It just gives me this:

TypeError: (intermediate value).setName(...).setDescription(...).addArgument is not a function

A: The reason you are getting this error is because there is nothing called .addArgument() in the SlashCommandBuilder. If you want to add arguments like numbers or channels, you need to use .addNumberOption() or .addChannelOption(). The way you will need to use to add a channel and number option is like this:
.addNumberOption(option => {
    return option
        .setName('number') // Set the name of the argument here
        .setDescription('The number of messages to purge.') // Set the description of the argument here
        .setRequired() // This is optional. If you want the option to be filled, you can just pass in true inside the .setRequired() otherwise you can just remove it
})
.addChannelOption(option => {
    return option
        .setName('channel')
        .setDescription('The channel to purge messages from.')
        .setRequired()
})

You can learn more about slash commands and options here => Options | discord.js


text:
Q: Font difference in mathematica 9 and 10 after export to illustrator It seems WRI has changed the way fonts are dealt with in Mathematica 9 and 10.
The following command
Export["test.eps", "This is a nice formula"]

yields this

in Mathematica 9 (after import to Illustrator)
whereas it yields

in Mathematica 10. In other words, the font it not recognized anymore by Illustrator CS3. This is using Macos X.
I have tried uploading the Mathematica fonts from http://support.wolfram.com/kb/10427
but it does not seem to help.

Any ideas?
  (My apologies for a possibly silly question)

Update
Following @Szabolcs remark I tried
Export["test.pdf", "This is a nice formula"]

In Mathematica 9 I get a 1.3 Mb (!!) file which works fine in Illustrator
In Mathematica 10 I get

which is hardly progress!


text:
Q: SwiftUI + Combine, using Models and ViewModels together I'm very new to Swift and I am currently trying to learn by building a rent splitting app with SwiftUI + Combine. I want to follow the MVVM pattern and am trying to implement this. At the moment I have the following Model, ViewModel and View files:
Model:
import Foundation
import Combine

struct InputAmounts {
    var myMonthlyIncome : Double
    var housemateMonthlyIncome : Double
    var totalRent : Double
}

ViewModel (where I have attempted to use the data from the Model to conform to the MVVM pattern, but I am not sure I have done this in the cleanest way/correct way so please correct me if wrong)
import Foundation
import Combine

class FairRentViewModel : ObservableObject {

    private var inputAmounts: InputAmounts

    init(inputAmounts: InputAmounts) {
        self.inputAmounts = inputAmounts
    }

    var yourShare: Double {
        inputAmounts.totalRent = Double(inputAmounts.totalRent)
        inputAmounts.myMonthlyIncome = Double(inputAmounts.myMonthlyIncome)
        inputAmounts.housemateMonthlyIncome = Double(inputAmounts.housemateMonthlyIncome)
        let totalIncome = Double(inputAmounts.myMonthlyIncome + inputAmounts.housemateMonthlyIncome)
        let percentage = Double(inputAmounts.myMonthlyIncome / totalIncome)
        let value = Double(inputAmounts.totalRent * percentage)

        return Double(round(100*value)/100)
    }
}

And then am trying to pass this all to the View:
import SwiftUI
import Combine

struct FairRentView: View {

    @ObservedObject private var viewModel: FairRentViewModel

    init(viewModel: FairRentViewModel){
        self.viewModel = viewModel
    }

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Enter the total monthly rent:")) {
                    TextField("Total rent", text: $viewModel.totalRent)
                        .keyboardType(.decimalPad)
                }

                Section(header: Text("Enter your monthly income:")) {
                    TextField("Your monthly wage", text: $viewModel.myMonthlyIncome)
                        .keyboardType(.decimalPad)
                }

                Section(header: Text("Enter your housemate's monthly income:")) {
                    TextField("Housemate's monthly income", text: $viewModel.housemateMonthlyIncome)
                        .keyboardType(.decimalPad)
                }
                Section {
                    Text("Your share: £\(viewModel.yourShare, specifier: "%.2f")")
                }
            }
            .navigationBarTitle("FairRent")
        }
    }
}

struct FairRentView_Previews: PreviewProvider {
    static var previews: some View {
        let viewModel = FairRentViewModel(inputAmounts: <#InputAmounts#>)
        FairRentView(viewModel: viewModel)
    }
}

I am getting the build errors with the View:
"Value of type 'ObservedObject.Wrapper' has no dynamic member 'totalRent' using key path from root type 'FairRentViewModel'"
"Value of type 'ObservedObject.Wrapper' has no dynamic member 'myMonthlyIncome' using key path from root type 'FairRentViewModel'"
"Value of type 'ObservedObject.Wrapper' has no dynamic member 'housemateMonthlyIncome' using key path from root type 'FairRentViewModel'"
My questions are:

*

*What does this error mean and please point me in the right direction to solve?

*Have I gone completely the wrong way at trying to implement the MVVM pattern here?

As I said I am a Swift beginner just trying to learn so any advice would be appreciated.
UPDATE IN RESPONSE TO ANSWER
  var yourShare: String {
        inputAmounts.totalRent = (inputAmounts.totalRent)
        inputAmounts.myMonthlyIncome = (inputAmounts.myMonthlyIncome)
        inputAmounts.housemateMonthlyIncome = (inputAmounts.housemateMonthlyIncome)
        var totalIncome = Double(inputAmounts.myMonthlyIncome) 0.00 + Double(inputAmounts.housemateMonthlyIncome) ?? 0.00
        var percentage = Double(myMonthlyIncome) ?? 0.0 / Double(totalIncome) ?? 0.0
        var value = (totalRent * percentage)

        return FairRentViewModel.formatter.string(for: value) ?? ""
    }

I am getting errors here that "Value of optional type 'Double?' must be unwrapped to a value of type 'Double'" which I thought I was achieving with the ?? operands?

A: Your view model should have properties for each of the model properties you want to work with in the view and the view model should also be responsible for converting them to a format suitable for the view. The properties should be marked as @Published to so that the view gets updated if they are changed.
For example
@Published var myMonthlyIncome: String

and this is as you see a String and we can convert it in the init
myMonthlyIncome = FairRentViewModel.formatter.string(for: inputAmounts.myMonthlyIncome) ?? ""

Here is my complete version of the view model
final class FairRentViewModel : ObservableObject {
    private static let formatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }()

    private var inputAmounts: InputAmounts

    @Published var myMonthlyIncome: String
    @Published var housemateMonthlyIncome: String
    @Published var totalRent: String

    init(inputAmounts: InputAmounts) {
        self.inputAmounts = inputAmounts
        myMonthlyIncome = FairRentViewModel.formatter.string(for: inputAmounts.myMonthlyIncome) ?? ""
        housemateMonthlyIncome = FairRentViewModel.formatter.string(for: inputAmounts.housemateMonthlyIncome) ?? ""
        totalRent = FairRentViewModel.formatter.string(for: inputAmounts.totalRent) ?? ""
    }

    var yourShare: String {
        let value = inputAmounts.totalRent * inputAmounts.myMonthlyIncome / (inputAmounts.myMonthlyIncome + inputAmounts.housemateMonthlyIncome)

        return FairRentViewModel.formatter.string(for: Double(round(100*value)/100)) ?? ""
    }

    func save() {
        inputAmounts.myMonthlyIncome = FairRentViewModel.formatter.number(from: myMonthlyIncome)?.doubleValue ?? 0
        //...
    }
}

You should do something similar for yourShare and I the save method is just a simple example of how to update the model from the view if you tie the function to a Button action or similar.
Also note that the number style I used for the formatter is just a guess, you might need to change that. And it is recommended to work with Decimal instead of Double when dealing with money.


text:
Q: Format date in SharePoint 2013 I have a date field in SharePoint 2013 list. Using SP Service am retrieving the date field value. The value is retrieved as 2017-5-24 00:00:00. I want to format the date as May 5 2017. Can this be done using jquery?

A: Try below code:
String.format("{0:MMM} {0:dd} {0:yyyy}",new Date(ows_Date));

In the new Date()function, pass the column name of the date field
Excellent reference - Changing date format using javascript
Update - you need to write a custom function as below:
var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

function convertSPDate(d) {

    // split apart the date and time
    var xDate = d.split(" ")[0];
    var xTime = d.split(" ")[1];

    // split apart the hour, minute, & second
    var xTimeParts = xTime.split(":");
    var xHour = xTimeParts[0];
    var xMin = xTimeParts[1];
    var xSec = xTimeParts[2];

    // split apart the year, month, & day
    var xDateParts = xDate.split("-");
    var xYear = xDateParts[0];
    var xMonth = xDateParts[1];
    var xDay = xDateParts[2];

    var dDate = new Date(xYear, xMonth-1, xDay, xHour, xMin, xSec);
    return dDate;
}

This will return the spservices column to a date object.
After that, you can use it as below:
var convertedDate = convertSPDate($(this).attr("ows_Date"));

var formattedDate = monthNames[convertedDate.getMonth()] + ' ' + convertedDate.getDate() + ' ' + convertedDate.getFullYear();

Modified from here - jQuery function for formatting dates in SharePoint with SPServices
xMonth modified to xMonth-1

A: You do not need a library in order to display it like that.
var dateString = "2017-5-24 00:00:00";
var date = new Date(dateString);
date.toLocaleDateString("en-US", { year: 'numeric', month: 'long', day: 'numeric' }); // May 24, 2017

For further options you may also take a look at this post about date formatting.

A: You can do that using moment.js. Please go to the site https://momentjs.com/ , get moment.js from the site and add its reference to your code. You can convert your date in the expected format shown on the home page.


text:
Q: NodeJS, MongoDB data modelling for CSV data Problem
I have a CSV file with some data like below.
PK,title,year,length,budget,rating,votes,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,mpaa,Action,Animation,Comedy,Drama,Documentary,Romance,Short
1,$,1971,121,NA,6.4,348,4.5,4.5,4.5,4.5,14.5,24.5,24.5,14.5,4.5,4.5,,0,0,1,1,0,0,0
2,$1000 a Touchdown,1939,71,NA,6,20,0,14.5,4.5,24.5,14.5,14.5,14.5,4.5,4.5,14.5,,0,0,1,0,0,0,0

The CSV file is around 5MB in size and has around 58,000+ lines like the sample above.
Current Scenario
Currently I am parsing the above data and converting it to objects and saving to MongoDB in an array of the objects. Something like below
{ PK: '1',
  title: '$',
  year: '1971',
  length: '121',
  budget: 'NA',
  rating: '6.4',
  votes: '348',
  r1: '4.5',
  r2: '4.5',
  r3: '4.5',
  r4: '4.5',
  r5: '14.5',
  r6: '24.5',
  r7: '24.5',
  r8: '14.5',
  r9: '4.5',
  r10: '4.5',
  mpaa: '',
  Action: '0',
  Animation: '0',
  Comedy: '1',
  Drama: '1',
  Documentary: '0',
  Romance: '0',
  Short: '0' }
{ PK: '2',
  title: '$1000 a Touchdown',
  year: '1939',
  length: '71',
  budget: 'NA',
  rating: '6',
  votes: '20',
  r1: '0',
  r2: '14.5',
  r3: '4.5',
  r4: '24.5',
  r5: '14.5',
  r6: '14.5',
  r7: '14.5',
  r8: '4.5',
  r9: '4.5',
  r10: '14.5',
  mpaa: '',
  Action: '0',
  Animation: '0',
  Comedy: '1',
  Drama: '0',
  Documentary: '0',
  Romance: '0',
  Short: '0' }

Although, when I upload the file I receive the Document exceeds maximum allowed bson size of 16777216 bytes error.
I tried using GridFS. The file is getting uploaded and the chunks are prepared fine as well. But, I am not sure if I can retrieve the data back as an array of objects.
I need to retrieve all the data to crunch and create some analysis.
The CSV file is one source of data. Another source would be getting data from a web service on a proprietary system where the same process is followed.
Question
I think there is a flaw in the data model and in the way I am saving the data to MongoDB. If yes, then what is the optimal way to handle the large amount of data.
Would really appreciate any help.


text:
Q: websockets - detect multiple clients with same ID and "kick" them This is my server side websocket script:
var clients = [ ];

//sample request: ****:8080/?steamid=123456789
var connection;
var aqsteamid = getParameterByName("steamid",request.resource);

connection = request.accept(null, request.origin);

connection.ID = aqsteamid;
connection.balRefreshes = 0;
connection.clientIndex = clients.push(connection) - 1;

//check if this user is already connected. If yes, kicks the previous client ***====EDITED====***
for(var i = 0; i < clients.length; i++)
{
    if(clients[i].ID === aqsteamid){
        var indx = clients.indexOf(clients[i]);
        clients[indx].close();
    }
}

console.log('ID',connection.ID,' connected.');

socket.on('close', function(webSocketConnection, closeReason, description){
    try{
        console.log('ID',webSocketConnection.ID,'disconnected. ('+closeReason+';'+description+')');
        webSocketConnection.balRefreshes = 0;
        webSocketConnection.spamcheck = false;
        clients.splice(webSocketConnection.clientIndex, 1);
    }catch(e)
    {
        console.log(e);
    }
});

Basically what I want is to kick all connections with same ID (for example, connecting with multiple browser tabs).
But, instead of kicking the old client, it kicks both clients or in some cases both clients remain connected with same ID.
Is there any other way or is there any mistakes in my script?
Thanks

A: using an object instad of Array to key the clients pool makes it faster and simpler:
var clients = {};

//sample request: ****:8080/?steamid=123456789
var connection;
var aqsteamid = getParameterByName("steamid",request.resource);

connection = request.accept(null, request.origin);

connection.ID = aqsteamid;
connection.balRefreshes = 0;
clients[aqsteamid]=connection;

socket.on('close', function(webSocketConnection, closeReason, description){
    try{
        console.log('ID',webSocketConnection.ID,'disconnected. ('+closeReason+';'+description+')');
        webSocketConnection.balRefreshes = 0;
        webSocketConnection.spamcheck = false;
        delete clients[aqsteamid];
    }catch(e)
    {
        console.log(e);
    }
});

//check if this user is already connected. If yes, kicks the previous client
if(clients[aqsteamid]) clients[aqsteamid].close();
console.log('ID',connection.ID,' connected.');

With an object pool, we can remove all the array pool looping and comparing logic, and our index will never get out of sync.

A: It sounds like multiple connections with the same ID could be part of a genuine workflow with multiple tabs (unlike, say, malicious users that intentionally scrape data w/multiple threads...)
Rather than "kicking" the users from other tabs and then having to deal with them re-connecting, a more elegant solution would be to introduce an orchestration layer across multiple tabs.
You can rely on localstorage api to elect a master tab that will handle communications with the server (doesn't really matter if it's websocket or ajax) and share responses with other tabs - again, through localstorage. It doesn't really matter if you have 1 or 20 tabs open when you can share that data since you care about same message notifications, or stock ticker updates, or whatever.
From another stackoverflow answer:

The storage event lets you propagate data between tabs while keeping a
  single SignalR connection open (thereby preventing connection
  saturation). Calling localStorage.setItem('sharedKey', sharedData)
  will raise the storage event in all other tabs (not the caller):
$(window).bind('storage', function (e) {
    var sharedData = localStorage.getItem('sharedKey');
    if (sharedData !== null)
        console.log(
            'A tab called localStorage.setItem("sharedData",'+sharedData+')'
        );
});

Given the code above, if sharedKey value is already available when the page is loaded, assume a master tab is active and get shared values from localstorage. You can check if a master tab re-election is needed (i.e. that browser tab has been closed or navigated away) with an interval or relying on something more sophisticated like page visibility api.
Note you're not limited to sharing "same" data across multiple tabs but instead batch any requests over a shared channel.


text:
Q: Wrong number of arguments or invalid property assignment error in hp UFT Set ParentObject=Browser("Title:=Sign-In").Page("Title:=Sign-In Home Page")
PropertyRequired="name"
PropertyValue="Agree and Login"
Result="yes"

Function WebButton(ParentObject,PropertyRequired,PropertyValue,Result)
Call ReportResult(Result)
Dim hit
hit=0
   If PropertyRequired="" then
       PropertyRequired="name"
   End If

 If ParentObject.WebButton(PropertyRequired &":="&PropertyValue).exist then
     ParentObject.WebButton(PropertyRequired &":="&PropertyValue).click
     hit=1
 End if

If hit>0 then
    Reporter.reportevent micpass,"The button: "&PropertyValue,"Clicked    sucessfully"
else
    Reporter.reportevent micpass,"The button: "&PropertyValue,"not Clicked sucessfully"
End if
End Function

After I Call this function, then an error " Wrong number of arguments or invalid property assignments" displayed.
Call WebButton(ParentObject,PropertyRequired,PropertyValue,Result)

A: I just executed your piece of code .I dont find any issues .

A: Try using parenthesis when calling Reporter.reportevent so it's like this:
Reporter.reportevent (micpass, "The button: " & PropertyValue, "Clicked sucessfully")


text:
Q: SSIS Error: insert values list doesn't match column list In ssis component OLE DB Command:
insert into D_MAPPING_CLIENTS (ID, DIRECTORY_ID, SOURCE_ID, BASE_ID)
  values (

     case when exists ( select 1 from D_MAPPING_CLIENTS )
           then ( select MAX(ID) + 1 from D_MAPPING_CLIENTS )

         else 1
     end

  , ISNULL(?,
      case when exists ( select 1 from D_MAPPING_CLIENTS )
             then ( select MAX(DIRECTORY_ID) + 1 from D_MAPPING_CLIENTS )

           else 1
       end )

   , ( select ID from D_SOURCES_CLIENTS where SOURCE = 'D:\load\1\clients.txt' )

   , ?)

When I try to save it, i get an error: 'Insert value list does not match column list', although when i run this script in Management Studio it works fine.
What's the problem?
UPD: Where i replace last '?' to some value it works fine :o

A: The problem you are experiencing is a result of one of two things. Either you have not set up the Parameter Mapping in your Execute SQL Task, or not set the BypassPrepare setting in the settings of the same task, which is most likely the case.
I managed to recreate your error, as well as bypass it. The steps I followed are as follows:

*

*Recreated your DB with just those two tables specified in your query. Tested it out with hard-coded values to be certain that it works.

*Added two variables to my package - BaseID & DirectoryID and gave them some default values.

*Created an SQL Execute Task and added your query to the SQLStatement.

*Went to Parameter Mapping and mapped the two variables specifying Parameter names of 0  & 1.
At this point my BypassPrepare option was set to False, running the task resulted in the exact error you are receiving.

*Set the BypassPrepare option to True. Executing the task resulted in success and a row being added to the DB without any problem.

For information about this specific property (used in a different context, but has the same general functionality) see: http://technet.microsoft.com/en-us/library/microsoft.sqlserver.dts.tasks.executesqltask.executesqltask.bypassprepare.aspx

UPDATE
The solution given is for an SQL Execute Task, not for an OLE DB Command. Changing the location of the '?' value parameters in the SQL query to the front as stated by the OP works around this issue.
Another option is to fall back onto calling a Stored Procedure.


text:
Q: AVAssetWriter startWriting Cannot call method when status is 3 I am working with Video filtering.I used GPUImage from
BradLarson. It perfect work on Images, but now I am trying to filter video file from Library it give me error [AVAssetWriter startWriting] Cannot call method when status is 3.
I used IOS7
heare is my code
- (void)viewDidLoad
{
    [super viewDidLoad];
    videoEditingPlayView = [[GPUImageView alloc] initWithFrame:CGRectMake(60,108,200,200)];

    [self.view addSubview:videoEditingPlayView];
}

-(IBAction)btnEffectsClick:(id)sender{
     NSURL *videoURl = [NSURL fileURLWithPath:self.strVideoURl];
    if (movieFile != nil) {
        videoFilter = nil;
       movieFile = nil;
     }
movieFile = [[GPUImageMovie alloc] initWithURL:videoURl];
movieFile.runBenchmark = YES;
videoFilter = [[GPUImageBrightnessFilter alloc] init];
[(GPUImageBrightnessFilter *)videoFilter setBrightness:0.0];
[movieFile addTarget:videoFilter];
videoEditingPlayView.hidden = NO;

GPUImageView *filterView = (GPUImageView *)videoEditingPlayView;
[videoFilter addTarget:filterView];

NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.m4v"];
NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];

movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(480, 360)];
[videoFilter addTarget:movieWriter];

// movieWriter.
movieWriter.shouldPassthroughAudio = YES;
movieFile.audioEncodingTarget = movieWriter;
[movieFile enableSynchronizedEncodingUsingMovieWriter:movieWriter];
[filterView setFillMode:kGPUImageFillModePreserveAspectRatio];
filterView.transform = CGAffineTransformRotate(filterView.transform, 3.14159/2);

double delayToStartRecording = 0.5;
dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, delayToStartRecording * NSEC_PER_SEC);
dispatch_after(startTime, dispatch_get_main_queue(), ^(void){
    NSLog(@"Start recording");
    [movieWriter startRecording];

    **[movieFile startProcessing];** ***if I remove this line then it is working but not dispying video on videoEditingPlayView***

    double delayInSeconds = 30.0;
    dispatch_time_t stopTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(stopTime, dispatch_get_main_queue(), ^(void){
        [filter removeTarget:movieWriter];
        [movieWriter finishRecording];

        [videoFilter removeTarget:movieWriter];

        movieWriter = nil;
        NSLog(@"Movie completed");
    });
});
}

in coding if I remove this line
[movieFile startProcessing];
then app run smoothly, but not displaying video. if I put [movieFile startProcessing] then it crash and give me a error.
I tried this one but can't solved crash.
GPUImage terminates due to [AVAssetWriter startWriting] Cannot call method when status is 3'
https://github.com/BradLarson/GPUImage/issues/1228
Blends with GPUImageView are not giving expected result
GPUImageMovieWriter - crashing with "Cannot call method when status is 2"
And also other.
Thanks.

A: Check your destination file is exist.
If exist, remove the exist file.


text:
Q: Selenium - screenshot with different names I'm using Selenium to grab a screenshot from a list of urls. test.txt include reddit.com, stackoverflow.com and spotify.com. When iterating through this list I want it to save in the folder Screenshots with the file name being the url + '.png'. It does not work though. I'm either getting errors or it just keeps running without doing anything.
This one works but it just overwrites the old one
screenshot = driver.save_screenshot('Screenshots/foo.png')

I want it to look like this but it does not work:
screenshot = driver.save_screenshot('Screenshots/', line,  '.png')

I am new to python but it doesn't work using + instead ' either.
The problem is that it takes too many arguments.
class Screenshot():

filehandle = open("test.txt", "r")
for line in filehandle:
    DRIVER = 'chromedriver'
    driver = webdriver.Chrome(DRIVER)
    driver.get(line)

    screenshot = driver.save_screenshot('Screenshots/foo.png')
    driver.quit()

A: Creating a screenshot class is unnecessary for a simple task like this.
#!/usr/bin/env python
from __future__ import print_function

import os
from selenium import webdriver

def main():
    driver = webdriver.Chrome()

    # With automatically closes files when they go out of scope
    with open('test.txt', 'r') as f:
        for url in f.readlines():
            driver.get(url)

            # os.path.join should make it platform agnostic
            # Also remove any '/' from the url and replace to avoid any file system save issues
            sn_name = os.path.join('Screenshots', url.strip().replace('/', '-') + '.png')
            print('Attempting to save:', sn_name)

            # '.save_screenshot' returns false if it fails so throw exception
            if not driver.save_screenshot(sn_name):
                raise Exception('Could not save screen shot: ' + sn_name)

    # Close browser
    driver.quit()

if __name__ == '__main__':
    main()


text:
Q: Invariant Violation: View config not found for name option (React Native) I'm trying to use this library https://github.com/country-regions/react-country-region-selector for my react native application.
The example code is as follows:
import React from "react";
import { View, Text } from 'react-native';

// note that you can also export the source data via CountryRegionData. It's in a deliberately concise format to
// keep file size down
import {
  CountryDropdown,
  RegionDropdown,
  CountryRegionData
} from "react-country-region-selector";

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { country: "", region: "" };
  }

  selectCountry(val) {
    this.setState({ country: val });
  }

  selectRegion(val) {
    this.setState({ region: val });
  }

  render() {
    const { country, region } = this.state;
    return (
      <View>
        <CountryDropdown
          value={country}
          onChange={val => this.selectCountry(val)}
        />
        <RegionDropdown
          country={country}
          value={region}
          onChange={val => this.selectRegion(val)}
        />
      </View>
    );
  }
}

export default Example;

I changed the divs in the render method into View, which has left me with the current error: Invariant Violation: View config not found for name option.
I'm not sure if this is because the library is intended for React as opposed to React-Native or if there is something else going on that I'm unaware of.

A: This won't work because this library renders HTML, which is not available in react-native. You can confirm this by going to node_modules/react-country-region-selector/src to see the source code.
However, the Picker component in react-native has a very similar API, so you could easily remake this to be compatible. Note that you should not edit files in your node_modules as they will be corrected any time you run yarn / npm. Instead, you should create your own local version of this module.
It's really just a matter of replacing select with Picker and option with Picker.Item and changing the onChange handlers to work with the Picker instead of expecting a DOM event.
You can learn more about the Picker API here


text:
Q: Prolog Define Predicates Define a predicate that converts a number of minutes into the corresponding hours and minutes by recursively subtracting 60 from the number of minutes and incrementing the number of hours. An example of using the rule is:
?- mins_to_hours_and_mins(124, H, M).
H=2 M=4

A: Try this one :) The main idea is to accumulate number of hours in the predicate min by subtracting 60 from total time and when the total time is lower than 60 we can unify counted hours from accumulator with H variable and rest of time with M variable.
minutes(X,H,M):-                     %main predicate
    min(X,0,H,M).

min(X,H,ResultH,ResultM):-           %ending condition of recursion
    X<60,
    ResultH is H,                    %unification with counted hours
    ResultM is X.

min(X,H,ResultM,ResultH):-           %recursive predicate
    X >= 60,
    X2 is X-60, H2 is H+1,           %subtracting from total time
    min(X2,H2,ResultM,ResultH).


text:
Q: How to Sum the same element from different arrays in php? I have arrays like this: array('id'=>value,'id'=>value)
$arrays=array(
    [0] => Array ( [3] => 1, [102] => -1, [15] => 1,)
    [1] => Array ( [5] => 1, [80] => -1 )
    [2] => Array ( [99] => -1, [3] => -1,[5] => 1 )
)

I need to get the total result of a given key. In the above example, if ask for id of 3, the sum is 0, if ask for id of 5, the sum is 2. I can only think of something like this:
  foreach($arrays as $array){
    foreach( $array as $id=>$v){
     if( $id == $asked )
        $total = $total + $v;
    }
  }

Somehow I guess there has to be an efficient way to do the job. I would like to learn. Thanks!

A: Using array_reduce:
$key = 3;

$sum = array_reduce($arrays, function(&$memo, $item) use($key){

    array_key_exists($key, $item) && $memo += $item[$key];

    return $memo;

});

A: foreach($arrays as $array) {
    $total += $array[$id];
}

A:  $prec_array=end($arrays);
 foreach($arrays as $array){
    foreach($array as $id=>$v){
     if(array_key_exists($id, $prec_array) )
            $total[$id] += $v + $prec_array[$id] ;
    $prec_array = $array;
    }
 }


text:
Q: Do not filter outlinks in Nutch? I'm currently trying to perform a deep crawl within a small list of sites. To accomplish this, I updated conf/domain-urlfilter.txt with the domains of the sites I wish to scrape, which worked nicely. However, I found that not only were the links crawled at every step filtered, but the outlinks captured from each page crawled were filtered as well.
Is there a way to avoid filtering captured outlinks while still filtering crawled URLs?


text:
Q: If $V \subset H$ compact, is $L^2(0,T;V) \subset L^2(0,T;H)$ compact too? As the question states, if we have the compact embedding of Hilbert spaces $V \subset H$, is $L^2(0,T;V) \subset  L^2(0,T;H)$ compact too?
If not true in general, is it true for $V=H^1(\Omega)$ and $H=L^2(\Omega)$?

A: You want to know whether the unit ball of $L^2(0,T;V)$ is relatively compact (=has compact closure) in $L^2(0,T;H)$. A readable treatment of relative compactness in Lebesgue-Bochner  spaces is in Tightness, integral equicontinuity and compactness for evolution problems in Banach spaces by Rossi,  and Savaré, see Theorem 1. In a nutshell, you need: boundedness with respect to some Banach space compactly embedded in $H$ (which you have), and integral equicontinuity (which you don't have). Without integral equicontinuity, a counterexample is provided by $f_n(t)=e^{int}\varphi $, where $\varphi$ is any fixed element of $V$.


text:
Q: How to make Glide use previously downloaded image as placeholder Is it possible to show previously downloaded image in Glide as placeholder while downloading new image.
Like I have an image loaded in imageview using glide. Now the imageurl is changed, so while loading this new image is it possible to keep displaying the old image (might be from cache).
What I want is while the new image is being loaded from the URL, is it possible to keep the current image as placeholder.

A: I found the answer to this in the discussion here - https://github.com/bumptech/glide/issues/527#issuecomment-148840717.
Intuitively I also thought of using placeholder(), but the problem is that as soon as you load the second image, you loose the reference to the first one. You can still reference it but it is not safe as it may be reused by Glide or recycled.
The proposed solution from the discussion is to use thumbnail() and load the first image again. The load will return the first image immediately from the memory cache and it will look as if the image did not change until the second image is loaded:
String currentImageUrl = ...;
String newImageUrl = ...;

Glide.with(this)
    .load(newImageUrl)
    .thumbnail(Glide.with(this)
        .load(currentImageUrl)
        .fitCenter()
    )
    .fitCenter()
    .into(imageView);

A: Glide have a capability of getting the bitmap of the image from that url, so just get it and then save it to a desired storage into your phone, and after that in your .placeholder() just use that bitmap when you are trying to get another image , take a look at this snippet
/** Download the image using Glide **/

Bitmap theBitmap = null;
theBitmap = Glide.
    with(YourActivity.this).
    asBitmap().
    load("Url of your image").
    into(-1, -1).
    get(); //with this we get the bitmap of that url

   saveToInternalStorage(theBitmap, getApplicationContext(), "your preferred image name");

/** Save it on your device **/

public String saveToInternalStorage(Bitmap bitmapImage, Context context, String name){

        ContextWrapper cw = new ContextWrapper(context);
        // path to /data/data/yourapp/app_data/imageDir

        String name_="foldername"; //Folder name in device android/data/
        File directory = cw.getDir(name, Context.MODE_PRIVATE);

        // Create imageDir
        File mypath=new File(directory,name_);

        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(mypath);

            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("absolutepath ", directory.getAbsolutePath());
        return directory.getAbsolutePath();
    }

/** Method to retrieve image from your device **/

public Bitmap loadImageFromStorage(String path, String name)
    {
        Bitmap b;
        String name_= name; //your folderName
        try {
            File f=new File(path, name_);
            b = BitmapFactory.decodeStream(new FileInputStream(f));
            return b;
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        return null;
    }

/** Retrieve your image from device and set to imageview **/
//Provide your image path and name of the image your previously used.

Bitmap b= loadImageFromStorage(String path, String name)
ImageView img=(ImageView)findViewById(R.id.your_image_id);
img.setImageBitmap(b);


text:
Q: Xamlreader/writer custom serialisation (dictionary) I'd like to (de)serialize a dictionary collection object with xamlreader and xamlwriter. This is not supported by default in the framework.
Does anyone know how to adapt the following code from https://dzone.com/articles/how-to-serializedeserialize-a-dictionary-object-in-1 designed for the xmlreader to work with the xamlreader?
[XmlRoot("Languages")]
public class LanguageSettings<TKey, TValue> : Dictionary<TKey, TValue>,
                                              IXmlSerializable
{
    public XmlSchema GetSchema() { return null; }
    public void ReadXml(XmlReader reader)
    {
        if(reader.IsEmptyElement) { return; }
        reader.Read();
        while (reader.NodeType != XmlNodeType.EndElement)
        {
            object key = reader.GetAttribute("Title");
            object value = reader.GetAttribute("Value");
            this.Add((TKey)key, (TValue)value);
            reader.Read();
        }
    }
    public void WriteXml(XmlWriter writer)
    {
        foreach (var key in this.Keys)
        {
            writer.WriteStartElement("Language");
            writer.WriteAttributeString("Title", key.ToString());
            writer.WriteAttributeString("Value", this[key].ToString());
            writer.WriteEndElement();
        }
    }
}

This is required for the purpose of serializing a WPF object inherited from a Content into that has a Generic.Dictionary object as a member variable (doing XamlWriter.Save(wpfObject.dictionaryObj) throws an exception that generics are not supported).


text:
Q: How to get PID of started App in C# I have got a few  pairs of the identical apps.
It looks like

Pair 1: App A + App B
Pair 2: App A + App B
and etc

Each App A starts App B from its folder. (They are both at the same folder.)
So I start it like this
Code of App A
Process p = new Process();
p.StartInfo.FileName = FileManager.AppDirectoryName + "\\" + AppB;
p.Start();

And I also stop App B like this.
foreach (Process p in Process.GetProcesses())
{
    if (p.ProcessName == AppB)
    {
        p.Kill();
        return;
    }
}

The problem is that at the same time could be many App B  executing so this method does not allow to detect target App B to kill.
I assume to use PID of App B to kill it.
But I don't know how to obtain PID at the moment to start App B...
Any clue?

A: After starting the app, the Id property on the Process object will indicate the PID of the newly started process
var PID = p.Id;

A: Save a reference to the Process object:
Process p = new Process();
p.StartInfo.FileName = @"c:\windows\notepad.exe";
p.Start();

// ...

p.Kill();

or remember its PID:
Process p = new Process();
p.StartInfo.FileName = @"c:\windows\notepad.exe";
p.Start();

long pid = p.Id;

// ...

Process.GetProcessById(pid).Kill();


text:
Q: jQuery datepicker language (Localization) How to change between languages I'm trying to set the location to my jQuery UI calender, but it doesn't work.
Those are my links:
Header View File: header1.php

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" href="<?php echo base_url("assets/testelib/jquery-ui.min.css"); ?>">

Those are the example files used in the jQuery online example that I did download and I'm trying to generate the result.
https://jqueryui.com/datepicker/

Languages downloaded now right from:
https://github.com/jquery/jquery-ui/tree/master/ui/i18n

and the VIEW file: register1.php

Date: <input type="text" id="datepicker">
 <select id="locale">
<option value="de" selected="selected">Deutsch (German)</option>
<option value="">English</option>
<option value="fr">French (Français)</option>
<option value="pt-BR">Portugues BR</option>
</select>

What am I doing wrong please? The calendar shows only the date and etc with the default language (English).

A: This was fun, not having used this before.
I ended on going to https://jqueryui.com/download/ and grabbed the 1.12.1 jquery version with everything just for fun later...
So from that download I grabbed the jquery.js and jquery-ui.min.js and put those in my assets folder (see the paths I used, but yours will be fine).
My Test View File - Call it what you like...

Date: <input type="text" id="datepicker">
    <select id="locale">
        <option value="de" selected="selected">Deutsch (German)</option>
        <option value="en">English</option>
        <option value="fr">French (Français)</option>
        <option value="pt-BR">Portugues BR</option>
    </select>

FYI - I assign the DOM element to a variable and then refer to it... which is where let domDatePicker = $("#datepicker"); comes from.
From what I experienced (my tinkering) it appears that you need to initialise the datepicker first. i.e. domDatePicker.datepicker(); or else nothing appears until you make a selection which seems odd, when using Google Chrome on Linux.
Anyway hope that gets you closer to something working wonderfully well.


text:
Q: Making Keepass work (seamlessly) under Windows I'm searching for a recipe to make Keepass work under Windows (Windows 7 professional 64). My definition of "work" is that it saves/fills in passwords in the browser (via Keefox extension), and that I do not otherwise see it. It is the last part which is keeping me busy.
In particular, I do not want to enter an extra password (in addition to my login password) every time I turn on or reboot the computer, which also requires me to click in the window first... because for some ingenious idea the window that pops up doesn't have keyboard focus.
What I have tried so far:

*

*Settings: Remember and automatically open last used database, automatically save when closing, automatically search key files, remember directories and key sources, minimize to tray, mimimize after opening database.

*Save database with no password.
This prompts me for a password. Empty password works, of course, but I still have to confirm it every time.

*Save database with password.
Same as above, except I actually have to enter a password, which is worse.

*Add a keyfile in the same directory as the database.
Instead of confirming an empty password, I now have to confirm opening that keyfile. Which is basically the same thing.

*Use Windows credentials. That sounds like it's just made for the purpose! Unluckily, you guessed it, this requires me to confirm "Use Windows credentials" every single time.

*Save database with the password "password" and edit the Run registry entry that Keepass sets to keepass.exe -pw "password". That didn't work, still get prompted.

*Edit the Run registry key to either keepass.exe -keyfile:keyfile.txt or use the -preselect option instead. One of them actually worked once (I forgot which one, playing around and trying so much), but then again didn't work the next day, apparently Keepass overwrites the registry key on the next occasion (looking at it now, the registry key no longer contains any commandline options).

What I want is to have the passwords stored locally, and I want to be able to backup the database and copy it from the desktop computer to my laptop (which, although it seems like a trivial thing, is not really all that trivial with the browser's builtin password store).
That's really all I need. If there's some encryption involved so the database is not immediately readable with the naked eye in a text editor, then that's fine with me, but it doesn't really add any value.
I am fine with the database not being protected by any explicit password or the Windows login being the only security measure. I am fine with anyone logging in successfully with my username being able to access all browser passwords. No worries there.

A: I just tested the following, and it works fine:
"C:\path\to\keepass.exe" --keyfile:"C:\path\to\keyfile.key" "C:\path\to\database.kbdx"

I think the main difference to what you tried is the colon (:) between the argument name and value, rather than a space.
You can also use --pw:"password" if you prefer, but a keyfile is marginally safer in this configuration.
Save that in a batch file to run it more easily, e.g. mykeepass.bat
Command-line options are documented here: http://keepass.info/help/base/cmdline.html, or run keepass.exe --help.


text:
Q: Geometry Math 8th (Area of a Trapezoid) The windshield in a truck is in the shape of a trapezoid. The lengths of the bases of the trapezoid are 70 inches and 79 inches. The height is 35 inches. Find the area of the glass in the windshield.

A: The formula for the area of a trapezoid is $\dfrac {a+b}2\times h$, so that becomes $\dfrac {149}2\times35 = 2,607.5$inches$^2$

A: The average of the two bases is 74.5, and I multiply that by the height which is 35 to get 2607.5 inches.


text:
Q: Closed, convex curves with minimized lengths Let $\gamma$ be closed, smooth, strictly convex curve. It is known that we can find a special linear transformation $A\in SL(2)$ so that the length of $A\gamma$ is minimized.
I am interested in knowing of a test/ criteria $(\ast)$ that if a given closed, smooth, strictly convex curve $\gamma$ satisfies $(\ast)$, then its length must be already minimized; that is, we do not need to apply any special linear transformation to $\gamma$ to reach the minimum length.
In terms of the support function, I have the following necessary conditions that $\gamma$ must satisfy. Before stating the conditions, let me first define the support function of $\gamma.$ The support function of a smooth, strictly convex, closed curve $\gamma$ is defined by $h(\theta)=\langle x, (\cos \theta, \sin \theta) \rangle,$ where $x$ is the point on $\gamma$ with the outer unit normal $(\cos \theta, \sin \theta)$ and $\theta\in[0,2\pi]$ (It then follows that $x=(h\cos\theta -h_{\theta}\sin\theta,h\sin\theta+h_{\theta}\cos\theta)$ and thus we have a parametrization of $\gamma$ over the unit sphere $\mathbb{S}^1$ identified with $[0,2\pi]$.). It is also known that the length of $\gamma$ can be expressed as follows
$$L(\gamma)=\int_{0}^{2\pi}h~d\theta.$$
Now the conditions: if $L(A\gamma),~A\in SL(2),$ is minimized for $A=I$, then
$$0=\int_{0}^{2\pi}D_{L_i}hd\theta,i=1,2~~~(\ast)$$
where $L_1=\left(
  \begin{array}{cc}
   1  &  0\\
    0 &  -1\\
  \end{array}
\right)
$ and $L_2=\left(
  \begin{array}{cc}
   0  &  1\\
    1 &  0\\
  \end{array}
\right)
$. Note $L_1,L_2$ are the generatores of the Lie group of $SL(2).$ Here, I should say
$$D_{L_i}h=\langle L_ix^T, (\cos \theta, \sin \theta)\rangle.$$
Doing some calculations $(\ast)$ implies that $\int_0^{2\pi}h\cos2\theta d\theta=\int_0^{2\pi}h\sin2\theta d\theta=0.$
Now my questions are:
1- given a curve $\gamma$ satisfying $(\ast)$, is it true that the length of $\gamma$ is already minimized?
2- generally, given $\gamma,$ can I explicitly find an $A\in SL(2)$ such that the length of $A\gamma$ is minimum?
3- what is the direct generalization to higher dimensions for hypersurfaces? (I know this last question is very vague)

A: The paper by C.M. Petty "Surface area of a convex body under affine transformations" gives a necessary and sufficient conditions that a convex body has minimal surface area among its affine transforms of the same volume. This, in particular, answers my questions asked above. The paper explicitly states in section 3 that the condition $\ast$ given above is necessary and sufficient. Equivalently, if the second Fourier coefficient of the support function are zero then the length is minimized.

A: Your condtion $(*)$ is certainly not sufficient for the global minimum: There could be several local extrema of the length, and all of them satisfy $(*)$. In the following I look at the problem in my pedestrian way. It then becomes clear that the global minimum has to be found numerically.
Let the curve $\gamma$ be given by
$$\gamma:\quad z(\phi)=p(\phi)u(\phi)+\dot p(\phi)\dot u(\phi)$$
with $u(\phi):=(\cos\phi,\sin\phi)$. Then
$$\dot z=(p+\ddot p)\dot u=\rho\dot u\ ,$$
whereby $\rho:=p+\ddot p$ denotes the radius of curvature. We now introduce a linear map $A\in SL(2,{\mathbb R})$ that transforms the curve $\gamma$ into the curve
$$\gamma_A:\quad w(\phi):=Az(\phi)\ .$$
In order to compute the length of $\gamma_A$ we have to look at
$$|\dot w|=\rho \sqrt{\langle A\dot u,A\dot u\rangle}\ .\tag{1}$$
Now $\langle A\dot u,A\dot u\rangle=\langle A'A\dot u,\dot u\rangle$. The matrix $A'A$ is symmetric, whence can be written in the form $A'A=T^{-1}DT$, where $D={\rm diag}\bigl(\lambda,{1\over\lambda}\bigr)$ with $\lambda\geq1$, and $T$ is a rotation matrix. Instead of $(1)$ we now have
$$|\dot w|=\rho \sqrt{\langle DT\dot u,T\dot u\rangle}=\rho \sqrt{\lambda\cos^2(\phi+\alpha)+{1\over\lambda}\sin^2(\phi+\alpha)}\>d\phi\ .$$
The length of $\gamma_A$ is therefore given by
$$L(\gamma_A)=\int_0^{2\pi}\rho(\theta-\alpha)\sqrt{\lambda\cos^2\theta+{1\over\lambda}\sin^2\theta}\>d\theta\ .$$
Looking at this formula I get the impression that we can minimize over $\alpha$ once and for all, independently of $\lambda$. This has to do with the partcular symmetries of the large surd. In a second step one would then find the optimal $\lambda$.


text:
Q: Yii2 params access within local config file in common directory I'm using Yii2 advanced template,
I want to access params.php in main-local.php file,
I called this ways:
main-local.php:
'mailer' => [
            'class' => 'myClass',
             'apikey' => \Yii::$app->params['mandrill_api_key'],
             'viewPath' => '@common/mail',
        ],

and I have stored this mandrill_api_key in params.php
params.php:
<?php
return [
    'adminEmail' => 'admin@example.com',
    'supportEmail' => 'support@example.com',
    'user.passwordResetTokenExpire' => 3600,
     'mandrill_api_key' => 'mykey'
];

I'm getting this error:

Notice: Trying to get property of non-object in C:\xampp\htdocs\myproject\common\config\main-local.php on line 25

What should I do to access these parameters?

A: The config files are read before the application is instantiated as explained in the request lifecycle:

*

*A user makes a request to the entry script web/index.php.

*The entry script loads the application configuration and creates an application instance to handle the request.

*The application resolves the requested route with the help of the request application component.

*...

As such \Yii::$app does not yet exist hence the error. I would suggest moving your api_key definition to the main-local.php config such that there is no confusion over where it is being set:
'mailer' => [
    'class' => 'myClass',
    'apikey' => 'actual api key',
    'viewPath' => '@common/mail',
],

Alternatively, you can use Yii2's dependancy injection container to set the apikey in your application's entry script:
...
$app = new yii\web\Application($config);
\Yii::$container->set('\fully\qualified\myClass', [
    'apikey' => \Yii::$app->params['mandrill_api_key'],
]);
$app->run();

A: You can just do
$params['mandrill_api_key']

you dont need to use
\Yii::$app->params['mandrill_api_key']

A: The params is a part of config and you can not call this in your config .
the best way for handel this you can use this in your class :
myClass:
class myClass extends ... {

    public $apikey;

    public function __construct(){
        $this->apikey =  \Yii::$app->params['mandrill_api_key'];
    }

}


text:
Q: Differing char spacing in a WPF RichTextBox I have a custom control I have made.  It extends a RichTextBox.
I have code that sets the width of the Document so that the number of chars is limited.  (I am using Courier New, so I have a fixed width font.)
This all works fine.
But once I put the control in my application, the limit starts failing.  After comparing the two, I noted that the spacing between my test application and my real application is different.
Here is an example:

As you can see my spacing for the Test App is larger than the spacing for the Real App.
I don't have any any spacing, kerning, typography or gliph settings (that I can find) in either app.  Also, I have checked every setting starting with "Font" (FontSpacing, FontSize...) they are all exactly the same.
What else could cause the text to apply different spacing in one app as opposed to another?
NOTE:
In case it is relevant, the xaml that inserts the control into my test app is the same as the xaml that inserts the control into my real app.  I will post it if someone wants to see it.

A: It probably has to do with the differences between the Ideal and Display TextFormatting Modes. See this SO Question for a good explanation from Hans.