text:
Q: Is the complex space $\mathbb C\times \mathbb C$ a field? Is the complex space $\mathbb C\times \mathbb C$ a field?
If not, which axiom that defines field doesn't hold?

A: Presume you are performing addition and multiplication component-wise, i.e.
$$(x_1, y_1)+(x_2, y_2)=(x_1+y_1, x_2+y_2)$$
$$(x_1, y_1)(x_2, y_2)=(x_1y_1, x_2y_2)$$
In that case, the role of multiplicative unity ("one") is played by $(1,1)$:
$$(1,1)(x,y)=(1x, 1y)=(x,y)$$
and the role of additive unity ("zero") is played by $(0,0)$:
$$(0,0)+(x,y)=(0+x, 0+y)=(x,y)$$
However, look at the element $(1,0)$. It is not zero, but it hasn't got a multiplicative inverse, because there is no pair $(x,y)$ such that $(1,0)(x,y)=(1,1)$ - simply because $0y=0\ne 1$ for every $y$.
So, $\mathbb C\times\mathbb C$ is not a field because there are non-zero elements which don't have a multiplicative inverse.

A: Just to add to @StinkingBishop's answer, the reason it starts with "Presume you are adding..." is this:
The cardinality of $\Bbb C \times \Bbb C$ is the same as that of $\Bbb R$, i.e., there exists some bijection $f$ from the first to the second, with inverse I'll call $g$ to save typing. If you define
$$
(a,b) \oplus (c, d) = g\left( f(a, b) + f(c, d) \right)
$$
and
$$
(a,b) \odot (c, d) = g\left( f(a, b) \cdot f(c, d) \right)
$$
then $\Bbb C \times \Bbb C$ actually is a field with the addition and multiplication operations $\oplus$ and $\odot$.
The broader implication of this contrived example is that it generally doesn't make sense to ask "Is such-and-such a set actually a field?" without specifying the operations you're considering.
There are special cases, however, where an intermediate kind of question makes sense. You can ask "Is there a multiplication operation $\otimes: S^2 \times S^2 \to S^2$ on the 2-sphere that makes the 2-sphere into a group, and in which $\otimes$ is a differentiable function?" In this case, you haven't specified what the operation is, but you have put some restriction on it. (Answer: it turns out that there's no such "multiplication", but it's not all that easy to prove.)

A: John Hughes, I see what you mean. You are basically re-writing the elements of the set $\mathbb R$ using the elements of the set  $\mathbb C\times \mathbb C$ (which is possible as they have the same cardinality). Then you multiply and add the new elements just as if they still were in $\mathbb R$. This clearly makes $\mathbb C\times \mathbb C$ a field with respect to new fancy operations.
But I am confident Karen was meaning exactly what Stinking Bishop assumed. If I were an instructor who plans to include this in homework, I would necessarily mention that point.


text:
Q: Undefined array key 1 Laravel I am having this problem in visualizing, through a card, the elements present in the db.
This is the controller:
Controller.php

    class PublicController extends Controller
    {
        public function homepage(){
            $articles = Article::all();
            //dd(compact('articles'));
            return view('welcome', compact('articles'));
        }

    }

and this is the view:
welcome.php

    @foreach {$articles as $article}

{{$article->title}}

Card subtitle

{{$article->description}}

                            Card link
                            Another link

                    @endforeach

This is the error that appears to me:
Undefined array key 1

A: You are using the wrong type of brackets/parentheses here:
@foreach {$articles as $article}

It should be like this:
@foreach ($articles as $article)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to validate multiple form fields in MySQL with PHP? I was trying to build a login form, where the user has to add this data in a form: first name, last name, studentnumber and email.
I have a test user in my MySQL database, but so far it's not working. Here's my code:
<?php
//Start session//
session_start();

//Include database connection file and header file//
include_once('resources/includes/database.inc.php');
include_once('header.php');

?>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//Escape de gebruikersnaam
$sFirstName = mysql_real_escape_string($_POST['firstname']);
$sLastName = mysql_real_escape_string($_POST['lastname']);
$sStudentNumber = ($_POST['studentnumber']);
$sEmail = ($_POST['email']);
$sSQL = 'SELECT `id`, `firstName`, `lastName`, `studentNumber`, `email`, `accepted` FROM   `student` WHERE `firstName` = \'' . $sFirstName . '\'';
$rsSQL = mysql_query($sSQL);
$aUser = mysql_fetch_array($rsSQL);
  //Er is geen rij gevonden en $aUser is false:
//Dat betekent dat er geen user is met de opgegeven gebruikersnaam
if($aUser == false)
{
    echo 'Deze gebruiker is niet gevonden';
}
//Vergelijk de rest
elseif($aUser['lastname'] != $sLastName)
{
  echo 'De achternaam is niet bekend';
}

elseif($aUser['studentnumber'] != $sStudentNumber)
{
    echo 'Het studentnummer is niet geldig';
}

elseif($aUser['email'] != $sEmail)
{
  echo 'Het e-mailadres is niet bekend';
}

//Inloggen gelukt
else
{        //De combinatie is goed, maak de sessie aan
    $_SESSION['login_user'] = $aUser['id'];

    //Verstuur de gebruiker door
    header("location: studentloggedin.php");

    //Mocht de redirect hierboven niet werken:
    echo 'Je bent ingelogd, klik hier om door te gaan.';
}
}
?>

<form method="post">

  Voornaam
  <input type="text" name="firstname" />

  Achternaam
  <input type="text" name="lastname" />

  Studentnummer
  <input type="text" name="studentnumber" />

  Email
  <input type="text" name="email" />

  <input type="submit" value="Inloggen" />

</form>
<?php
$html = file_get_contents('resources/templates/homecontent.template.html');
print $html;
include_once('resources/templates/footer.template.html');
?>

Anyone knows what I'm doing wrong? If I fill everything in correctly according to my database user, I get: 'De achternaam is niet bekend' (Last name isn't recognized). Perhaps I should check the validation in the MySQL query?

A: Array keys are case sensitive.
$aUser['lastname'] != $aUser['lastName']
You also should move away from mysql_ as the MySQL API is deprecated.  Use PDO or MySQLi with prepared statements to avoid SQL injections.  Right now, your query is open to injections using a $_POST variable directly in the query.
For debugging purposes, I suggest you print out the array if you're having trouble in the future using: print_r($aUser).  It may have saved you a trip here.


text:
Q: How to save specific users answers in JSFiddle This is probably a dumb question and probably not possible but what I am looking to do is I have created an NHL drop and drag board on JSFiddle for my friends and I. Is there a way to have their answers saved so if they click back on the fiddle their results will still be shown from their last use.
This is what i'm using for the drag and drop
$(function() {
  $(".draggable").draggable();
   $(".item").droppable({
    drop: function(event, ui) {
      var $this = $(this);
      $this.append(ui.draggable);

      var width = $this.width();
      var height = $this.height();
      var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
      var cntrTop = (height / 2) - (ui.draggable.height() / 0.50);

      ui.draggable.css({
        left: cntrLeft + "px",
        top: cntrTop + "px"
      });
    }
  });
});

This is the link to the fiddle
http://jsfiddle.net/NickBonino/537wtvjv/2/
I just want it so that when they drag and drop their players to the left, the next time they come back to view the fiddle their response should still be there
Thanks everyone.


text:
Q: Problem with Date & time format on server I'm having a problem trying to filter a list between 2 dates. I have a solution running on our local machine .NET 3.5. The solution runs fine without any errors. But when I put it on our server (2008) I get
System.FormatException: String was not recognized as a valid DateTime.
I can recreate the problem locally if I change my machines date/time format from English (United Kingdom) to English (United states).
The problem is I've set the server setting to exactly the same as the local solution and I am still getting the errors.
The code involved is
public DateTime StartDate
    {
        get
        {
            if (this.ViewState["StartDate"] != null)
            {
                return DateTime.Parse(this.ViewState["StartDate"].ToString());
            }
            else { return DateTime.Today.AddYears(-1); }
        }
        private set
        {
            this.ViewState["StartDate"] = value.ToString();
        }
    }

    public DateTime EndDate
    {
        get
        {
            if (this.ViewState["EndDate"] != null)
            {
                return DateTime.Parse(this.ViewState["EndDate"].ToString());
            }
            else { return DateTime.Today; }
        }
        private set
        {
            this.ViewState["EndDate"] = value.ToString();
        }
    }

Please help!

A: Use ParseExact.  This will allow you to specify a date format, irrespective of the machine's locale.
Lots of questions on Stack Overflow.
.NET Parsing string into DateTime

A: Hej, try specifying the culture info to the DateTime.Parse method, ex:
DateTime.Parse(dateString, new CultureInfo("en-US", false))

more here http://msdn.microsoft.com/en-us/library/1k1skd40.aspx


text:
Q: Install VBOX guest additions on Debian Testing Is there a way to install the Virtualbox's guest additions on Debian Testing ? When I try the 'classic way', I get this message :

Building the main Guest Additions module ...fail!
  (Look at /var/log/vboxadd-install.log to find out what went wrong)

/var/log/vboxadd-install.log :

/tmp/vbox.0/Makefile.include.header:97: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR= and run Make again. Stop.

A: you need to have the kernel-headers installed, e.g.
$ sudo aptitude install linux-headers-amd64

this will install the default linux-headers, if you have a non-default kernel, you need to install the matching headers.

A: I was able to get them installed by the following.
apt-get install dkms build essential

then with "Guest Additions CD image" inserted.
sh /media/cdrom/VBoxLinuxAdditions.run

Reboot and guest additions worked fine.

A: I tried everything possible to use guest additions when using ubuntu as guest and never got it working. As soon as I installed ubuntu, guest additions installed without a hitch

A: You should try the following command.
sudo yum install kernel-devel
sudo yum upgrade

and then restart you virtual machine.
This methods works for me best.

A: First you need to install kernel packages like other said.
If you use a graphical destop.You must switch to root user to run VBoxLinuxAdditions.run.
It's worked on centos7 with virtualbox5.1.28.

A: These are the steps I use to install the guest additions:
sudo bash
apt-get install build-essential module-assistant
module-assistant prepare

<change directory to wherever you have the Guest Additions CD mounted>

sh VBoxLinuxAdditions.run

It's probably best to reboot after installing the guest additions, so the modules can load themselves properly.
This should work on any Debian-based distro.  I know it works on at least Debian (Wheezy -> Stretch, and possibly back to Sarge) and Ubuntu 10.04 -> 17.10.


text:
Q: Ошибка google is not defined При вызове функции initMap(), которая загружает карту выдаёт ошибку
google is not defined.
функция:
function initMap(lat, lng, radius) {
    var myLatlng = new google.maps.LatLng(lat, lng);
    map = new google.maps.Map($("#map"), {
        center: myLatlng,
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
        var circle = new google.maps.Circle({
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35,
            map: map,
            center: myLatlng,
            radius: radius,
            editable: true

        });

    google.maps.event.addListener(circle, 'radius_changed', function() {
        $("#radius").attr("value", circle.getRadius() * 0.001);
    });

    google.maps.event.addListener(circle, 'center_changed', function() {
        $("#google_lat").attr("value", parseFloat(circle.getCenter().lat()));
        $("#google_lng").attr("value", parseFloat(circle.getCenter().lng()));
        $("#lat_out").html(circle.getCenter().lat());
        $("#lng_out").html(circle.getCenter().lng());
    });

    $("#radius").keyup(function(){
        temp_radius = parseFloat(($(this).val()) * 1000);
        circle.setRadius(temp_radius);
    });

    $("#radius").ready(function(){
        $("#radius").val(5);
    });

    $('#apply').click(function () {
        $("#wrap_for_map").attr('hidden', true);
        $("#google_lat").val(parseFloat(circle.getCenter().lat()));
        $("#google_lng").val(parseFloat(circle.getCenter().lng()));
        $("#google_radius").val(parseFloat(circle.radius));
    });

    $('#cancel').click(function cancel() {
        $("#wrap_for_map").attr('hidden', true);
        $("#google_lat").val(null);
        $("#google_lng").val(null);
        $("#radius").val(null);
        $("#google_radius").val(null)
        $('#lat_out').html('');
        $('#lng_out').html('');
    });
}

вызывается первый раз при загрузке страницы:
$(document).ready(function () {
    var google_lat = $("#google_lat").val();
    var google_lng = $("#google_lng").val();
    initMap(google_lat, google_lng, temp_radius);

A:
а разве эта функция принимает jQuery объект? new google.maps.Map – Grundy 4 минуты назад

Да, действительно ошибка была из за этого
исправил на map = new google.maps.Map(document.getElementById("map"), и заработало


text:
Q: How to route class component by clicking button in React? I am new to React. I am trying to build a page and having like 3 button or img on main page. When I click either one, I shall be routed to another class component. You can treat it like click the icon and route you to another category page (just an example). Below is my structure and partial code I tried. I have no idea how to achieve that, and I googled and seems cannot find the stuff I want.
Structure:
/src
  .index.js
  .App.js
  .BookStore.js
  .FruitStore.js
  .FoodStore.js

index.js
import React from "react";
import { render } from "react-dom";
import App from "./App";

render(
    <App />,
    document.getElementById('root')
);

App.js:
import React from "react";
import BookStore from "./BookStore";

const AppContainer = () => {
    return (
        //do the routing
        <BookStore/>
    )
};

export default AppContainer;

BookStore.js
export default class BookStore extends React.Component {
}
const contentDiv = document.getElementById("root");
const gridProps = window.gridProps || {};
ReactDOM.render(React.createElement(BookStore , gridProps), contentDiv);

A: First, you could have a look at the/one react router, e.g. https://reactrouter.com/web/guides/quick-start
However, since you're writing you're new to react, this might be a little too much ...
First, I was wondering why you're using the "ReactDOM" in your indexjs (that seems to be correct), but also in the BookStore.js. I would also recommend to write your components as functions, like your "AppContainer" and not use the class components anymore (or do you really need to do that? - why?). You can use hooks instead to have e.g. state in the components.
You would then need any kind of state in your AppContainer which is used for the routing. Maybe like this:
const AppContainer = () => {
    const [showDetail, setShowDetail] = useState();
    return <>
        {!showDetail && <BookStore onDetail={detail => setShowDetail(detail)} />}
        {showDetail && <DetailPage detail={showDetail} onBack={() => setShowDetail(undefined)}}
    </>
}

Your AppContainer then has a state wheter or not to show the Bookstore (which is shown when "showDetail" is falsy, or a DetailPage which is shown when showDetail is truthy.
For this to work, your Bookstore needs to provide callbacks to let the AppContainer know that something should change. Very simply it could look like this:
const BookStore = ({onDetail}) => {
    return <button onClick={() => onDetail("anything")}>Click me</button>
}

Now when someone clicks the button on the bookstore, it calls the "onDetail" callback, which was set in the AppContainer to set the "showDetail" state. So this one will be updated to "anything" in this case. This will result in a rerender on the AppContainer which will now render a DetailPage component instead.


text:
Q: Writing a regular expression with decimal values I need to write a regular expression for use in Google Course Builder. The expression needs to  accept 22.69 - 23 inclusive.
The decimals are beating me! Help would be greatly appreciated. Google Course Builder uses expressions in this format: \b0*(2[89]|[34][0-9]|50)\b

A: If I break it down, I think you are looking for these matches:
 \b0*(22\.69[0-9]*|22\.[7-9][0-9]*|23|23\.0*)\b

That is:
22.69
22.7*
22.8*
22.9*
23
23.0...

Does that regex work for your use?  Also, I'm not sure which regex it is, you might need to escape the decimal.


text:
Q: MongoDB Rolling calculations So I haven't used MongoDB in a long time, was wondering if there are any built in ways (or plugins) to help keep tracking of various calculations without having to do the work manually.
For example...
Product schema
<id>
<product name>

Reviews schema
<id>
<product_id>
<score>

If I want to keep track of the average score so I can query/sort very quickly (without having to calculate it every query) I was planning to add to the Product schema something like
<reviews.score.sum>
<reviews.score.median>
<reviews.score.count>

That would save the DB a lot of work obviously when trying to query products where the average review > X. Or finding the top X products by most reviews.
But then I would have to do the math / calculations work on every change. Is there any built in ways to have MongoDB auto calculate some of these common math operations on document change? Or do I need to do it manually/look into some other time series/analytical DB?


text:
Q: How to do multiple map operations with the same value using Java stream? I have a "root" list which contains objects with different lists inside. I have it now divided in 3 operations but i think it could be done using only one so i wouldn't repeat code. Is it possible?
List<Prices[]> pricesList = new ArrayList<Prices>();
List<Instructions[]> instructionsList = new ArrayList<Instructions>();
List<Sizes[]> sizesList = new ArrayList<Sizes>();

/* storesList contains a list of Stores which each of them has
   inside a list of prices, instructions and sizes.
   I want join all of that individual lists into a single one.*/
 storesList.stream()
                .map(Devices::getDevicesSubtype)
                .filter(Objects::nonNull)
                .map(subtype -> (MobileSubtype) subtype)
                .map(MobileSubtype::getPrices)
                .forEachOrdered(list -> pricesList.add(list));

storesList.stream()
                .map(Devices::getDevicesSubtype)
                .filter(Objects::nonNull)
                .map(subtype -> (MobileSubtype) subtype)
                .map(MobileSubtype::getInstructions)
                .forEachOrdered(list -> instructionsList.add(list));

storesList.stream()
                .map(Devices::getDevicesSubtype)
                .filter(Objects::nonNull)
                .map(subtype -> (MobileSubtype) subtype)
                .map(MobileSubtype::getSizes)
                .forEachOrdered(list -> sizesList.add(list));

/*How could i not repeat this part of the code and do the 3 for each ordered?*/
storesList.stream()
                .map(Devices::getDevicesSubtype)
                .filter(Objects::nonNull)
                .map(subtype -> (MobileSubtype) subtype)

A: Regarding your actual code, I'd suggest one forEach before mapping to a specific category, then add in each list
storesList.stream()
        .map(Devices::getDevicesSubtype)
        .filter(Objects::nonNull)
        .map(subtype -> (MobileSubtype) subtype)
        .forEachOrdered(subtype -> {
            pricesList.add(subtype.getPrices());
            instructionsList.add(subtype.getInstructions());
            sizesList.add(subtype.getSizes());
        });

Note : classes should be name at singular if there represent only one element, is Prices is one price, it should be name Price to avoid confusion, same for Instructions and Sizes


text:
Q: Is it always true that $P(A \cap B) = P(A) + P(B) - P(A \cup B) $? I saw this equation in a solution to a question, but maybe it's taken out of context. I didn't see this equation mentioned in the textbook.
So is the above equation always true?

A: $$\text{You must be very familiar with the equation}\;\;P(A \cup B) = P(A) + P(B) - P(A \cap B)$$
$$P(A \cap B) = P(A) + P(B) - P(A \cup B)\;\;\text{is just the same equation rearranged}$$


text:
Q: Hide items that do not have class I am trying to hide(); all of the sub-item's if the child sub-list does not have the active class. The sub-list receives the active class if it belongs to the selected main category (click Main1 or Main 2)
I tried this code without success:
var item = $(".sub-list");

if (!$(item).hasClass("active")) {
  $(item)
    .closest(".sub-item")
    .hide();
} else {
  $(item)
    .closest(".sub-item")
    .show();
}

In the code snippet, the sub-items do not hide(); even when the sub-list receives the active class. How do I hide all of the sub-items that have the active class?

$(document).ready(function() {
  function toggleSubcatDiv(input, showTypeList) {
    var $list = $(input).closest(".post-item");
    $list
      .find(".sub-list")
      .filter(".active")
      .removeClass("active")
      .end()
      .filter('[data-for="' + $(input).attr("name") + '"]')
      .addClass("active");
  }
  $(this).on("click click.init", ".cat-item", function(e) {
    var $menu = $(this).closest(".cat-dropdown");
    var item = $(".sub-list");
    if (!$(item).hasClass("active")) {
      $(item)
        .closest(".sub-item")
        .hide();
    } else {
      $(item)
        .closest(".sub-item")
        .show();
    }
    $menu
      .find(".title")
      .children(":checkbox")
      .prop("checked", true)
      .next("span")
      .text($(this).text())
      .css("color", this.style.color);
    toggleSubcatDiv($(":radio", this), "init" !== e.namespace);
  });
});
.sub-item {
  min-height: 10px
}

.sub-item input {
  display: none
}

.cat1 {
  border: 2px solid blue;
}

.cat2 {
  border: 2px solid red;
}

.sub-list:not(.active) {
  display: none;
}

  Main Category:

<input type="checkbox"> Choose...

<input type="radio" name="cat1">Main 1

<input type="radio" name="cat2">Main 2

  Sub Category:

<input class="sub-input" id="comp" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha" fill="blue" d="M21.72 16.784a.094.094 0 0 0-.071-.033H3.351a.094.094 0 0 0-.093.108c.003.017.279 1.711 2.421 1.711h13.642c2.142 0 2.418-1.694 2.42-1.711a.095.095 0 0 0-.021-.075zm-7.844 1.193h-2.752v-.633h2.752v.633zM5.252 16.092h14.496c.21 0 .38-.17.38-.38V6.81a.38.38 0 0 0-.38-.38H5.252a.38.38 0 0 0-.38.38v8.904c0 .21.17.38.38.38zM6.2 7.758h12.598v7.006H6.201V7.758z"/></svg>
Main 1A

<input class="sub-input" id="ticket" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha2" fill="blue" d="M7.519 14.008l3.473 3.473 6.372-6.372-3.473-3.473-6.372 6.372zm13.884-4.77L19.925 7.76a1.98 1.98 0 0 1-2.686-2.686l-1.477-1.477a.992.992 0 0 0-1.4 0L3.597 14.362a.992.992 0 0 0 0 1.4l1.478 1.478a1.98 1.98 0 0 1 2.685 2.686l1.478 1.477a.993.993 0 0 0 1.4 0l10.765-10.765a.993.993 0 0 0 0-1.4zM10.992 19.07L5.93 14.008l7.962-7.96 5.06 5.061-7.96 7.96z"/></svg>
Main 1B

<input class="sub-input" id="elephant" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha3" fill="red" d="M19.565 9.341h-4.086a4.636 4.636 0 0 1-1.67 3.027.476.476 0 0 1-.672-.067.478.478 0 0 1 .066-.674 3.684 3.684 0 0 0 1.354-2.858 3.7 3.7 0 0 0-3.695-3.695A3.7 3.7 0 0 0 7.188 8.38a3.448 3.448 0 0 0-.86.702c-.826.936-1.008 2.16-1.008 3.053 0 .382.01.765.02 1.135.03 1.11.066 2.493-.3 2.87-.029.029-.115.117-.422.117a.957.957 0 1 0 0 1.914c.74 0 1.343-.234 1.793-.696.6-.617.795-1.505.846-2.513.113.003.234.005.36.005.955 0 2.245-.115 3.266-.627 0 0-.07.442-.07.568v3.807c0 .68.643 1.211 1.325 1.211h.018c.682 0 1.23-.53 1.23-1.21v-1.96h4.544v1.975c0 .672.565 1.195 1.237 1.195h.018c.672 0 1.197-.523 1.197-1.195v-2.182c.598-.3.957-.898.957-1.586v-3.828c0-.99-.783-1.794-1.774-1.794zM7.189 12.107a.451.451 0 1 1 .902 0 .451.451 0 0 1-.902 0z"/></svg>
Main 2A

<input class="sub-input" id="hook" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha4" fill="red" d="M13.587 16.6h1.829c-.254 1.303-1.405 2.31-2.772 2.31a2.836 2.836 0 0 1-2.823-2.836v-5.166a.853.853 0 0 0 .25-.611V5.884a.779.779 0 0 0-.776-.793.779.779 0 0 0-.776.793v4.413c0 .246.1.466.25.611v5.166c0 2.115 1.74 3.835 3.854 3.835 2.09 0 3.821-1.717 3.846-3.83l.012-1.97v-1.573L13.587 16.6z"/></svg>
Main 2B

<input class="sub-input" id="plane" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha5" fill="red" d="M20.061 15.32v-.868l-6.14-4.27.14-3.993c-.071-2.093-1.417-2.427-1.614-2.427-.196 0-1.526.44-1.507 2.427l.14 3.992-6.141 4.271v.868l6.28-1.167.16 4.568-2.294 1.595v.392h2.493a1.07 1.07 0 0 0 1.846 0h2.49v-.392l-2.292-1.595.16-4.568 6.28 1.167z"/></svg>
Main 2C

A: The issue is caused by $(".sub-list") returning more than one element.
So when you test using .hasClass(), you always get a true, since at least one element returned has the class.
You have to run an .each() loop to test all elements separatly:
var item = $(".sub-list");

item.each(function(){
  if (!$(this).hasClass("active")) {
    $(this)
      .closest(".sub-item")
      .hide();
  } else {
    $(this)
      .closest(".sub-item")
      .show();
  }
});

I also added a quick fix for the radio buttons... To uncheck the other:
$(".cat-item").not(this).find("input").prop("checked",false);

Your snippet fixed with the above change:

$(document).ready(function() {
  function toggleSubcatDiv(input, showTypeList) {
    var $list = $(input).closest(".post-item");
    $list
      .find(".sub-list")
      .filter(".active")
      .removeClass("active")
      .end()
      .filter('[data-for="' + $(input).attr("name") + '"]')
      .addClass("active");
  }
  $(this).on("click click.init", ".cat-item", function(e) {
    $(".cat-item").not(this).find("input").prop("checked",false);

    var $menu = $(this).closest(".cat-dropdown");
    var item = $(".sub-list");

    item.each(function(){
      if (!$(this).hasClass("active")) {
        $(this)
          .closest(".sub-item")
          .hide();
      } else {
        $(this)
          .closest(".sub-item")
          .show();
      }
    });
    $menu
      .find(".title")
      .children(":checkbox")
      .prop("checked", true)
      .next("span")
      .text($(this).text())
      .css("color", this.style.color);
    toggleSubcatDiv($(":radio", this), "init" !== e.namespace);
  });
});
.sub-item {
  min-height: 10px
}

.sub-item input {
  display: none
}

.cat1 {
  border: 2px solid blue;
}

.cat2 {
  border: 2px solid red;
}

.sub-list:not(.active) {
  display: none;
}

  Main Category:

<input type="checkbox"> Choose...

<input type="radio" name="cat1">Main 1

<input type="radio" name="cat2">Main 2

  Sub Category:

<input class="sub-input" id="comp" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha" fill="blue" d="M21.72 16.784a.094.094 0 0 0-.071-.033H3.351a.094.094 0 0 0-.093.108c.003.017.279 1.711 2.421 1.711h13.642c2.142 0 2.418-1.694 2.42-1.711a.095.095 0 0 0-.021-.075zm-7.844 1.193h-2.752v-.633h2.752v.633zM5.252 16.092h14.496c.21 0 .38-.17.38-.38V6.81a.38.38 0 0 0-.38-.38H5.252a.38.38 0 0 0-.38.38v8.904c0 .21.17.38.38.38zM6.2 7.758h12.598v7.006H6.201V7.758z"/></svg>
Main 1A

<input class="sub-input" id="ticket" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha2" fill="blue" d="M7.519 14.008l3.473 3.473 6.372-6.372-3.473-3.473-6.372 6.372zm13.884-4.77L19.925 7.76a1.98 1.98 0 0 1-2.686-2.686l-1.477-1.477a.992.992 0 0 0-1.4 0L3.597 14.362a.992.992 0 0 0 0 1.4l1.478 1.478a1.98 1.98 0 0 1 2.685 2.686l1.478 1.477a.993.993 0 0 0 1.4 0l10.765-10.765a.993.993 0 0 0 0-1.4zM10.992 19.07L5.93 14.008l7.962-7.96 5.06 5.061-7.96 7.96z"/></svg>
Main 1B

<input class="sub-input" id="elephant" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha3" fill="red" d="M19.565 9.341h-4.086a4.636 4.636 0 0 1-1.67 3.027.476.476 0 0 1-.672-.067.478.478 0 0 1 .066-.674 3.684 3.684 0 0 0 1.354-2.858 3.7 3.7 0 0 0-3.695-3.695A3.7 3.7 0 0 0 7.188 8.38a3.448 3.448 0 0 0-.86.702c-.826.936-1.008 2.16-1.008 3.053 0 .382.01.765.02 1.135.03 1.11.066 2.493-.3 2.87-.029.029-.115.117-.422.117a.957.957 0 1 0 0 1.914c.74 0 1.343-.234 1.793-.696.6-.617.795-1.505.846-2.513.113.003.234.005.36.005.955 0 2.245-.115 3.266-.627 0 0-.07.442-.07.568v3.807c0 .68.643 1.211 1.325 1.211h.018c.682 0 1.23-.53 1.23-1.21v-1.96h4.544v1.975c0 .672.565 1.195 1.237 1.195h.018c.672 0 1.197-.523 1.197-1.195v-2.182c.598-.3.957-.898.957-1.586v-3.828c0-.99-.783-1.794-1.774-1.794zM7.189 12.107a.451.451 0 1 1 .902 0 .451.451 0 0 1-.902 0z"/></svg>
Main 2A

<input class="sub-input" id="hook" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha4" fill="red" d="M13.587 16.6h1.829c-.254 1.303-1.405 2.31-2.772 2.31a2.836 2.836 0 0 1-2.823-2.836v-5.166a.853.853 0 0 0 .25-.611V5.884a.779.779 0 0 0-.776-.793.779.779 0 0 0-.776.793v4.413c0 .246.1.466.25.611v5.166c0 2.115 1.74 3.835 3.854 3.835 2.09 0 3.821-1.717 3.846-3.83l.012-1.97v-1.573L13.587 16.6z"/></svg>
Main 2B

<input class="sub-input" id="plane" type="radio" name="radios" />

<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"><path id="patha5" fill="red" d="M20.061 15.32v-.868l-6.14-4.27.14-3.993c-.071-2.093-1.417-2.427-1.614-2.427-.196 0-1.526.44-1.507 2.427l.14 3.992-6.141 4.271v.868l6.28-1.167.16 4.568-2.294 1.595v.392h2.493a1.07 1.07 0 0 0 1.846 0h2.49v-.392l-2.292-1.595.16-4.568 6.28 1.167z"/></svg>
Main 2C

A: item is already a jquery object, no need with $() once more, you may try this:
var $item = $(".sub-list");

if (!$item.hasClass("active")) {
  $item
    .closest(".sub-item")
    .hide();
} else {
  $item
    .closest(".sub-item")
    .show();
}


text:
Q: Unresolved external symbol referenced in function _main when using OpenCV CascadeClassifier I have been trying to execute the below code but couldn't compile it.I searched for error by masking some lines as comments.Finally I reached CascadeClassifier face_cascade;by removing all the other lines from face_cascade.load to rectangle(image,faces[i],Scalar(0,125,165),2,8,0); But I couldn't understand what the error is!Did I declare CascadeClassiier in a wrong way?
Thank you in advance.
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include<opencv2/features2d/features2d.hpp>
#include<iostream>
#include<stdio.h>

using namespace std;
using namespace cv;

int main()
{
    Mat image=imread("taylor_swift.jpg");
    imshow( "input", image );
    cvtColor(image,image,CV_BGR2GRAY);
    equalizeHist( image,image );

    CascadeClassifier face_cascade;
    face_cascade.load( "haarcascade_frontalface_alt2.xml" );

    // Detect faces
    vector<Rect> faces;
    face_cascade.detectMultiScale(image,faces,1.5,3,0 |CV_HAAR_SCALE_IMAGE);

    for(size_t i=0;i<faces.size();i++ )
    {

        rectangle(image,faces[i],Scalar(0,125,165),2,8,0);
    }

    imshow( "Detected Face", image );

    waitKey();
    return 0;
}

EDIT:
Error   1   error LNK2019: unresolved external symbol "public: virtual __thiscall cv::CascadeClassifier::~CascadeClassifier(void)" (??1CascadeClassifier@cv@@UAE@XZ) referenced in function _main   C:\Users\vamsidhar muthireddy\documents\visual studio 2010\Projects\OPEN_CV_TEST\OPEN_CV_TEST\main.obj

Error   2   error LNK2019: unresolved external symbol "public: __thiscall cv::CascadeClassifier::CascadeClassifier(void)" (??0CascadeClassifier@cv@@QAE@XZ) referenced in function _main    C:\Users\vamsidhar muthireddy\documents\visual studio 2010\Projects\OPEN_CV_TEST\OPEN_CV_TEST\main.obj

Error   3   error LNK1120: 2 unresolved externals   C:\Users\vamsidhar muthireddy\documents\visual studio 2010\Projects\OPEN_CV_TEST\Debug\OPEN_CV_TEST.exe 1

A: You must be seeing compiler errors like this:
/tmp/cckqEgtd.o: In function `main':
face.cpp:(.text+0x50): undefined reference to `cv::imread(std::string const&, int)'
face.cpp:(.text+0x87): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
face.cpp:(.text+0xca): undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
face.cpp:(.text+0x101): undefined reference to `cv::_OutputArray::_OutputArray(cv::Mat&)'
face.cpp:(.text+0x11a): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
face.cpp:(.text+0x13a): undefined reference to `cv::cvtColor(cv::_InputArray const&, cv::_OutputArray const&, int, int)'
face.cpp:(.text+0x153): undefined reference to `cv::_OutputArray::_OutputArray(cv::Mat&)'
face.cpp:(.text+0x16c): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
face.cpp:(.text+0x185): undefined reference to `cv::equalizeHist(cv::_InputArray const&, cv::_OutputArray const&)'
face.cpp:(.text+0x194): undefined reference to `cv::CascadeClassifier::CascadeClassifier()'
face.cpp:(.text+0x1d7): undefined reference to `cv::CascadeClassifier::load(std::string const&)'
face.cpp:(.text+0x275): undefined reference to `cv::CascadeClassifier::detectMultiScale(cv::Mat const&, std::vector<cv::Rect_<int>, std::allocator<cv::Rect_<int> > >&, double, int, int, cv::Size_<int>, cv::Size_<int>)'
face.cpp:(.text+0x32a): undefined reference to `cv::rectangle(cv::Mat&, cv::Rect_<int>, cv::Scalar_<double> const&, int, int, int)'
face.cpp:(.text+0x36c): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
face.cpp:(.text+0x3af): undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
face.cpp:(.text+0x3d7): undefined reference to `cv::waitKey(int)'
face.cpp:(.text+0x3fa): undefined reference to `cv::CascadeClassifier::~CascadeClassifier()'
face.cpp:(.text+0x4f3): undefined reference to `cv::CascadeClassifier::~CascadeClassifier()'
/tmp/cckqEgtd.o: In function `cv::Mat::~Mat()':
face.cpp:(.text._ZN2cv3MatD2Ev[_ZN2cv3MatD5Ev]+0x39): undefined reference to `cv::fastFree(void*)'
/tmp/cckqEgtd.o: In function `cv::Mat::release()':
face.cpp:(.text._ZN2cv3Mat7releaseEv[_ZN2cv3Mat7releaseEv]+0x47): undefined reference to `cv::Mat::deallocate()'
collect2: error: ld returned 1 exit status

These kind of undefined reference errors occur when you do not link the executable against the required libraries.
If you are on a linux machine then you can use this to compile your code.
g++ face.cpp `pkg-config opencv --libs`

EDIT:
Have a look at http://docs.opencv.org/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.html . This link from the OpenCV documentation explains how to configure Visual Studio with OpenCV
Here is a property sheet you can use with minor modifications as per your setup to configure visual studio https://raw.githubusercontent.com/OpenNI2-Book/openni2book/master/props/OpenCV.props
You may need to change some paths according to your installation directory. Also you will have to change the library names according to the opencv version you have. For example if you have OpenCV 2.4.10 then you will replace opencv_core246.lib with opencv_core2410.lib and so on.


text:
Q: JTable not visible when added to Jpanel I have JButton in the front panel. When it is clicked it should display the data in table format. I have assigned the data and column names to JTable parameter but it is not visible in the front end. I confirmed the values are assigned correctly but not sure why table is not visible in the panel. Here is my code:
private void disPlayDataActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
       sql = "select * from persons";

    try {
              Statement  st = con.createStatement();
              ResultSet rs = st.executeQuery(sql);
              ResultSetMetaData metaData = rs.getMetaData();
              int columnCount=metaData.getColumnCount();
              String[]columnNames=new String[columnCount];

              for(int i=0;i< columnNames.length;i++){
                columnNames[i]=metaData.getColumnName(i+1);

        }
        ArrayList<String[]> rows=new ArrayList<>();
        while(rs.next()){
            String[]currentrow=new String[columnCount];
            for(int i=0;i<columnCount;i++){
                currentrow[i]=rs.getString(i+1);

        }

              rows.add(currentrow);
        }
        String[][] rowsArray=new String[rows.size()][columnCount];
        rowsArray=rows.toArray(rowsArray);
        JTable jt=new JTable(rowsArray,columnNames);
        jPanel2.add(jt);
        jt.setVisible(true);

    } catch (SQLException ex) {
        Logger.getLogger(EmployeePanel.class.getName()).log(Level.SEVERE, null, ex);
    }

    finally{

    }

}

A: can you try this one,
JTable jt=new JTable(rowsArray,columnNames);
jt.setBounds(30,40,200,300);   // you can put dimension as per your wish...

JScrollPane sp=new JScrollPane(jt);
jPanel2.add(sp);
// code fore set visible true to jpanel2...

A: Swing's layout API is lazy, it's designed this way.  You need to tell it when you're ready for it revalidate the container hirarcy.
JTable jt=new JTable(rowsArray,columnNames);
jPanel2.add(jt);
jPanel2.revalidate();
jPanel2.repaint();

Without knowing your full code, generally speaking, it's much easier to simply have a main JTable and change it's model when ever you need to.


text:
Q: Перевод в десятичную систему счисления больших двоичных чисел Никак не могу найти алгоритм, только обратный нашел Перевод в двоичную систему счисления больших чисел

A: Требуемый алгоритм несложен.
Для перевода числа в другую систему счисления достаточно многократного деления с остатком на основание новой системы счисления, при котором частное используется в качестве нового делителя. Запись числа в новой системе счисления - это последовательность остатков, записанная в обратном порядке.
С практической точки зрения, делить длинное число на 10 - не лучший вариант. Лучше использовать промежуточную систему счисления (например, по основанию 1 000 000 или 1 000 000 000), что сокращает количество "длинных" делений.

A: Алгоритм приходит легко, если понимать запись двоичного числа.
Например, рассмотрим двоичное число ниже:

В десятичной форме оно будет выглядеть так:
dec_num = 2^0 + 2^5 + 2^7 = 161
То есть мы просто сложили двойки в степенях позиций с ненулевыми значениями.
Как же нам это закодить?
На каждой итерации нашего алгоритма мы должны знать:
1)позицию элемента(в общем-то это есть значение нашего счётчика цикла)
2)цифру числа в данной позиции
Чтобы узнать последнюю цифру числа достаточно взять остаток от деления по модулю 10(операция bin_num%10). Но как тогда узнать предпоследнюю? Очень просто! Достаточно модифицировать наше бинарное число в конце каждой итерации следующим образом
bin_num/=10. Применяя эту операцию, мы как бы сдвигаем число вправо, делая его предпоследнюю цифру последней, чтобы операция bin_num%10 давала нужный результат.

Надеюсь этих рассуждений достаточно, чтобы найти верное решение:)


text:
Q: Alternative name for *ngIf directive A long time ago Angular 2's docs mentioned an alternate name for *ngIf, that didn't use an asterisk. I believe it was something similar to <prefix>-ng-if where <prefix> was some short prefix.
I cannot find any reference to this in the latest docs.
The use case is that the xml parser I am required to use does not support attributes preceded by '*'.

A: You can use
<template [ngIf]="expr"></template>

or
<template bind-ngIf="expr"></template>

A: You can use template with [ngIf](with Property binding)
<template [ngIf]="condition">
  <p>
    Content Goes here
  </p>
</template>


text:
Q: 'is_author()' logic in widget for author only So, I have a widget that I only want to show it to the page author.
I used the following logic: is_author()
However it does not seem to work (it shows non-author)
Am I using this logic right?
Any suggestions?
Thank you

A: is_author() is only for Archive pages.
Quote from the Codex:

is_author() checks if an Author archive page is being displayed

So viewing a single Post or Page isn't going to get a TRUE from is_author().
I think you'll want something more like this:
global $post,$current_user; // get the global variables to check
get_currentuserinfo();  // get current user info
// Now check if the author of this post is the same as the current logged in user
if ($post->post_author == $current_user->ID) {
   // do code here
}

I hope this helps. :)
EDIT #1:
Shortened code version.
// Check if the author of this post is the same as the current logged in user
if ( $post->post_author == get_current_user_id() ) {
   // do code here
}

A: You can use:
$obj = get_queried_object();
$user_id = get_current_user_id();

// check if page's post author is same as logged in user
if (isset($obj->post_author) && $obj->post_author == $user_id) {
    // ... do your stuff here
}

With get_queried_object function you get object of the current page. As it's requested that page should be of "page" type you'll get WP_Post object of the current page (post_type = 'page').
The get_current_user_id is self-explanatory.
So if both match, you'll get code running for current user which is creator of the page.
You can also place a check that queried object is 'page':
if ($obj instanceof WP_Post && $obj->post_type == 'page') {
    // ...
}


text:
Q: Exclude a single page from wp_list_pages()? I am using wp_list_pages() to list all of the children of a parent page in my navigation. I want to exclude 1 child page from that navigation, how would I write that?
<?php
 $children = wp_list_pages("title_li=&child_of=20&echo=0&depth=1");
  if ($children) {?>

<a href="<?php echo get_permalink($post->post_parent) ?>"><?php
    echo $parent_title;?>

     <?php echo $children; ?>
<?php } ?>

A: The Wordpress Doc
wp_list_pages( array|string $args = '' )

'exclude' (string) Comma-separated list of page IDs to exclude

You can try :
<?php wp_list_pages(array('exclude'=>'id')); ?> // id of page you want to exclude separated by comma


text:
Q: What is the type "int/2" in OCaml When I executed the following commands in the interaction environment (either OCaml or utop), all the expressions of "int" type turned out to be "int/2" type. This behaviour can be replicated as follow.
# 3;;
- : int = 3

# type int;;
type int

# type a;;
type a

# 3;;
- : int/2 = 3

Does anyone have any idea why this happens? Thanks!
Edit on Mar 2 2020:
I found that the "int/2" won't appear if I do the following. Can anyone please explain what happened here?
# 3;;
- : int = 3

# type int;;
type int

# 3;;
- : int = 3

Update: OCaml version 4.08.1 was used in the above cases.

A: The constant 3 is of the built-in type int, which is not the type int that is in scope. So the toplevel appends a number to signal this fact. Otherwise things can get very confusing. I.e., you can get messages like "a value was expected of type int but this value is of type int". With the /n tag, it more clearly says "a value was expected of type int/n (one kind of int) but this value is of type int/m (another different kind of int)"
It appears this behavior was added in OCaml 4.08.0. You can find discussion of the feature here: https://github.com/ocaml/ocaml/pull/1120
Update
You should show your OCaml version. This feature was added recently enough that you may encounter toplevels both with and without the feature.
At any rate, both of your examples use the int/n notation in my tests using OCaml 4.10.0
$ ocaml
        OCaml version 4.10.0
# 3;;
- : int = 3
# type int;;
type int
# type a;;
type a
# 3;;
- : int/2 = 3

$ ocaml
        OCaml version 4.10.0
# 3;;
- : int = 3
# type int;;
type int
# 3;;
- : int/2 = 3

(It's also possible that this behavior was made a little more consistent in OCaml 4.10.0.)


text:
Q: inputting a certain number for wages doesn't stop the do while loop when it reaches the number    #include <stdio.h>

int main()
{
char firstname[20];
char lastname[20];
float wage;
int n_emp;
int e_numemp;
FILE *staff_ptr;

staff_ptr=fopen ("staff", "wage");
printf("Input the numbers employees you would like to add\n");
scanf("%d",&n_emp);
do {
  (e_numemp=n_emp-1);
  printf("Enter the first name of the employee\n");
  scanf("%s",&firstname);
  printf("Enter the second name of the employee\n");
  scanf("%s",&lastname);
  printf("Enter the wage of the employee\n");
  scanf("%f",&wage);
  fwrite (&firstname,sizeof (firstname),1,staff_ptr);
  fwrite (&lastname,sizeof (lastname),1,staff_ptr );
  fwrite (&wage,sizeof (wage),1,staff_ptr );
}
while (e_numemp!=0);
fclose (staff_ptr);
return 0;
}

The question for my assignment is "Write a program to ask for the name and wage of each employee in a firm and store the data in a file called "staff"
For some reason when i input a number like 4 for the numbers of employees it just doesn't stop at 4 and keeps going on forever

A: In every iteration of the loop e_numemp is always set to n_emp - 1 (n_emp is never changed once input).
Assuming you wanted to save the initial value of n_emp, perhaps you meant:
scanf("%d",&n_emp);
e_numemp = n_emp;
do {
  e_numemp -= 1;
  .
  .
  .
} while ( e_numemp != 0 );


text:
Q: Google Maps JavaScript API calculate distance to each marker I am using the Google Maps JavaScript API. As an alternative to the map view, I am providing a "list" view of the locations (by locations I mean markers):
var locloc = [];
var testContent;

var marker, i;

for (i = 0; i < locations.length; i++) {

    // UPDATE THE LIST OF LOCATIONS SECTION

    locloc.push({
        lat: locations[i][5],
        lng: locations[i][6]
    });

    testContent += '
'
                   + locations[i][0] + '
'
                   + locations[i][5] + ',' + locations[i][6]
                   + '
';

    document.getElementById("search_results").innerHTML = testContent;

    var icon_image;
    icon_image = 'https://maps.gstatic.com/mapfiles/ms2/micons/subway.png';

    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][5], locations[i][6]),
        animation: google.maps.Animation.DROP,
        icon: icon_image,
        map: map
    });

"List of Locations" section code:

List of Locations

In addition, I have a search box allowing to search by address:
<input type="text" name="address" id="address" class="address" placeholder="Where are you coming from?" />

I would like to have the user search an address and then update the "List of Locations" section with the locations sorted by the distance (closest first) from the search address.
How can I calculate the distance to each marker and output it into the List of Locations section using the Google Maps JavaScript API?


text:
Q: Webbrowser Unable to open website while internet explorer opens it I have a simple windows forms application that opens a web page using WebBrowser and fills username and password fields and submits the form, then I just get the cookie from it and use it to download files from that site using HttpWebRequest:
    public static CookieContainer GetCookieContainer(string username, string password)
    {
        WebBrowser wb = new WebBrowser(){ ScriptErrorsSuppressed = true };
        bool completed = false;
        wb.DocumentCompleted += (s, e) =>
        {
            HtmlElement el = wb.Document.GetElementById("email");
            if (el != null)
            {
                el.SetAttribute("value", username);
                wb.Document.GetElementById("password").SetAttribute("value", password);
                wb.Document.Forms["registration"].InvokeMember("submit");
            }
            else
                completed = true;
        };
        wb.Navigate("https://somesite.com/login");
        do
        {
            Application.DoEvents();
        } while (!completed);
        return GetUriCookieContainer(new Uri("https://somesite.com"));
    }

The above code works perfectly on my local machine and I'm able to grab CookieContainer, and use it to download the file. but when I run it on the server, I get and error popped up:

Unable to Download / from somesite.com.
  Unable to open this internet site. the requested site is either unavailable or can not be found. Please try again later.

I'm using windows 10, and the server is Windows server 2016.


text:
Q: How to simultaneously diagonalize two commuting matrices? I'm working on a numerical problem involving simultaneous diagonalization.
I have two matrices, $K$ and $B$, for which $[K,B]=0$. I want to use the eigenvectors of $B$ to diagonalize $K$. Here is the $B$ matrix,
\begin{equation}
B = \begin{pmatrix}
0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & -1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & -1 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & -1 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0
\end{pmatrix}
\end{equation}
$B$ is singular, is it still possible to use it to diagonalize $K$? First I get the eigenvectors of $B$, which MATLAB will return in a matrix $V$ with the $B$ eigenvectors as it's columns. Then
I use this matrix $V$ to block diagonalize $K$, i.e.
\begin{align}
V^{-1}KV = [K]_{BD}
\end{align}
$[K]_{BD}$ denotes that $K$ is in the basis where it is now block diagonal. Then I can diagonalize each of $[K]_{BD}$'s blocks, getting eigenvectors of those blocks. Padding those block-eigenvectors with zeros should give me the eigenvectors of the full $[K]_{BD}$. I assemble  these into a matrix, let's call it $S$. Then I can diagonalize $S$ by performing,
\begin{align}
S^{-1}[K]_{BD}S = K_D
\end{align}
where $K_D$ is the now diagonal $K$. I can apply
\begin{align}
S^{-1}(V^{-1}BV)S = B_D
\end{align}
and I will have simultaneously diagonalized the $K$ and $B$ matrix as desired.
Some issues I'm facing / questions I have are:

*

*MATLAB tends to return the matrix of eigenvectors (the $V$ or the $S$) with an arbitrary ordering of the columns (it's at the whims of algorithmic efficiency). Does this matter for my procedure? I think this is a problem because the procedure relies on a correspondence between the degenerate subspaces of $B$ and the blocks of $[K]_{BD}$.

*As mentioned, is $B$ being singular a problem? It seems like it is because MATLAB is throwing an error when I try to use $V^{-1}$ in the computation.

*My understanding of this whole topic isn't great. I'm trying to follow the procedure shown in this video. But maybe someone that reads this post can direct me to a good textbook section to clear up any misconceptions you notice in the above.


text:
Q: How to pass int values to ASP.NET page methods from jQuery? I am using ASP.NET page methods with jQuery. Here is my code,
$.ajax({
      type: "POST",
      url: "Default.aspx/GetRecords",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",

and the ASP.NET page method is,
[WebMethod]
public static string GetRecords(int currentPage,int pagesize)
{
    // my logic here
}

How to pass values for currentPage and pagesize from jQuery?

A: I got it working. My data section must be
data: "{'currentPage':1,'pagesize':5}",

A: Did you try just:
$.ajax({
    type: "POST",
    url: "Default.aspx/GetRecords",
    data: {"currentPage": 1, "pageSize": 100},
    contentType: "application/json; charset=utf-8",
    dataType: "json",

?

A: Try this
$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{ currentPage: '" +parseInt( $('#currentpage').val()) + "',pageSize:'"+parseInt( $('#pagesize').val()) +"'}",
        url: "Default.aspx/GetRecords",
        dataType: "json",
        success: function (data) {
                     $("#result").html(data.d);
                 }
        });


text:
Q: Java compiler behaviour during narrowing primitive conversion K.Sierra and B.Bates in their book "SCJP Study Guide" write
"The following is legal byte b = 27; but only because the compiler automatically narrows the literal value to a byte. In other words, the compiler puts in the cast. The preceding code is identical to the following: byte b = (byte) 27;"
In my opinion this explanation is incorrect. Are these two lines of code identical?
In fact
byte b = 27;

is simply a constant. And the compile-time narrowing of constants is the only reason why this code is valid. So no cast is needed. When narrowing the compiler just checks whether the specified value fits in the type of the variable.
The specification says:

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

In the second case
byte b = (byte) 27;

casting does occur during at runtime and the primitive value is computed according to specific rules. The compiler doesn't care about the compatibility of primitive types. For example
byte b = 5.0; // compile error
byte b = 277777777; // compile error
byte b = (byte) 5.0; // valid!
byte b = (byte) 277777777; // valid!!

This makes me think that widening/narrowing conversion and casting are fundamentally different. But in various sources they are often used interchangeably. Is this correct? Does casting occur under the covers in case of an implicit narrowing conversion?
Can anyone explain the real behavior of the compiler in the situation described in the above book?

A: It's easy enough to test it out. Put the following in Temp.java:
class Temp {
  public static void main(String[] argv) {
    byte b = 27;
    System.out.println(b);
  }
}

Now compile it with your favorite compiler:
$ javac Temp.java

Now dump the bytecode with javap:
 $ javap -c Temp.class
 Compiled from "Temp.java"
  class Temp {
    Temp();
      Code:
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return

    public static void main(java.lang.String[]);
      Code:
         0: bipush        27
         2: istore_1
         3: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
         6: iload_1
         7: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
        10: return
  }

Now replace 27 with (byte)27 and run again. You'll see there is no difference. In fact the two classfiles will have the same md5sum.
There is no runtime cast in the bytecode because the compiler figured out it wouldn't be needed, and optimized it away.
I believe you're correct that syntactically the line byte b = 27 differs from the line byte b = (byte) 27, but they are semantically the same, because all standard compilers are smart enough to optimize the line into a single bytecode.

A: Before we start, it's important to note that in java, all purely numeric literals are int values.
The key phrase regarding allowable un-cast constants is is representable in the type of the variable. That just means the constant "is in range" of the variable type, so:

*

*for byte   -128 to 127

*for short  -32768 to 32767

*for char   0 to 65535

Values "in range" won't "lose information" if cast to the variable type. That explains why in-range constants are allowed.
For values outside of the range, an explicit cast is required because information would be lost if a cast was performed. When a narrowing cast is done, bits outside the scope of the variable type are simply masked off - that's what "losing information" means in these cases.
It's as if an assignment of a constant is like:
byte b = nnn & 0xFF;

If nnn is within range, then the mask will not change the value, so nothing lost, so no problem - compiles OK.
If nnn is out of range, information would be lost, so require an explicit cast to acknowledge the loss.
If you recall that all integer literals are ints, the rules are actually no different than those that apply to assigning an int to narrower variable type, except the compiler allows no cast if it knows the value will "fit",


text:
Q: When assert() fails, what is the program exit code? When an assert() call fails, what is the exit code used, and where is it documented?

A: The C99 (unchanged in C11) standard states that assert calls abort and the abort stuff states this about the return code:

An implementation-defined form of the status unsuccessful termination is returned to the host environment by means of the function call raise(SIGABRT).

It's documented in section 7.2.1.1 (assert) and 7.20.4.1 (abort) of the C99 standard here.
Many UNIX systems will return 128 plus the signal number (SIGABRT is signal number 6) so you may get 134. Whatever you get, it should be documented by the C implementation.
For example, see here for gcc. Although it's quite silent on what gets returned to the calling environment. From the specific sections here:

Some choices are made by the library and operating system (or other environment when compiling for a freestanding environment); refer to their documentation for details.

And here:

The behavior of most of these points are dependent on the implementation of the C library, and are not defined by GCC itself.

So is the glibc doco here on program termination (specifically the exit status bit). It mentions conventions but no firm rules.

A: It's implementation-specific.  You could do this:
int main()
{
    assert(0);
}

Then run it:
./a.out
echo $?

1 (<- or whatever)

This'll at least tell you what to expect for your setup.  I'm getting 134 on a couple of Linux boxes with both GCC and g++.

A: I can't find the actual spec for it (POSIX is kind of hard to search), but I did find a reference.
A thrown assertion results in an exit status that is the same as whatever EXIT_FAILURE expands to be (reference). Since you are dealing with Linux, you are also dealing with POSIX, which further defines the behavior from c99.

A: I was working with POSIX message queues, and I have got the same error, mq_open was failed with errono 38 (ENOSYS).
The workaround is to rebuild the kernel with POSIX MESSAGE QUEUE enabled in the kernel configuration.
This will build the kernel with POSIX message queue support and it worked for me.


text:
Q: Python power with negative values returns error I'm having trouble with powers with negative numbers: sometimes it gives me error, sometimes it does it without warnings or errors.
import numpy as np

FS = 1.28
X = (np.arange(20) / FS)[np.newaxis]

Y = np.real((X.T @ X) ** (-0.5))

for i in range (0,  20, 1):
        for j in range (0,  20, 1):
                print(Y[i][j])

This code doesn't give any problems.
This other one, instead, returns error:
W = np.real(((W @ W.T)**(-0.5)) @ W)

W is 2x128 matrix.
The error is:
W = np.real(((W @ W.T)**(-0.5)) @ W)
RuntimeWarning: invalid value encountered in power

in both cases I've made operations with a matrix and the same power, why in the second case it returns error ?


text:
Q: Repeat the loop with variables (Row Lines) incrementing by 1 I'm pretty new to VBA and struggling with a loop.
I'm doing a report that copies certain cells from an excel sheet to a new one ("Report").
How do I manage to increment the variables by +1 so that it checks and copies cell B3,B4,B5... to B3,B4,B5... on the report sheet? (and so on...)
Appreciate your help, thank you!
Sub CopyRow()

'Return to Sheets("CS15 Download"), Find Last Row and LastRow = that row
    Sheets("CS15").Select
    Range("A8").Select
    Selection.End(xlDown).Select
    ActiveCell.Offset(0, 1).Range("A1").Select
    Selection.End(xlUp).Select
    LastRow = ActiveCell.Row

Dim ObjDes As Variant
Const Lvl As Integer = 1

ObjDes = Range("Q1").Value

'Variables to be copied
Dim ComNum As Integer
ComNum = Range("F3").Value
Dim Description As Variant
Description = Range("G3").Value

'Target Cells in Report Sheet
Dim ReportComNum As Integer
ReportComNum = Sheets("Report").Range("B2")
Dim ReportDescription As Variant
ReportDescription = Sheets("Report").Range("C2")

'Variables to Check
Dim Level As Variant
Level = Range("B3").Value

'Select the first Component Number
Range(ComNum).Select

'Do Until LastRow is reached
Do While ActiveCell.Row < LastRow + 1

'If the Level Is 1 Then
If Range("B3").Value = Lvl Then

    'Copy the ComNum and Description into B2/C2 of Report Sheet
    ReportComNum.Value = Range(ComNum).Value
    ReportDescription.Value = Range(Description).Value
    'Select Next Row
    ActiveCell.Offset(1, 0).Range("A1").Select

'If Level is not 1, but the ObjDes starts with "BDS" Then
ElseIf Range("B3").Value > Lvl And InStr(1, ObjDes, "BDS") = 1 Then

    'Copy the ComNum and Description into B2/C2 of Report Sheet
    ReportComNum.Value = Range(ComNum).Value
    ReportDescription.Value = Range(Description).Value
    'Select Next Row
    ActiveCell.Offset(1, 0).Range("A1").Select

'If not, go to next row
Else
ActiveCell.Offset(1, 0).Range("A1").Select

End If

Loop

End Sub

A: There are multiple ways to address worksheet cells in vba.  It looks from your code that you were using the range object and it's addressing scheme of letter/number (i.e. B3,B4,B5...).  That is valid and the range object is very powerful.
However, when working with individual cells and trying to write iterative code over a worksheet I find that the Cells(Row,Col) method is easier for me to use.  It addresses all rows and columns with  integer values and fits well into a for..next loop.
This code goes in the source worksheet object. It iterates over rows 3 to 5 and over column 2 (column B).  Sets the same cell range in the "Report" worksheet with the current value plus 1.   Changing the range of operation just requires change the values on the for statement. Those can even be parametrized and passed into the function.  The Option Explicit forces the declaration of all variables.
Some good MS docs on addressing worksheet values
Hope that helps..
Option Explicit
Private Sub CopyIt()
Dim Row, Col

For Row = 3 To 5
    For Col = 2 To 2
        Sheets("Report").Cells(Row, Col) = Me.Cells(Row, Col) + 1
    Next
Next


text:
Q: What's the Rails Way to pass data to controller method? After getting some data from an API, I filtered the results and showed them on a view to et the user select which data he wants to save to the database. The user doesn't have to fill anything once all the data came from the API.
My question is: what's the best way/rails way to pass all this data to the controller?
Right now I'm using a form with hidden fields. It works but I was wondering if that's the best way.
Here's how my 'form_for' looks like:
<%= form_for (@new_photoset) do |f| %>
  <%= f.hidden_field :id, :value => not_imported_set.id %>
  <%= f.hidden_field :name, :value => not_imported_set.name %>
  <%= f.hidden_field :thumb_url, :value => not_imported_set.url) %>
  <%= f.submit "Import" %>
<% end %>

A: I believe you're on the right track, this is way you would normally do this in rails.


text:
Q: Python, ROOT, and MINUIT integration? I'm a modest graduate student in a high energy particle physics department. With an unfounded distaste for C/C++ and a founded love of python, I have resorted to python for my data analysis so far (just the easy stuff) and am about to attempt backing python scripts against ROOT libraries and, particularly, utilize MINUIT for some parameter minimization.
As well as asking if anyone has any tips for the installation and usage of these, I wondered if it was worth it to even attempt it or just to slip into the "norm" of using C/C++, or if things like pyminuit are usable. Or do you think I could wrap entire C/C++ scripts into python code to make use of my existing self-written analysis methods (I have no wrapper experience as of yet). Sorry for the vagueness; I'm headed into a great unknown that far outweighs my current experience.

A: You are aware of pyROOT, right?
Never tried it myself, so I don't know how it might stack up against your needs.

A: It's probably worth checking out rootpy. Maybe not totally mature yet, but it's a step in the right direction.
Yes, rootpy is built on top of PyROOT, but with some additional features:

*

*it emphasizes a pythonic interface and hides some of the ugliness of ROOT;

*it integrates with matlibplot, which has a larger development community, and a greater presence on SO, not to mention better looking plots;

*it allows conversion to HDF5 files, which will allow you to share data with people who can't take the time to install the monolithic ROOT package.

Unfortunately, as long as you're working with something built on top of CINT (which PyROOT is), you'll still have to deal with one of the ugliest parts of ROOT.

The other option, if you're sick of fumbling with PyROOT, is to use one of the packages that converts ROOT directly to HDF5

A: I wrote a minuit wrapper a while back(In my sample of 1 experience, ROOT's minuit seems more robust than pyminuit and I like ROOT Minuit output more)
https://github.com/piti118/RTMinuit
With numpy root file reading capability
https://github.com/piti118/root_numpy
And not so polished fitting library and toy generation etc. based on RTMinuit and numpy
https://github.com/piti118/dist_fit
Tutorials and help are all given in the package


text:
Q: 403 forbidden on recaptcha only when deployed I've got a 403 - forbidden while send a key to recaptcha v2 from google.
Locally, at the 127.0.0.1 it works.
But when published at IIS, the problem occurs.
The Elmah log reports Forbidden 403 and when I comment the request line and republish, my app works.
Im trying to send with a WebClient, sending the key with GET params.
Again:
Locally it works ok, but when published at my IIS instance, I receive 403 error.
It can be a server infrastructure/proxy/firewall problem?


text:
Q: Select the "id" of a collection of images to export them with their corresponding "id" automatically in GEE I have just started to learn about Google Earth Engine and I have a problem in my code.
The code accesses the Sentinel-1 catalog, applying some filters and a crop depending on the study area. On this clipping, a loop is applied to be able to export all the images to google drive.
My problem is that I can not export the image with its corresponding "id".
I have tried to store the "id" in a variable and to select the elements of the list that contains the "id" but it does not recognize it when I put it in description to export it.

var fecha_ini = '2018-10-01';

var fecha_fin = '2018-10-12';

var dataset = ee.ImageCollection('COPERNICUS/S1_GRD')
                          .filterDate(fecha_ini,fecha_fin)
                          .filter(ee.Filter.listContains('transmitterReceiverPolarisation','VV'))
                          .filter(ee.Filter.eq('instrumentMode','IW'))
                          .filter(ee.Filter.eq('orbitProperties_pass','DESCENDING'))
                          .filterBounds(Andalucia_agua)
                          .select('VV');

print(dataset)
var clip = function(image){

    return image.clip(Andalucia_agua);
};

var dataset_clip = dataset.map(clip);

Map.addLayer(dataset_clip.select('VV'),{min:-50,max:0}, 'Escena', false);

var lista = dataset_clip.toList(dataset_clip.size())

var i;

var imagen;

for (i = 0; i< numero_imagenes; i++) {

  var imagen = ee.Image(lista.get(i))

  var id = print(imagen.id())

  Map.addLayer(imagen.select('VV'),{min:-50,max:0}, 'Escena_0'+ i )

  Export.image.toDrive({
    image: imagen,
    description: id,
    scale: 10,
    region: Andalucia_agua,
    maxPixels: 1E10
});
}

A: The code as follows uses the 'forEach' method to iterate a list with the corresponding ids. It also selects from the id image (by using slice method) only the date because the id, as string, is too long. It also includes a not recommend 'getInfo' method. However, it works without any problem.
var Andalucia_agua = ee.Geometry.Polygon(
        [[[-6.181516998737666, 37.22475726749809],
          [-6.181516998737666, 37.21341126336629],
          [-6.153879517048213, 37.21341126336629],
          [-6.153879517048213, 37.22475726749809]]], null, false);

var fecha_ini = '2018-10-01';
var fecha_fin = '2018-10-12';

var dataset = ee.ImageCollection('COPERNICUS/S1_GRD')
                          .filterDate(fecha_ini,fecha_fin)
                          .filter(ee.Filter.listContains('transmitterReceiverPolarisation','VV'))
                          .filter(ee.Filter.eq('instrumentMode','IW'))
                          .filter(ee.Filter.eq('orbitProperties_pass','DESCENDING'))
                          .filterBounds(Andalucia_agua)
                          .select('VV');

print(dataset);

var clip = function(image){

    return image.clip(Andalucia_agua);

};

var dataset_clip = dataset.map(clip);

Map.addLayer(dataset_clip.select('VV'),{min:-50,max:0}, 'Escena', false);

var lista = dataset_clip.toList(dataset_clip.size());

print(lista);

var ids = lista.map(function (ele){

  return ee.String(ee.Image(ele).id()).slice(17,25);

});

ids.getInfo().forEach(function (c) {

  var idx = lista.indexOf(c);

  var image = ee.Image(lista.get(idx));

  Export.image.toDrive({
    image: image,
    description: 'image'.concat('_', c),
    scale: 10,
    region: Andalucia_agua,
    maxPixels: 1E10
  });

});

Your code also works as follows but, it's even worse. The use of for-loops is discouraged in Earth Engine and it is necessary to employ two 'getInfo'.
var Andalucia_agua = ee.Geometry.Polygon(
        [[[-6.181516998737666, 37.22475726749809],
          [-6.181516998737666, 37.21341126336629],
          [-6.153879517048213, 37.21341126336629],
          [-6.153879517048213, 37.22475726749809]]], null, false);

var fecha_ini = '2018-10-01';
var fecha_fin = '2018-10-12';

var dataset = ee.ImageCollection('COPERNICUS/S1_GRD')
                          .filterDate(fecha_ini,fecha_fin)
                          .filter(ee.Filter.listContains('transmitterReceiverPolarisation','VV'))
                          .filter(ee.Filter.eq('instrumentMode','IW'))
                          .filter(ee.Filter.eq('orbitProperties_pass','DESCENDING'))
                          .filterBounds(Andalucia_agua)
                          .select('VV');

print(dataset);

var clip = function(image){

    return image.clip(Andalucia_agua);

};

var dataset_clip = dataset.map(clip);

Map.addLayer(dataset_clip.select('VV'),{min:-50,max:0}, 'Escena', false);

var lista = dataset_clip.toList(dataset_clip.size());

print(lista);

var i;

var numero_imagenes = lista.size();

for (i = 0; i< numero_imagenes.getInfo(); i++) {

  var imagen = ee.Image(lista.get(i))

  var id = imagen.id();

  Map.addLayer(imagen.select('VV'),{min:-50,max:0}, 'Escena_0'+ i )

  Export.image.toDrive({
    image: imagen,
    description: id.getInfo(),
    scale: 10,
    region: Andalucia_agua,
    maxPixels: 1E10
});
}

Editing Note:
Based in this answer, I found out a better way to do that. Code looks as follows:
function setId (img) {

  return img.set({'id': img.id()});

}

var Andalucia_agua = ee.Geometry.Polygon(
        [[[-6.181516998737666, 37.22475726749809],
          [-6.181516998737666, 37.21341126336629],
          [-6.153879517048213, 37.21341126336629],
          [-6.153879517048213, 37.22475726749809]]], null, false);

var fecha_ini = '2018-10-01';
var fecha_fin = '2018-10-12';

var dataset = ee.ImageCollection('COPERNICUS/S1_GRD')
                          .filterDate(fecha_ini,fecha_fin)
                          .filter(ee.Filter.listContains('transmitterReceiverPolarisation','VV'))
                          .filter(ee.Filter.eq('instrumentMode','IW'))
                          .filter(ee.Filter.eq('orbitProperties_pass','DESCENDING'))
                          .filterBounds(Andalucia_agua)
                          .select('VV')
                          .map(setId);

print(dataset);

dataset.aggregate_array('id').evaluate(function (ids) {
  ids.map(function (id) {
    var img = dataset.filter(ee.Filter.eq('id', id));
    exportImages(img, id);
  });
});

function exportImages(img, id) {

 print(id);

  Export.image.toDrive({
    image: img,
    description: 'image'.concat('_', id),
    scale: 10,
    region: Andalucia_agua,
    maxPixels: 1E10
  });

}


text:
Q: OS X auto-layout prevents window resizing One for the auto-layout gurus out there: I don't understand why the following auto-layout setup prevents resizing of the window.
I have three views organized this way:
-----------------
|           |   |
|     F     | S |
|           |   |
-----------------
|     B     |
-------------

S has a fixed with, B has a fixed height, and F should always have S's height and B's width.
This is what I set up in terms of constraints:
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[F(>=100)][S(==100)]|"
                                                             options:0
                                                             metrics:nil
                                                               views:@{ @"F": _f, @"S": _s }]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[F(>=100)][B(==100)]|"
                                                             options:0
                                                             metrics:nil
                                                               views:@{ @"F": _f, @"B": _b }]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[B(==F)]"
                                                             options:0
                                                             metrics:nil
                                                               views:@{ @"B": _b, @"F": _f }]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[S(==F)]"
                                                             options:0
                                                             metrics:nil
                                                               views:@{ @"S": _s, @"F": _f }]];

The way I see things, this should allow me to resize the window freely, with F resizing to fill the space. But the constraints lock the window resizing completely.
Any idea what I'm doing wrong?
Thanks

A: I have seen this same basic issue crop up several times because one of the view's translatesAutoresizingMaskIntoConstraints property is YES.
This used to be controlled by a checkbox in Xcode's UI editor, but in Xcode 6.1.1 the checkbox is gone. However, for views created in code (e.g. WKWebView, which doesn't support instantiation from a .xib file), or for views created with earlier versions of Xcode, this property might be set to YES.
If so, that can cause auto-layout to behave in unexpected ways, often including your symptom that the window cannot be resized. You have manually configured the view to be resized with the window, but the automatic translation of autoresizing mask to constraints might add additional constraints, that cannot be simultaneously fulfilled if the window grows.
To illustrate, consider the method below. This extends NSView to add a method that resizes another view to the receiver's size, adds it as a subview of the receiver, and  sets up auto-layout constraints so that the subview grows and shrinks with its superview (the receiver).
However, we noticed a bug here, where it usually worked correctly, but sometimes the window containing all the views would become un-resizable. The reason turned out to be that subview.translatesAutoresizingMaskIntoConstraints was YES in some cases — and this caused unwanted additional layout constraints that prevented the window from resizing. Adding the second-to-last line fixed that bug.
That might be what is happening in your case (depending on how your views are being created).
@implementation NSView (Nakahara)

- (void)nakahara_embedSubview:(NSView *)subview;
{
    subview.frame = self.bounds;
    [self addSubview:subview];

    NSArray *newConstraints =
    @[
      [NSLayoutConstraint constraintWithItem:subview attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0],
      [NSLayoutConstraint constraintWithItem:subview attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0],
      [NSLayoutConstraint constraintWithItem:subview attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0],
      [NSLayoutConstraint constraintWithItem:subview attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0.0],
      ];

    subview.translatesAutoresizingMaskIntoConstraints = NO;
      // IMPORTANT! It took a while to figure out why this was sometimes working and sometimes not. It was because subview.translatesAutoresizingMaskIntoConstraints is sometimes YES and sometimes NO, and if it is YES, autolayout will break in undefined ways (e.g., windows suddenly become unresizable).

    [self addConstraints:newConstraints];
}

@end

A: When you create a new constraint, the default priority is 1000 (NSLayoutPriorityRequired). This means that the auto layout engine will potentially affect the window size in order to satisfy your constraints.
If you set the priorities of your constraint to something less than 500 (NSLayoutPriorityWindowSizeStayPut), you should get the behaviour you want.


text:
Q: How can we connect to a VM via anyconnect VPN in github actions I am trying to access my VM through sshpass but the problem is, We have an anyconnect VPN in the middle and that is preventing me to establish a connection to the server through github actions
How ever I can connect to that VPN in windows by using anyconnect tool.
and VPN also takes second password for more security.
Is there any way that I can connect to my VM via VPN through github actions workflow ?


text:
Q: Issue installing Ruby 2.7.2 on Mac I initially tried rbenv and followed this person's issue but I ended up switching to RVM and getting this error:
Error running '__rvm_make -j4',
please read /Users/thendralprabu/.rvm/log/1622423552_ruby-2.7.2/make.log

There has been an error while running make. Halting the installation.

Here's the order of steps I attempted so far.
rvm install 2.7.2
rvm get master
rvm reinstall 2.7.2

Here's what my make file is telling me, and my errors have been pointing me in the direction of the *include statement in the makefile, telling me that the file doesn't exist and I'm not sure how to address that.

A: What version of MacOS are you using?

*

*You can try to reinstalls the header files by this command:
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
Where 10.14 is you current MacOS version.

*If you on Big Sur you can try this solution.

*Also you can try install ruby with this flag:
export optflags=" -Wno-nullability-completeness " && rvm install 2.7.2
PS. I think "ruby-on-rails" tag is unnecessary.

A: I'd use brew
and rbenv
Follow this guide
https://gorails.com/setup/osx/11.0-big-sur
TO ruby install?
make sure to rehash.


text:
Q: CSS/div positioning that does not work in IE I have been searching for an answer for a good hour without luck so It may be OK to ask my silly question:
I am trying to overlay a legend over a map. The map is generated with openlayers and lives in a div called map. the legend is an html table but could be a picture as well and lives in another div called legend.
hence the HTML

and the CSS
* {
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
    border: none;
    font-family: Arial;
    font-size: 9px;
    text-decoration: none;
    text-align: left;
    }
html, body {
    background-color: red;
    }
#map{
    position:relative;
}
#legend{
  position:absolute;
  top: 1%;
  left: 100px;
}

This works just fine in Firefox, Safari and Chrome, but not in IE8.
In IE8 the legend is shown in its place, the red page background is behind but the map div has disappeared. Note that IE still loads the map tiles etc but seems to be putting them either behind the background or somewhere not on the screen...
If you have any suggestions, greatly appreciated!

A: Without the whole HTML page, it can be hard to give you a correct answer, to know what's exactly going on. Though you can use conditional IE tags to make your design work in Internet Explorer. More information here.
You will find that most IE8 quirks can be fixed by changing the positioning by a few pixels, position type, the display: value, or making elements at display:none;.
Firebug is your friend.


text:
Q: Creating & Updating UserProfiles in Django Django newbie here stumbling my way around the docs. I'm trying to create a user profile using Django's "UserProfiles", but I'm having a little trouble with figuring out the proper way to set the code based on Django docs.
Here's my code, based on the docs. (The create_user_profile is 100% from the docs).
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    user = models.OneToOneField(User)

    location = models.CharField(max_length = 100)
    website = models.CharField(max_length=50)
    description = models.CharField(max_length=255)
    fullName = models.CharField(max_length=50)
    email = models.EmailField(max_length = 100, blank = False)
    created = models.DateTimeField(auto_now_add=True)
    private = models.BooleanField()

    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance)

    post_save.connect(create_user_profile, sender=User)

What's the -proper- way to set and save these fields?
For example, if I have both the User and UserProfile models in one form (in a registration form, for example), how would I first create, then update all of this, before finally saving?

A:
how would I first create, then update all of this, before finally saving

These aren't separate steps. When you create or update a record in Django, you are saving it to the database.
For the registration form, I'd recommend you set it up as a ModelForm on User records, then specify the additional fields you want to save to the profile and save them separately in the save function, like so...
class RegistrationForm(forms.ModelForm):
    location = forms.CharField(max_length=100)
    # etc -- enter all the forms from UserProfile here

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', and other fields in User ]

    def save(self, *args, **kwargs):
        user = super(RegistrationForm, self).save(*args, **kwargs)
        profile = UserProfile()
        profile.user = user
        profile.location = self.cleaned_data['location']
        # and so on with the remaining fields
        profile.save()
        return profile

A: You could call profile.user.save() and after it profile.save() when you need to save data from registration form.


text:
Q: Multiline UILabel without word wrap? Is it possible to have a UILabel that consists of multiple \n-delimited lines to have lines with their width > the label width to be truncated and not wrapped?
Suppose I have some text like the following:

*

*This is a really long first line of text that is too long to fit horizontally

*Short line

*Another short line

I want this to appear in my UILabel like so:

1. This is a really long first line of text...
2. Short line
3. Another short line

However what is happening is I'm getting this:

1. This is a really long first line of text
that is too long to fit horizontally
2. Short line...

The third line is getting cut off. I've set the number of lines to 3, but it is still wrapping the first long line. It doesn't seem to matter what I set the line breaks property to on the label--it always wraps that first line. Is there any way to prevent wrapping completely on the label?

A: I don't think this is possible with any setting you can apply to your label. One way to do it, is to break the string into its individual lines, truncate any line that needs it so that it (with an added ellipsis) fits on one line, then put the string back together with line breaks. Something like this should work for any number of lines,
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (nonatomic) CGFloat ellipsisWidth;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *text = @"This is a really long first line of text that is too long to fit horizontally\nShort line\nAnother short line";
    NSString *ellipsis = @"...";
    self.ellipsisWidth = [ellipsis sizeWithAttributes:@{NSFontAttributeName:self.label.font}].width;

    __block NSMutableString *truncatedString = [@"" mutableCopy];
    [text enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
        [truncatedString appendFormat:@"%@\n", [self oneLineOfString:line withFont:self.label.font]];
    }];
    NSString *finalString = [truncatedString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    self.label.numberOfLines = 0;
    self.label.text = finalString;
}

-(NSString *)oneLineOfString:(NSString *) aLine withFont:(UIFont *) font {
    __block NSString *singleLine = nil;
    __block NSString *lastFragment;

    [aLine enumerateSubstringsInRange:NSMakeRange(0, aLine.length) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        NSString *textFragment = [aLine substringToIndex:(substringRange.location + substringRange.length)];
        CGRect textRect = [textFragment boundingRectWithSize:CGSizeMake(CGFLOAT_MAX ,CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
        if (textRect.size.width >= self.label.bounds.size.width - self.ellipsisWidth) {
            singleLine = [lastFragment stringByAppendingString:@"..."];
            *stop = YES;
        }
        lastFragment = textFragment;
    }];
    if (!singleLine) singleLine = aLine; // it doesn't need to be truncated, so return the passed in line
    return singleLine;
}

If you want to truncate by character instead of by word, you can pass NSStringEnumerationByComposedCharacterSequences instead of NSStringEnumerationByWords to the options parameter of
enumerateSubstringsInRange:options:usingBlock:.
Of course, you could do it the easy way; stack 3 labels on top of each other, and give each one a line of your text :)


text:
Q: how to change variable via AJAX? I need advice with AJAX.
I have page where i use to show info in block like:
<div1 container>
   <div2>
      some data
   </div2>
   <div3>
    <?php echo $variable;?>
   </div3>
</div>

and have another page that produce data:
function example( $array )
{
   ...some code...
return $answer
}

$variable = example($array);

i am sending AJAX query with some POST data from form and i need after operations  get new variable and put it in same  new params.
Here is my AJAX function:
function sendDataChild(btn) {
var form = $(btn).closest('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
    type: "POST",
    url: "get.php",
    dataType: "post",
    data: data,
    cache: false,
    success: function (data) {
        form[0].reset();
        //document.location.reload();
    },
    error: function (xhr, str) {
        alert('Возникла ошибка: ' + xhr.responseCode);
    }
});
return false;};

when i clear // and just reload page it works, but it is wrong way cause my page is quite big.
Can some body advise how to make it?

A: I think you want the success function to output the data into the div where you want the variable to show:
success: function (data) {
    form[0].reset();
    $("#divId").html(data);
}

A: Give a id to the div where you want to show the result
<div id="div3">

</div>

And you need to change your ajax
 function sendDataChild(btn) {
var form = $(btn).closest('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
    type: "POST",
    url: "get.php",
    dataType: "post",
    data: data,
    cache: false,
    success: function (data) {
        $('div3').html(data);
    },
    error: function (xhr, str) {
        alert('Возникла ошибка: ' + xhr.responseCode);
    }
});
}

A: HTML page
<div1 container>
   <div2>
      <!--some data-->
   </div2>
   <div3 id="div3">

   </div3>
</div>

PHP page
function example( $array )
{
   //...some code...
   echo $answer;
   exit;
}

And your JavaScript
function sendDataChild(btn) {
var form = $(btn).closest('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
    type: "POST",
    url: "get.php",
    dataType: "post",
    data: data,
    cache: false,
    success: function (data) {
        $('div3').html(data);
    }
});
}


text:
Q: Boost's stacktrace library doesn't work with C++ CLI I have been using the Boost stacktrace library to print out a stacktrace of my program.
Boost 1.78.0
When compiling with pure C++ it compiles and my program prints the stacktrace nicely.
However when compiling with C++ /CLI, my program doesn't print the stacktrace.
Here is my reproducable example :
#include <boost/stacktrace.hpp>
#include <sstream>
#include <iostream>
#include <string>

int main() {
    std::stringstream stack;
    stack << boost::stacktrace::stacktrace();
    std::string stacktrace = stack.str();      // The string "stacktrace" is empty when running with C++ CLI
    std::cout << stacktrace;
}

Compiling this with C++ /CLI doesn't print the stacktrace to stdout, whereas compiling with pure C++ does print it to stdout.
Another thing is that when I use boost/stacktrace/stacktrace.hpp instead of boost/stacktrace.hpp my program fails to print the stacktrace even in pure C++.
Unfortunately, I couldn't find any references to this issue on stack overflow.
I am on Windows, and I'm using Visual Studio 2022.
I am using Boost version Version: 1.78.0.
I installed boost with vcpkg.
Thank you

A: I don't think Boost Stacktrace claims CLR support.
I'd expect some output, but not particularly useful output.
Of course, in CLR mode, you can use .NET stacktraces: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace?view=net-6.0

Another thing is that when I use boost/stacktrace/stacktrace.hpp instead of boost/stacktrace.hpp my program fails to print the stacktrace even in pure C++.

That's probably because that's not correct usage. There's many nuts and bolts to configuring the library correctly, see https://www.boost.org/doc/libs/1_79_0/doc/html/stacktrace/configuration_and_build.html. One of the possible configurations leads to no-op implementation.


text:
Q: what would happen if I new a Local without a HandleScope in V8? is that allowed? Or what would happen if I do this.
Would this handle not be tracked by GC, or tracked by GC but not released?
In v8.h:
 /**
 * A stack-allocated class that governs a number of local handles.
 * After a handle scope has been created, all local handles will be
 * allocated within that handle scope until either the handle scope is
 * deleted or another handle scope is created.  If there is already a
* handle scope and a new one is created, all allocations will take
* place in the new handle scope until it is deleted.  After that,
 * new handles will again be allocated in the original handle scope.
*
* After the handle scope of a local handle has been deleted the
* garbage collector will no longer track the object stored in the
* handle and may deallocate it.  The behavior of accessing a handle
* for which the handle scope has been deleted is undefined.
*/
class V8_EXPORT HandleScope {

A: V8 blows up.   if you're running a debug build you'll get a nicer error message, but it will crash.
Something about "check_api_usage" or something like that.
I've seen that message too many times.
If you need to hold on to a javascript value longer than a lexical scope, you need to put it into a (more expensive) v8::Global<T> object instead.  Note that globals are move-only, similar to a unique_ptr.


text:
Q: casting producing const objects in c++ Would it be correct to say that whenever casting is used, the resulting object is a
const object?
...And therefore can only be used as an argument to a function if that
function accepts it as a const object?
e.g.
class C1 {
    public: C1(int i=7, double d = 2.5){};
};

void f(C1& c) {};

int main(){
    f(8);
    return 1;
}
//won't compile

(Of course if f(....) receives the argument by value then it gets a non-const version
which it can work with)

A: It's a little off to call this 'casting'.  You are doing 'implicit construction'.  Implicit construction always creates a temporary object, which in turn is always const.
Note you can mark the constructor 'explicit' and this would block the implicit construction call you're seeing here.  But that only means you would need f(C(8)) instead of f(8); the C instance would still be const because it is temporary, however note no cast is being done.
See also const_cast for dirty workarounds if you really, really need to.  The other workaround would be to do a two liner: C c(8); f(c);

A: Usually when an object of a certain type is converted to an object of another type (a non-reference type), a temporary object is created (not a const object).  A temporary object (invisible, nameless, rvalue) can only bind (in C++98/03) to references that are const (except for the temporary known as the 'exception object').  Therefore, the result of a conversion that creates a temporary can only be used as an argument to a function that either accepts it as a const reference, or as a type that it can be copied/converted into.
So for e.g.
void f(double);  // 1
void f(const int&); // 2
void f(int&); // 3

struct B {  B(int) { } };
struct C { C(int)  { } };
void f(B b);  // 4
void f(B& b); // 5
void f(const C& c); //6
void f(C& c); // 7

// D inherits from B
struct D : B { D(int) : B(0) { } };
void f(D& d); // 8

int main()
{
   f( (int) 3.0 ); // calls 2, NOT 3
   f( (float) 3 ); // calls 1 - const reference requires the same type
   f( 1 );  // calls 2, NOT 3

   f( (B) 1 ); // calls 4, not 5 - can accept it by non-const value
   f( (C) 1 ); // calls 6, not 7 - can accept it by const-reference

   f( (D) 1 ); // calls 4, not 8 - since a 'D' temporary object can be converted to a 'B' object - but will not bind to a non-const reference
}

Hope that helps.

A: You can rewrite that as:
class C1
{
    public: C1(int i=7, double d = 2.5){};

};

void f(C1& c){};

int main()
{
    C1 c(8); //named
    f(c);
    //... can access the modified C1 instance here ...
    return 1;
}

The thing that the compiler doesn't like about your version is that your C1 instance is an un-named temporary: which f will modify, but (because it's an un-named temporary) the compiler knows that the caller (main) has no way to receive/preserve/notice those modifications.


text:
Q: How can I add features to my mapbox-gl map in angular through a forEach loop? Because I need more than a single line on my map I'm trying to put multiple features in a single source.
Currently my typescript code looks like this where myRoutes is the array containing all the routes (coordinates for the line to draw), however this isn't the correct way to do it and it doesn't work (only the first line gets drawn).
myRoutes.forEach((element: any) => {
    this.map.addSource("route", {
        type: "geojson",
        data: {
            type: "FeatureCollection",
            features: [
                {
                    type: "Feature",
                    properties: {},
                    geometry: {
                        type: "LineString",
                        coordinates: [
                            [element.fromLon, element.fromLat],
                            [element.toLon, element.toLat]
                        ]
                    }
                }
            ]
        },
    });
});

this.map.addLayer({ ... });

Looking at the official documentation of MapBox (link) it's possible to add more than one in the following way:
...
{
    'type': 'Feature',
    'geometry': {
        'type': 'Point',
        'coordinates': [-121.415061, 40.506229]
    }
},
{
    'type': 'Feature',
    'geometry': {
        'type': 'Point',
        'coordinates': [-121.505184, 40.488084]
    }
},
...

So my question is how could I generate these blocks automatically with a forEach in my typescript file using the data of myRoutes?

A: Create a collection of features but only add it once as source for example:
const features =  myRoutes.map((element: any) => {
            {
                type: "Feature",
                properties: {},
                geometry: {
                    type: "LineString",
                    coordinates: [
                        [element.fromLon, element.fromLat],
                        [element.toLon, element.toLat]
                    ]
                }
         });

this.map.addSource("route", {
    type: "geojson",
    data: {
        type: "FeatureCollection",
        features
    },
});


text:
Q: Persona 3 lighting glitch on PS3? I'm playing Persona 3 FES on the PS3, downloaded from the PSN, and I've noticed certain light-colored textures in the game are flashing and very bright -- for example, the tubas in the music room, or (more painfully) the walls of the top block of Tartarus. Is this the result of anything I can control? Some setting on the PS3 or on my TV perhaps? It's starting to give me a headache.
An example of what I mean (note that the capture software in this video dulls the effect some, it's much brighter on my tv):

A: For lack of a better answer, this does in fact appear to be an error in emulation that is not fixable. :(


text:
Q: How do I use console to track mouse movement?
Possible Duplicate:
java console mouselistener

I have to make an interactive word search for my final project, but I don't know how to track mouse movements.
I found MouseMotionListener, but I only found examples that use the Swing class, which my teacher specifically told us not to use.
Are there ways to use MouseMotionListener with console? If not, how can I track mouse coordinates on the console screen?