text:
Q: Image Handler returning same image after multiple calls in asp.net Im trying to create an image handler for my website, the basic resizing, rotating and cropping works, and displays fine in the website however I tried to add caching to the handler by saving the file in /chached/filename.png but for some reason after I've added caching, the image handler is returning the wrong image. For example I have a project listing page where  the resized project images are displayed in a tabular view, however the first 4 projects display as having the same image and then the next 4 a different image but all the same, etc etc.
I have a feeling it's due to the response.outputstream but I'm not sure because it seems like it's not getting enough time to complete the first image before the next one is called.
Just in case, the full code is available here: http://pastebin.com/BNyDfqPy
My process request method is as follows:
public void ProcessRequest(HttpContext context)
{
    // Settings and locations
    appPath = HttpContext.Current.Request.PhysicalApplicationPath;
    location = context.Request.QueryString["image"];
    cacheLocation = Path.GetDirectoryName(appPath + location) + "/Cached/";

    // Input/Output
    Bitmap bitOutput;
    Bitmap bitInput = GetImage(context);

    if (cacheAvailable)
    {
        bitOutput = bitInput;
    }
    else
    {
        try
        {
            Boolean crop = false;

            if (context.Request["type"] == "crop")
            {
                crop = true;
            }

            bitInput = RotateFlipImage(context, bitInput);

            if (hasSetSize)
            {
                Int32 x = String.IsNullOrEmpty(context.Request["x"]) ? 0 : Int32.Parse(context.Request["x"]);
                Int32 y = String.IsNullOrEmpty(context.Request["y"]) ? 0 : Int32.Parse(context.Request["y"]);

                bitOutput = ResizeImage(bitInput, _width, _height, crop, x, y);

                bitOutput.Save(cacheLocation + cacheKey + ".png", System.Drawing.Imaging.ImageFormat.Png);
            }
            else
            {
                throw new Exception();
            }
        }
        catch (Exception)
        {
            bitOutput = bitInput;
        }
    }

    context.Response.Clear();
    context.Response.Cache.SetNoStore();
    context.Response.ContentType = "image/png";

    using (MemoryStream ms = new MemoryStream())
    {
        bitOutput.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.WriteTo(context.Response.OutputStream);
    }
    //bitOutput.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);

    bitOutput.Dispose();
    bitInput.Dispose();
    context.Response.Flush();

    return;
}

And I get the image using this:
public Bitmap GetImage(HttpContext context)
{
    // Get location
    Bitmap bitOutput = null;

    try
    {
        if (!String.IsNullOrEmpty(location))
        {
            Image image = Image.FromFile(appPath + location);
            bitOutput = new Bitmap(image);
            hasSetSize = SetHeightWidth(context, bitOutput);

            if (!System.IO.Directory.Exists(cacheLocation))
            {
                System.IO.Directory.CreateDirectory(cacheLocation);
            }

            // Generate cache key
            cacheKey = "imagehandler_" + _width + "x" + _height + "_" + context.Request["RotateFlip"] + context.Request["type"];

            if (File.Exists(cacheLocation + cacheKey + ".png"))
            {
                image = Image.FromFile(cacheLocation + cacheKey + ".png");
                bitOutput = new Bitmap(image);
                cacheAvailable = true;
            }
        }
        else
        {
            throw new Exception("Can't load original or save to cache, check directory permissions!");
        }
    }
    catch (Exception)
    {
        Image image = Image.FromFile(appPath + noImageUrl);
        bitOutput = new Bitmap(image);
    }

    return bitOutput;
}

I also have isReusable set as following:
public bool IsReusable
{
    get
    {
        return false;
    }
}

The output looks like the image below, every project has a different image set but they either show the same image as the previous/next image, it's own image (which is what I want) or the placeholder image:

A: As I see the code you have probably use static variable for the cacheAvailable and after is set to true is not get back to false for the next call.
So check when you make the cacheAvailable false as default for every request.

A: First, unless you really want your handler to be able to use the same instance over and over, have IsReusable return false.
If you don't want to do that, remove the cacheAvailable class level variable, change this:
// Input/Output
Bitmap bitOutput;
Bitmap bitInput = GetImage(context);

To this:
// Input/Output
Bitmap bitOutput;
bool cacheAvailable;
Bitmap bitInput = GetImage(context, out cacheAvailable);

And modify GetImage to look like this
public Bitmap GetImage(HttpContext context, out bool cacheAvailable)
{
    // Get location
    Bitmap bitOutput = null;
    cacheAvailable = false;

    try
    {
        if (!String.IsNullOrEmpty(location))
        {
            Image image = Image.FromFile(appPath + location);
            bitOutput = new Bitmap(image);
            hasSetSize = SetHeightWidth(context, bitOutput);

            if (!System.IO.Directory.Exists(cacheLocation))
            {
                System.IO.Directory.CreateDirectory(cacheLocation);
            }

            // Generate cache key
            cacheKey = "imagehandler_" + _width + "x" + _height + "_" + context.Request["RotateFlip"] + context.Request["type"];

            if (File.Exists(cacheLocation + cacheKey + ".png"))
            {
                image = Image.FromFile(cacheLocation + cacheKey + ".png");
                bitOutput = new Bitmap(image);
                cacheAvailable = true;
            }
        }
        else
        {
            throw new Exception("Can't load original or save to cache, check directory permissions!");
        }
    }
    catch (Exception)
    {
        Image image = Image.FromFile(appPath + noImageUrl);
        bitOutput = new Bitmap(image);
    }

    return bitOutput;
}


text:
Q: Make a panel using columns of a dataframe I have a dataframe in R where the first column represents the client IDs and the other columns are daily dates. For example
id <- seq(1:4)
qqqq141101 <- c(500, 0, 78, 10)
qqqq141102 <- c(500, 0, 78, 10)
frame <- data.frame(id, qqqq141101 , qqqq141102)
frame

I want to make a panel where I would have two dates for each client with corresponding values. Like this
id <- c(1,1,2,2,3,3,4,4)
day <- as.Date(c('2014-11-01', '2014-11-02', '2014-11-01', '2014-11-02','2014-11-01', '2014-11-02','2014-11-01', '2014-11-02'))
value <- c(500,500, 0, 0, 78, 78, 10, 10)
frame <- data.frame(id, day , value)
frame

My actual data consists of over 400 clients and over 100 day variables.
I would very much appreciate any help.

A: Something like this (requires R libraries reshape2 and lubridate).
# Your sample data
id <- seq(1:4)
qqqq141101 <- c(500, 0, 78, 10)
qqqq141102 <- c(500, 0, 78, 10)
frame <- data.frame(id, qqqq141101 , qqqq141102)

# Wide to long dataframe
require(reshape2);
df <- melt(frame, id.vars = "id");

# Get dates from column names
require(lubridate);
df$variable <- ymd(gsub("qqqq", "", df$variable));

# Order by id then date
df <- df[order(df$id, df$variable), ];
df;
#  id   variable value
#1  1 2014-11-01   500
#5  1 2014-11-02   500
#2  2 2014-11-01     0
#6  2 2014-11-02     0
#3  3 2014-11-01    78
#7  3 2014-11-02    78
#4  4 2014-11-01    10
#8  4 2014-11-02    10

A: You could also solve this with:
library(dplyr)
library(tidyr)
library(anytime)

frame %>%
  gather(day, value, -1) %>%
  mutate(day = anydate(gsub('qqqq','20',day))) %>%
  arrange(id)

The result:
  id        day value
1  1 2014-11-01   500
2  1 2014-11-02   500
3  2 2014-11-01     0
4  2 2014-11-02     0
5  3 2014-11-01    78
6  3 2014-11-02    78
7  4 2014-11-01    10
8  4 2014-11-02    10

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update smart table after content changed I have an array of objects, which I display using st-table directive.
I filter the table by a value of a certain field in the objects.
The problem is, once a value of a field in these objects has been changed, the filtering is not performed.
I believe the reason for it is that smart-table watches the array's length, but doesn't perform deep comparison to see whether or not the values inside any of the objects changed.
What can I do to solve this?
edit: added code:
angular.module('myApp', ['smart-table'])
    .controller('mainCtrl', ['$scope', '$timeout',
    function ($scope, $timeout) {

        $scope.rowCollection = [
        {
          name: "sth odd",
          number: 1
        },
        {
          name: "sth even",
          number: 1
        }
        ];

        $scope.displayedCollection = [].concat($scope.rowCollection);

        function changeNumber(){
          $timeout(function(){
            $scope.rowCollection[1].number = $scope.rowCollection[1].number === 1 ? 2 : 1;
            changeNumber();
          }, 1000);
        }

        changeNumber();

    }
]);

http://plnkr.co/edit/IVYy5WrsiEJSRXZCqY9z?p=preview
Notice how when you search e.g number "2", the view isn't updated even though the property of the second item sometimes is "2" and sometimes not.

A: Found a solution for you, instead of using st-search use a plain ng-model and then filter by the ng-model value. then in the ng-repeat filter by that value
so instead of this
<input st-search="number" placeholder="search for number" class="input-sm form-control" type="search"/>
...

    {{row.name}}
    {{row.number}}

do this
<input ng-model="searchMe" placeholder="search for number" class="input-sm form-control" type="search"/>
....

    {{row.name}}
    {{row.number}}

here's a plunker, enter 2 and see how it redos the filtering each time

A: To refresh the smart-table you can add or remove items as you know or use a new array.. so just recreate the array.
$scope.rowCollection = [].concat($scope.rowCollection);


text:
Q: Issue with PDF.JS in the latest version of aura components I'm making use of pdf.js library to parse a pdf into images. I'm importing the library by making use of static resources and this library/below logic is working fine if the custom component API Version is <= 39. If I try to increase the custom component api version above 39 I'm getting an error 'Uncaught Error in $A.getCallback() [Cannot read property 'document' of undefined]'
Error with this line: var loadingTask = pdfjsLib.getDocument({data: pdfData});
Sample Code
**HTML**
<ltng:require scripts='/resource/POC_PDF_JS ,
                      /resource/POC_PDF_WORKER_JS' afterScriptsLoaded="{!c.loadpdf}"/>

**JS Logic**
var pdfData = atob(pdfbase64data);
console.log('PDFJS ', pdfjsLib);    // this is getting printed as object which contains getDocument()
pdfjsLib.GlobalWorkerOptions.workerSrc = $A.get('$Resource.POC_PDF_WORKER_JS');
var loadingTask = pdfjsLib.getDocument({data: pdfData});
console.log('loadingTask ', loadingTask);

loadingTask.promise.then(function(pdf) {
    console.log('Debugger pdf ',pdf);
}, function(error) {
     alert(error);
});

I tried changing to different versions of library but I see same issue. Is there anything that i'm missing or is there any alternative way to do this.

A: Workers are not supported in Aura, and as a consequence, anything that tries to run a worker in Aura will inevitably fail. This limitation is on purpose, as workers would be able to circumvent Locker Service API security restrictions, and are therefore not allowed. You'll need to have it do its work without the benefit of a worker.

A: I fixed this issue by adding
globalThis = window;

before setting
pdfjsLib.GlobalWorkerOptions.workerSrc


text:
Q: Both AssertEqual and AssertNotEqual give failure in my unittest in Python I have this test code on Binary Tree:
def test_deleteMin_root(self):
    btree = BinaryTree()
    min_value = self.person('AAKVIK', 'ANNE-MARIT', 'RISØYVEGEN 17', '1705', 'SARPSBORG')
    node = BinaryTreeNode(min_value)
    btree.insert(value = min_value)
    btree.insert(value = self.person('Zero', 'Zero', 'Zero street', '1234', 'ZeroCity'))
    btree.deleteMin()
    self.assertEqual(node, btree.findMin())

I get this failure result:
======================================================================
FAIL: test_deleteMin_root (__main__.BinaryTreeTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\abdka\Documents\Programs\Python\PythonExercises\aicourse\test_binarytree.py", line 47, in test_deleteMin_root
    self.assertEqual(node, btree.findMin())
AssertionError: <BinaryTreeNode.BinaryTreeNode object at 0x000001C7E33EFA00> != <BinaryTreeNode.BinaryTreeNode object at 0x000001C7EAB5A6D0>

When I change AssertEqual to AssertNotEqual in the last line of the test code (and that's the only thing I change):
def test_deleteMin_root(self):
    btree = BinaryTree()
    min_value = self.person('AAKVIK', 'ANNE-MARIT', 'RISØYVEGEN 17', '1705', 'SARPSBORG')
    node = BinaryTreeNode(min_value)
    btree.insert(value = min_value)
    btree.insert(value = self.person('Zero', 'Zero', 'Zero street', '1234', 'ZeroCity'))
    btree.deleteMin()
    self.assertNotEqual(node, btree.findMin())

I get this failure:
======================================================================
FAIL: test_deleteMin_root (__main__.BinaryTreeTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\abdka\Documents\Programs\Python\PythonExercises\aicourse\test_binarytree.py", line 47, in test_deleteMin_root
    self.assertNotEqual(node, btree.findMin())
AssertionError: <BinaryTreeNode.BinaryTreeNode object at 0x000001C7EE3D4F10> == <BinaryTreeNode.BinaryTreeNode object at 0x000001C7E5DCAA00>

When I assert equal, it says they're not equal, and when I assert not equal, it says they're equal. I don't understand; what's the error here?  How can I fix it?
Here's the full test code, BinaryTree code and BinaryTreeNode code:
Binary Tree code:
from BinaryTreeNode import BinaryTreeNode

class BinaryTree:
    def __init__(self, data = None):
        self._root = None
        if isinstance(data, BinaryTreeNode):
            self._root = data

    def findLeftMost(self, treenode):
        left = treenode.left
        if left == None:
            return treenode
        return self.findLeftMost(left)

    def findMin(self):
        return self.findLeftMost(self._root)

    def findRightMost(self, treenode):
        right = treenode.right
        if right == None:
            return treenode
        return self.findRightMost(right)

    def findMax(self):
        return self.findRightMost(self._root)

    def find(self, key, treenode = None):
        if treenode == None:
            treenode = self._root
        if treenode == None:
            return None
        elif treenode.value > key:
            if treenode.left:
                return self.find(key, treenode.left)
        elif treenode.value < key:
            if treenode.right:
                return self.find(key, treenode.right)
        elif treenode.value == key:
            return treenode
        else:
            raise KeyError("Key not found")

    def _getnodes(self, current = None, treenode = None, value = None):
        if current != None and treenode != None:
            return current, treenode
        if value == None:
            if treenode == None:
                raise Exception("Attempt to insert an empty space into Binary Tree")
            else:
                if treenode.value == None:
                    raise Exception("Attempt to insert an Node into Binary Tree with no key value")
        else:
            if treenode != None:
                if treenode.value != None:
                    raise Exception("Key inconsistency detected")
            else:
                treenode = BinaryTreeNode(value)
        if current == None:
            current = self._root
        return current, treenode

    def insert(self, current = None, treenode = None, value = None):
        if current == None:
            current = self._root
        # Checking consistency ...
        current, treenode = self._getnodes(current, treenode, value)
        if current != None:
            if treenode.value < current.value:
                treenode.level += 1
                if current.left is None:
                    current.left = treenode
                else:
                    self.insert(current.left, treenode)
            elif treenode.value > current.value:
                treenode.level += 1
                if current.right is None:
                    current.right = treenode
                else:
                    self.insert(current.right, treenode)
            else:
                if self._root == None:
                    treenode.level = 0
                    self._root = treenode
                else:
                    raise Exception("Duplicate key: " + treenode.value)
        else: # If empty tree, the first node entered is the root
            self._root = treenode
        return treenode

    def deleteMin(self):
        parent = self._root
        while True:
            # If a left branch exists - find the smallest item
            current = parent.left
            if current:
                if current.left == None:
                    if current.right != None:
                        parent.left = current.right
                        return current
                    else:
                        parent.left = None
                        return current
                else:
                    parent = current
            # If no left branch exists, the root item is the smallest in the tree
            else:
                self._root = parent.right
                return self._root

    def deleteMax(self):
        parent = self._root
        while True:
            current = parent.right
            if current.right == None:
                if current.left != None:
                    parent.right = current.left
                    return current
                else:
                    parent.right = None
                    return current
            else:
                parent = current

    def delete(self, key):
        node = self.find(key)
        delnode = node
        if not node.left and not node.right:
            node = None
        elif node.right:
            temptree = BinaryTree(node.right)
            mintempnode = temptree.deleteMin()
            node.value = mintempnode.value
        elif node.left:
            node = node.left
        return delnode

Binary Tree Node code:
class BinaryTreeNode:
    def __init__(self, value,
                 lefttree = None,
                 righttree = None):
        self.value = value
        self.left = lefttree
        self.right = righttree
        self.level = 0

    # Bruker setter/getters
    @property
    def value(self):
        return self.__value

    @value.setter
    def value(self, value):
        self.__value = value

    @property
    def left(self):
        return self.__left

    @left.setter
    def left(self, lefttree):
        self.__left = lefttree

    @property
    def right(self):
        return self.__right

    @right.setter
    def right(self, righttree):
        self.__right = righttree

    @property
    def level(self):
        return self.__level

    @level.setter
    def level(self, level):
        self.__level = level

    def __str__(self):
        return self.value

    def hasRight(self):
        if self.right == None:
            return False
        return True
        #return self.right != None

    def hasLeft(self):
        if self.left == None:
            return False
        return True
        #return self.left != None

    def prefixOrder(self):
        print(str(self.value), ' ')
        if self.hasLeft():
            self.left.prefixOrder()
        if self.hasRight():
            self.right.prefixOrder()

    def infixOrder(self):
        if self.hasLeft():
            self.left.infixOrder()
        print(str(self.value), ' ')
        if self.hasRight():
            self.right.infixOrder()

    def postfixOrder(self):
        if self.hasLeft():
            self.left.postfixOrder()
        if self.hasRight():
            self.right.postfixOrder()
        print(str(self.value), ' ')

    def levelOrder(self):
        from queue import SimpleQueue
        FIFOQueue = SimpleQueue()
        FIFOQueue.put(self)
        self.levelOrderEntry(FIFOQueue)
        while not FIFOQueue.empty():
            node = FIFOQueue.get()
            print(str(node.value), ' ')

    def levelOrderEntry(self, queue):
        if queue.empty():
            return
        node = queue.get()
        print(str(node.value), ' ')
        if node.hasLeft():
            queue.put(node.left)
        if node.hasRight():
            queue.put(node.right)
        if node.hasLeft() or node.hasRight:
            self.levelOrderEntry(queue)

    def __eq__(self, other):
        if other != None:
            return self.value == other.value
        elif other == None and self.value == None:
            return True
        return False

    def __ne__(self, other):
        if other != None:
            if self.value == None:
                return False
            else:
                return not self.value != other.value
        return True

    def __lt__(self, other):
        if other != None:
            return self.value < other.value
        elif other == None and self.value == None:
            return False
        return False

    def __le__(self, other):
        if other != None:
            return self.value <= other.value
        elif other == None and self.value == None:
            return False
        return False

    def __gt__(self, other):
        if other != None:
            return self.value > other.value
        elif other == None and self.value == None:
            return False
        return False

    def __ge__(self, other):
        if other != None:
            return self.value >= other.value
        elif other == None and self.value == None:
            return False
        return False

The full test code:
import unittest
from BinaryTree import BinaryTree
from BinaryTreeNode import BinaryTreeNode
from collections import namedtuple

class BinaryTreeTest(unittest.TestCase):
    def setUp(self):
        self.person = namedtuple('person', ['lastname', 'firstname', 'address',
                                            'postalcode', 'city'])
        persons_file = open("Personer-kort.dta", 'r')
        content = persons_file.read()
        content = content.splitlines()
        self.binarytree = BinaryTree()
        for p in content:
            self.binarytree.insert(value = self.person(*p.split(';')))
        persons_file.close()

    def test_findMin(self):
        min_value = self.person('AAKVIK', 'ANETTE', 'BAKLIEN 11', '1360', 'NESBRU')
        node = BinaryTreeNode(min_value)
        self.assertEqual(node, self.binarytree.findMin())

    def test_findMax(self):
        max_value = self.person('ØYFOSS', 'ØISTEIN', 'ORHEIM 76', '0367', 'OSLO')
        node = BinaryTreeNode(max_value)
        self.assertEqual(node, self.binarytree.findMax())

    def test_deleteMin(self):
        self.binarytree.deleteMin()
        min_value = self.person('AAKVIK', 'ANNE-MARIT', 'RISØYVEGEN 17', '1705', 'SARPSBORG')
        node = BinaryTreeNode(min_value)
        self.assertEqual(node, self.binarytree.findMin())

    def test_deleteMin_root(self):
        btree = BinaryTree()
        min_value = self.person('AAKVIK', 'ANNE-MARIT', 'RISØYVEGEN 17', '1705', 'SARPSBORG')
        node = BinaryTreeNode(min_value)
        btree.insert(value = min_value)
        btree.insert(value = self.person('Zero', 'Zero', 'Zero street', '1234', 'ZeroCity'))
        btree.deleteMin()
        self.assertNotEqual(node, btree.findMin())

    def test_deleteMax(self):
        self.binarytree.deleteMax()
        max_value = self.person('ØYFOSS', 'WERNER STENVOLD', 'KIRKVOLL 28', '5935', 'LAVIK')
        node = BinaryTreeNode(max_value)
        self.assertEqual(node, self.binarytree.findMax())

    def test_find(self):
        value = self.person('SKARSHAUG','ASBJØRN HARALD', 'ALAPMO 72', '7290', 'STØREN')
        node = BinaryTreeNode(value)
        self.assertEqual(node, self.binarytree.find(value))

    def test_find_key_not_found(self):
        value = self.person('BORIS','JOHNSON', 'SOME STREET 72', '1234', 'LONDON')
        self.assertEqual(None, self.binarytree.find(value))
        self.assertRaises(KeyError, self.binarytree.find, value)

    def test_delete(self):
        value = self.person('SKARSHAUG','ASBJØRN HARALD', 'ALAPMO 72', '7290', 'STØREN')
        node = BinaryTreeNode(value)
        self.assertEqual(node, self.binarytree.find(value))
        self.binarytree.delete(value)
        self.assertEqual(None, self.binarytree.find(value))

    def test_insert_value(self):
        value1 = self.person('WIKILUND','JOHAN', 'SVETUN 11', '8510', 'NARVIK')
        node1 = BinaryTreeNode(value1)
        value2 = self.person('ALFRED', 'POLLEN', 'gate 11', '1234', 'KONGSBERG')
        node2 = BinaryTreeNode(value2)
        self.binarytree.insert(value=value1)
        self.binarytree.insert(value=value2)
        self.assertEqual(node1, self.binarytree.find(value1))
        self.assertEqual(node2, self.binarytree.find(value2))

    def test_insert_node(self):
        value1 = self.person('WIKILUND','JOHAN', 'SVETUN 11', '8510', 'NARVIK')
        node1 = BinaryTreeNode(value1)
        value2 = self.person('ALFRED', 'POLLEN', 'gate 11', '1234', 'KONGSBERG')
        node2 = BinaryTreeNode(value2)
        self.binarytree.insert(treenode=node1)
        self.binarytree.insert(treenode=node2)
        self.assertEqual(node1, self.binarytree.find(value1))
        self.assertEqual(node2, self.binarytree.find(value2))

    def test_insert_duplicate(self):
        value = self.person('SKARSHAUG','ASBJØRN HARALD', 'ALAPMO 72', '7290', 'STØREN')
        self.assertRaisesRegex(Exception, "Duplicate key", self.binarytree.insert, [None, None, value])

    def test_insert_empty_space(self):
        self.assertRaisesRegex(Exception, "Attempt to insert an empty space into Binary Tree",
                                self.binarytree.insert, [None, None, None])

    def test_insert_empty_node(self):
        node = BinaryTreeNode(None)
        self.assertRaisesRegex(Exception, "Attempt to insert an Node into Binary Tree with no key value",
                        self.binarytree.insert, [None, node, None])

    def test_find_in_empty_tree(self):
        tree = BinaryTree()
        value = self.person('SKARSHAUG','ASBJØRN HARALD', 'ALAPMO 72', '7290', 'STØREN')
        self.assertEqual(None, tree.find(value))

if __name__ == '__main__':
    import sys;sys.argv = ['', 'BinaryTreeTest']
    unittest.main()


text:
Q: The definition of topological manifold with boundary An $n$-manifold with a boundary is a second countable Hausdorff space in which any point has a neighborhood which is homeomorphic to an open subset of $\mathbb H^n = \{x\in \mathbb R^n:x_n\geq 0\}$ endowed with a Euclidean topology.

What I am confused about the definition is that what if there exists a neighborhood $U$ of $p\in X$ s.t. it is homeomorphic both to an open set of $\mathbb{H}^n$ which intersect $\partial\mathbb{H}^n$and an open set which is not.
Or another case what if there exist two neighborhoods $U,V$ of $p\in X$, with one homeomorphic to an open set of $\mathbb{H}^n$ which intersect $\partial\mathbb{H}^n$ and another one not.

A: This is not possible. If $V \subset \mathbb{H}^n$ and $V' \subset \mathbb{H}^n$ are open and homeomorphic, then either both intersect $\partial \mathbb{H}^n$, or neither of them does.
You can give several proofs of this, for example using relative homology (if $x \in \partial\mathbb{H}^n$ then $H_n(V, V \setminus \{x\}) = 0$, whereas if $x \not\in \partial\mathbb{H}^n$ then $H_n(V, V \setminus \{x\}) = \mathbb{Z}$).
Since you tagged this "differential geometry", here is a proof that uses the inverse function theorem. Suppose that $V \cap \partial\mathbb{H}^n = \varnothing$ while $V \cap \partial\mathbb{H}^n \neq \varnothing$, and suppose that you have a diffeomorphism $f : V \to V'$. Then since $V \cap \partial\mathbb{H}^n = \varnothing$, then $V \subset \mathbb{H}^n \subset \mathbb{R}^n$ is an open subset of $\mathbb{R}^n$. You can compose the map $f$ with the inclusion $i : V' \to \mathbb{R}^n$ to get a map
$$i \circ f : V \to \mathbb{R}^n.$$
Since $f$ was a diffeomorphism, the map $i \circ f$ is injective, and its differential is invertible everywhere. It follows by the inverse function theorem that $(i \circ f)(V) = V'$ is open in $\mathbb{R}^n$. Let $x \in V' \cap \partial \mathbb{H}^n$. Then since $V'$ is open in $\mathbb{R}^n$, it contains a small ball around $x$. But this ball will intersect $\mathbb{R}^n \setminus \mathbb{H}^n$, a contradiction as $V' \subset \mathbb{H}^n$.


text:
Q: UML Class Diagram Multiplicity I have a confusion in UML class diagram Multiplicity.
To ask my question , first i need to give you an example of a situation; Consider this requirement:
"Sections shall have many topics."
I can make the classes for Section and Topic with their multiplicity as follows :
Example 1)

The above relation can be read as : "One or more sections has many topics".
But consider this design also :
Example 2)

The above relation can be read as "One section has many topics , and one topic is in only one section."
Question 1 is :
What is the correct design?
Because for me i think the Example 2 design is the correct one, because i am considering only ONE instance at that particular time. But in Example 1 , they considered the Section class as a very high view! (Of course i can make infinity number of instances of any class...)
Question 2 is : In Example 2, do we say that there exists only one Section in the whole system, that's why we write it as in Example 1? Also in Example 1, This relation is Many to Many, so we need to make an association class to handle it.
I hope you understood my confusion, thanks in advance :D

A: Q1: In fact it depends on the requirements. A Topic can appear in many Sections as being discussed under different aspects. If you require that a topic must be completely covered in one section then your 2nd approach would be right. Anyhow, I think that the first is the more common way of doing things.
Q2: No. You only say that a Topic can have only one Section. To tell that there's only one section allowed you'd probably need a constraint. (I used a <<singleton>> stereotype for such purposes which is no UML standard, though.)
BTW: you multiplicity in ex. 2 is wrong. To the left you must only have 1..* and to the right only one 1.

A: In example 1 there are two independent statements:
Every instance of a section can have any number of topics and
every instance of a topic must have at least one section. I don't know whether this is what you meant.
PS: The composition, shown by the filled diamond, implies exclusivity. Therefore, the multiplicity can at maximum be 1, not 1..*.
An Association Class is not needed. Many to many relationships are just normal Associations.


text:
Q: Ajax request in symfony no return I have this template :

   Link

The js :
{% block javascript %}
{{ parent() }}

{% endblock %}

In the source of page I have :

The config for numbers_update route :
numbers_update:
path: /numbers/update
defaults: { _controller: ClientBundle:Admin/NumbersBlock:update }
requirements:
    _method:  POST

The methode updateAction()
public function updateAction(Request $request){
    $i_id = $request->request->get('id');
    $em = $this->getDoctrine()->getManager();

    return $this->json(array());
}

I use basic authentification, so I'm added this call in the security.yml :
access_control:
 - { path: ^/admin/homepage, roles: ROLE_ADMIN }
 - { path: ^/admin/numbers, roles: ROLE_ADMIN }
 - { path: ^/admin/numbers/update, roles: ROLE_ADMIN }

I'm logged now but I don't get a retourn after ajax request.
Please help me ! I don't understand what can be the problem. Do you have some ideas ? ...Thx in advance.

A: You're missing a return false on one of two possible places in your handler.
Either do this:
 onclick="changeNumber({{ number.getId }}); return false;"

or
 onclick="return changeNumber({{ number.getId }});"

If you go with the 2nd solution - you'll need to add a return false; at the end of your changeNumber function.
The problem here is that, when you click on this , the call to your handler actually works and it probably does the AJAX call, but you don't see it.
Since you are not preventing the default behavior of an a.click, the page actually follows the link given in the href (besides calling your handler) and you leave the current page (or possibly go again to same one).
Whether you go to different page or the same one, the WebDeveloper tool will most likely refresh and you won't see the AJAX call listed.
A tip for WebDeveloper tool: it may help to also enable the not-clearing of the Console and Network tabs between page submits and refreshes.

A: I think you have to :
use Symfony\Component\HttpFoundation\JsonResponse;

and
return new JsonResponse(array('key' => 'value' ));
//instead of
return $this->json(array());

Clear cache to be sure.
In chrome, you can find more about the error in "network" tab in developper tools (when you use ajax).

A: Link

I suggest you modify the href link, your href = "",
When you click on this page will refresh again. Even if you go away ajax. Because the refresh the page, you also look not to come out. You can instead
Href = "javascript:;" Elsewhere, and then you according to the normal way of thinking to write.


text:
Q: Importing javascript into html inline script for single file usage I am working on node express server which generates reports (tables, charts) for data stored in database (MongoDB). What makes it hard is that the report should be downloadable as a single file and viewable offline. Which means that all the data and javascript should be inside the html file.
By searching stackoverflow I found this question - Inline CSS/Javascript into a HTML file. One of the solutions is command-line tool which visits the page and bundles together all assets, other solutions use other languages. In my case it doesn't make sense to visit the page and download the files as they are already in memory and should be imported from node server.
So here is example of how I've been doing it so far.
Server.js:
// Templating library
const mustache = require("mustache");
// Javascript to be imported into html as inline script
const someFunction = require("./src/someFunction.js").toString();

app.get("/:id", async (req, res) => {
  // Get data from DB
  const data = await MongooseSchema.find({ id: req.params.id });

  // Read html view
  const view = fs.readFileSync("./views/report.html", "utf8"});

  // Render with mustache
  const html = mustache.to_html(view, {
    data,
    javascript: { someFunction }
  });

  // Send rendered html
  res.send(html);
});

And report.html includes this script tag:
<script>
  const data = {{{data}}};
  {{{javascript.someFunction}}}
</script>

I am importing javascript files as strings and then rendering them inside the html file using mustache templating library. This approach seems kind of hacky, there should be a better way.
Also I am thinking about implementing some bundler (webpack/parcel/rollup) to combine all the js files into one which I could then manually import into html as inline script.
And maybe even use some framework like react to make my life easier.
So my question is, is this approach viable? Are there any better ways to do this?


text:
Q: why am i geting an undefined reference linking error in C I'm doing some experiments with the nRF52840 and SEGGER Embedded Studio. I'm quite new to C but managed to get desired results using and changing the examples. I'm now trying to port the uart example to the two way ranging example to send the results to an external device but keep running into the following error:

I pinpointed the error (I think at least) to the following piece of code in a file named app_uart.h the problematic functions gets called in the second last line of the following code block:
uint32_t app_uart_init(const app_uart_comm_params_t * p_comm_params,
                       app_uart_buffers_t *           p_buffers,
                       app_uart_event_handler_t       error_handler,
                       app_irq_priority_t             irq_priority);

// TODO no reference to app_uart_init()

#define APP_UART_FIFO_INIT(P_COMM_PARAMS, RX_BUF_SIZE, TX_BUF_SIZE, EVT_HANDLER, IRQ_PRIO, ERR_CODE) \
    do                                                                                \
    {                                                                                \
        app_uart_buffers_t buffers;                                                                \
        static uint8_t     rx_buf[RX_BUF_SIZE];                                                    \
        static uint8_t     tx_buf[TX_BUF_SIZE];                                                    \
                                                                                \
        buffers.rx_buf      = rx_buf;                                                              \
        buffers.rx_buf_size = sizeof (rx_buf);                                                     \
        buffers.tx_buf      = tx_buf;                                                              \
        buffers.tx_buf_size = sizeof (tx_buf);                                                     \
        ERR_CODE = app_uart_init(P_COMM_PARAMS, &buffers, EVT_HANDLER, IRQ_PRIO);                  \
    } while (0)

The error is, according to SEGGER Embedded Studio, in my ds_twr_responder.c file pointing to the function call
 APP_UART_FIFO_INIT(&com_params, UART_RX_BUFF_SIZE, UART_TX_BUFF_SIZE, uart_err_handle, APP_IRQ_PRIORITY_LOWEST, err_code);

going to the declaration of the function brigs us to app_uart.h. this file is in de same directory as ds_twr_responder.c along with app_uart.c (in which the function is defined)
I don't really kno where to look as i'm not sure why this error could possibly pop up.
Is there some direction i should be looking in?


text:
Q: Uri is accepting domain without root? I trying to understand why Uri object is accepting this URL:
http://test/dir/page?id=1

I'm loading this URL with this code:
    string u = "http://test/dir/page?id=1";
    Uri url;
    if (!Uri.TryCreate(u, UriKind.Absolute, out url))
        throw new InvalidUrlException(u);

For me, this URL is seems missing.
What do you think?

A: It is a valid URL when your local server name is test.


text:
Q: Html from modules being escaped I have an issue with html output from a joomla module being escaped so that it's rendered as text .
I have no idea why this could happen, is it a joomla core issue?
This only started happening after an update

A: It looks like a problem with the extension that uses the {source} tags, rather than Joomla.  Googling says this is probably Sourcerer.
Make sure that Sourcerer is also patched and that the developer says it works on the version of Joomla you have updated to.  Also check that it is still published in your plug-ins list.  Third party extensions can often stop working if you update the core code and their code is for an earlier version of Joomla (or just badly written).
Looking at the code in your example, you probably don't actually need Sourcerer to add your code anyway as it is all HTML rather than server side code - just update the editor plugin's parameters to stop it stripping the tags you want to use. NB code needs to be added in the code view rather than the WYSIWYG view of the editor.
Sourcerer is really primarily for PHP, which makes me balk as it feels like a massive hack rather than an extension designed with good practise and Joomla's framework in mind.


text:
Q: How to make network adapter work only for specific application on windows 10? I'm using my Wi-Fi home to browsing internet and whatching youtube, on other side i connect my 3g phone with my computer using usb threading settings to play fortnite, what i want to do is to make this network adapter which receive internet from my 3g phone only wrk for my fortnite game, and the Wi-Fi adapter for all other my desktop application. and make all other application prevent to connect with the adapter which receive internet from 3g phone.
Edited: i found on the internet software called force bind ip, that software make inject self to the applications to do the job, but my questoin now is it safe to use with fortnite game?!
Thanks in advance


text:
Q: How to apply an Group Policy only to Clients in a specific IP range? (using WMI Filter) I need to apply a GPO only to some computers in a specific network range.
I'm aware that there many other solutions for this issue. I could group them into an OU or use Sites. But the current situation doesn't allow me to act in any other way except to determine if the IP address of the client is in a specific network.
Therefore I assumed I could use a WMI filter and I asked my good friend Google for help:
I found http://waynes-world-it.blogspot.ch/2008/03/wmi-filter-for-subnet-filtered-group.html but
Select * FROM Win32_IP4RouteTable
WHERE ((Mask='255.255.255.255' AND NextHop='127.0.0.1')
AND (Destination Like '10.31.%'))

doesn't seem to work.
The policy isn't applied to any computer due to the filter.
Can anyone give me hint how this could be solved?
Thank you very much

A: Got it:
SELECT * from Win32_IP4RouteTable
       WHERE ((Mask='0.0.0.0' AND NextHop LIKE '10.31.%'))

Works perfect. Seems the sample is either wrong or at least not applicable to Windows Server 2008 R2


text:
Q: why isn't my output value different from the expected value when I try to submitted the problem This is the two sum problem in leetcode.com:
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in nums:
            for j in nums:
                value = i + j
                if value == target and i != j:
                    return [nums.index(i),nums.index(j)]

when I ran the code, my output is [0,1], which is the same as the expected output, but when I submit the the question, the output is null. I just started learning coding, so please be as specific as possible. Thanks

A: You have some issues which I will help you fix but your solution probably still won't pass because of how slow it is.
Instead of going over every element using the second loop just go over the elements after the index of the first loop. (This also means you don't need to check if the indices are the same).
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)): # Only go i to end
                value = nums[i] + nums[j]
                if value == target:
                    return [i, j]
        return None # Its better to explicitly say what your are returning.

Note that the solution above is still extremely inefficient. You can do this faster using a dict since dictionaries have a O(1) look up time (in most cases), making the following solution O(n).
class Solution(object):
    def twoSum(self, nums, target):
        passed = dict()
        for index, num in enumerate(nums):
            if target - num in passed:
                return [passed[target - num], index]
            else:
                passed[num] = index


text:
Q: Distortion correction with open CV I am trying to correct image distortion with open CV.
The theory for the distortion I am trying to correct is a combined barrel and pincushion distortion like this:

I am not working with a normal camera here, but with a galvanometer scanning system (like this: http://www.chinagalvo.com/Content/uploads/2019361893/201912161511117936592.gif), so I cannot just record a checkerboard pattern like all the OpenCV guides suggest.
But I can move the scanner to a target position and measure the actual position of the laser beam in the image plane, which plots e.g. to this:

So I put those values into OpenCV's calibrateCamera function in this script:
import numpy as np
import cv2

targetPosX = np.array([-4., -2., 0., 2., 4., -4., -2., 0., 2., 4., -4., -2., 2., 4., -4., -2., 0., 2., 4., -4., -2., 0., 2., 4.])
targetPosY = np.array([-4., -4., -4., -4., -4., -2., -2., -2., -2., -2., 0., 0., 0., 0., 2., 2., 2., 2., 2., 4., 4., 4., 4., 4.])
actualPosX = np.array([-4.21765834, -2.14708042, -0.07755157, 1.9910175, 4.05941744, -4.17816164, -2.10614537, -0.03775821, 2.02883123, 4.09875409, -4.13937186, -2.07079973, 2.07072068, 4.1377518, -4.10200901, -2.03229052, 0.0367603, 2.10655379, 4.17627114, -4.06449305, -1.99426964, 0.07737988, 2.14365487, 4.21625359])
actualPosY = np.array([-4.04808315, -4.08681247, -4.12545265, -4.16807799, -4.20657896, -1.98568911, -2.0217478, -2.06356789, -2.10326313, -2.14456442, 0.07567631, 0.03889721, -0.04043382, -0.08069954, 2.14054726, 2.09940048, 2.05965315, 2.02167639, 1.9800822, 4.20167787, 4.16215278, 4.12334605, 4.08099448, 4.04376011])

scale = 100 # px / mm
height = 9 * scale # range of measured points is -4 to 4mm --> show area from -4.5 to 4.5 with 100 px / mm
width = 9 * scale

def scale_and_shift(array, scl, shift):
    array *= scl
    array += shift
    return array

# shift recorded positon into image coordinate system
targetPosX = scale_and_shift(targetPosX, scale, width / 2.)
targetPosY = scale_and_shift(targetPosY, scale, height / 2.)
actualPosX = scale_and_shift(actualPosX, scale, width / 2.)
actualPosY = scale_and_shift(actualPosY, scale, height / 2.)

# create images
target_image = np.full((height,width), 255)
combined_image = np.full((height,width), 255)
actual_image = np.full((height,width), 255)
for i in range(len(targetPosX)):
    cv2.circle(target_image, (int(targetPosX[i]), int(targetPosY[i])), 20, 0, -1)

    # circle in combined image is target position, full point is actual position
    cv2.circle(combined_image, (int(targetPosX[i]), int(targetPosY[i])), 20, 0, 5)
    cv2.circle(combined_image, (int(actualPosX[i]), int(actualPosY[i])), 20, 0, -1)

    cv2.circle(actual_image, (int(actualPosX[i]), int(actualPosY[i])), 20, 0, -1)

cv2.imwrite("combined_before.png", combined_image)

# create point lists for calibrateCamera function. set 3rd dimension to zero.
targetPoints = np.array([np.vstack([targetPosX, targetPosY]).T]).astype("float32")
targetPoints_zero = np.array([np.vstack([targetPosX, targetPosY, list(np.zeros(len(targetPosX)))]).T]).astype("float32")
imagePoints = np.array([np.vstack([actualPosX, actualPosY]).T]).astype("float32")
imagePoints_zero = np.array([np.vstack([actualPosX, actualPosY, np.zeros(len(actualPosX))]).T]).astype("float32")

# read image to apply to
# saving and reading because just passing the actual_image somehow didn't work
cv2.imwrite("image.png", actual_image)
img = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE)
h, w = img.shape[:2]

# calulate distortion matrix
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(targetPoints_zero, imagePoints, (h,w), None, None)

# refine distortion matrix to avoid cut-off
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))

# undistort
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)

cv2.imwrite('calibresult.png', dst)
cv2.imwrite("correction.png", dst - actual_image)

for i in range(len(targetPosX)):
    # circle in combined image is target position, full point is actual position
    cv2.circle(dst, (int(targetPosX[i]), int(targetPosY[i])), 20, 0, 5)

cv2.imwrite('combined_result.png', dst)

However, the result is not as expected - the corrected image does not line up with the target image (full dots - corrected actual points. Circles - target points):

Comparing before and after shows that just a minimal correction / distortion compensation was applied (just calculated the diff of before and after for the actual image:

Is there any way I can tweak the calibrateCamera? Or is this just the wrong tool for this job?

A: I don't have enough reputation to comment, so I have to post an answer.
For users that struggle with camera calibration might be helpful to keep in mind, that it is not always possible to fit perfectly a lens distortion model. And that if you are not sure about your lens, you can try both rectilinear, and fish-eye distortion. link
Before deep diving into the OpenCV calibration tweaking, you should read calibration good practices.
If your setup is precise enough, you might consider using higher feature count. Using fine patterns is preferable.
Try to simulate what people do with their chessboards. Collect images from different areas and tilts:

*

*Try shifting the whole grid to different directions. Try to get as close to edges as possible. (there is the strongest distortion)

*If you have an option to tilt your marking field, please do. Then you can calculate the "undistorted" points with basic geometry. (See homogeneous coordinates)

And finally, you can try to simulate different calibration patterns. For example asymmetric circles. If your setup is precise enough, you might be able to sample border of each circle.


text:
Q: Android Parsing 5mb json file causing, Out of Memory Exception I am trying to parse a json file of 5mb, which is causing out of memory exceptions, I know the solution for this is to use json stream parser,
But I need to know why this is happening when Android devices has 1GB ram, at least it can allocate 100MB to my application I think, what going on?

A: Many other apps will claim their portion of 1GB, and you have to have enough free RAM to make garbage collection efficient.
Your app can only get 24 MB for its entire process. Some of it must be kept free for GC, and some of it is taken by other classes, data, and uncollected garbage.
Parsed JSON is essentially a number of nested lists and hashes. Assume that every (boxed) number takes 4-16 bytes, each entry in a hashtable takes another 4-8 bytes for hash + 4 bytes for pointer, plus some overhead due to load factor below 1, strings become UCS2 even if ASCII would be enough, etc. Long JSON with many small objects can easily take 10x the RAM.
Try not to parse the entire file into memory, unless you need the whole of it in RAM for operation. Try streaming parser and writing things into a database.

A: One option: android:largeHeap.  The official documentation on this is distressing, but AFAICT it allows you 256MB of heap, and it was introduced in 3.0

A: Try to use following library to parse your json data
http://code.google.com/p/google-gson/


text:
Q: How to import a js file in a Chrome extension service worker? I am trying to use socket.io library in a service worker of y Chrome extension, but when I try to load it in Chrome I get the error: Uncaught SyntaxError: "Cannot use import statement outside a module".
I got the library from here, then I saved the it in my extension folder, in socketIo.js:

Then in my service_worker.js, I try to import it:
import io from './socketIo.js';
const socket = io("http://localhost:3002");

Since it as service worker, I do not attach it to my extension html file, therefore I can't simply set the worker as a module like this:
<script type="module" src="./service_worker.js"></script>.

Also, since extensions are not Node.js applications, they don't have a package.json where I could set the property "type": "module.
And as you can see I used both the relative path and the extension of the file imported, as suggested here: Chrome Extension Service Worker not Supporting Importing Other JS Files or NPM Packages
Now I've added the ES module version of socket.io and its "map" file.
And updated my service worker in manifest.json to be a ES module too:

But when I tried to load the extension again, I get this warning: "Service worker registration failed. Status code: 3", and the generic error:

A:
Since it as service worker, I do not attach it to my extension html
file, therefore I can't simply set the worker as a module like this: .
Also, since extensions are not Node.js applications, they don't have a
package.json where I could set the property "type": "module.

Register the service worker

You can optionally specify an extra field of "type": "module" to
include the service worker as an ES Module, which allows you to import
further code.

manifest.json
{
    "manifest_version": 3,
    "name": "socket.io",
    "version": "1.0",
    "background": {
        "service_worker": "background.js",
        "type": "module"
    }
}

But the socket.io version you're using isn't an ES Module:
Uncaught SyntaxError: The requested module '/socket.io.js' does not provide an export named 'default'

So I downloaded socket.io.esm.min.js and socket.io.esm.min.js.map from https://cdn.socket.io/4.5.3
I don't know if they have an ES Module version of socket.io 1.7.3
Including the .map file in the extension prevents this error in the service worker console:

DevTools failed to load source map: Could not load content for
chrome-extension://cfdinlnmiepoligakoinbffeaphkfmmp/socket.io.esm.min.js.map:
System error: net::ERR_FILE_NOT_FOUND

background.js
import io from "/socket.io.esm.min.js";
const socket = io("http://localhost:3002");

The service worker console still gets flooded with this error:

Event handler of 'beforeunload' event must be added on the initial evaluation
of worker script.

But I think there's a solution for that on Stackoverflow.
Or not:

*

*Add Socket.io to service_worker (chrome extension)

*Remote Socket.io Connection not working from a manifest v3 extension
Also, put the libraries socket.io.esm.min.js and socket.io.esm.min.js.map inside the same folder of service worker, in the same level (not in a sub folder).
After you made this changes, just refresh you extension in chrome://extensions/. But if this doesn't work, delete your extension and load it unpacked again.


text:
Q: How to add commas automatically for every 3 numbers while user input the text field - iOS Objective C How to add commas for every 3 numbers while user inputting the text field and also display the number with commas on the label?
I am using this function but it does not work.
- (void)commaFormatter
{
  NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
  [numberFormatter setGroupingSeparator:@","];
  [numberFormatter setGroupingSize:3];
  [numberFormatter setDecimalSeparator:@"."];
  [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
}

A: If you want a number like 123,456,789,5 then use shouldChangeCharactersInRange delegate method and write below code inside it.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *strTemp = textField.text;
    strTemp = [textField.text stringByReplacingOccurrencesOfString:@"," withString:@""];
    if (strTemp.length%3==0&&![string isEqualToString:@""]&&textField.text.length!=0&&![[textField.text substringWithRange:NSMakeRange(textField.text.length-1, 1)] isEqualToString:@","]) {
        _txtField.text = [_txtField.text stringByAppendingString:@","];
    }
    return YES;
}


text:
Q: Como montar o operator == de um struct? Eu tenho os structs a seguir:
struct Arco {

  int i, j;
  Arco () {};
  Arco (const Arco& obj): i(obj.i), j(obj.j) {};
  Arco(int _i, int _j) : i(_i), j(_j) {}

};

struct ARCO_TEMPO {
  Arco a;
  int slotTimeU;
  int slotTimeV;
  ARCO_TEMPO () {};
  ARCO_TEMPO (const ARCO_TEMPO& obj): a(obj.a), slotTimeU(obj.slotTimeU),     slotTimeV(obj.slotTimeV) {};
  ARCO_TEMPO (Arco _a, int _slotTimeU, int _slotTimeV, int _order) : a(_a), slotTimeU(_slotTimeU), slotTimeV(_slotTimeV) {}

};

struct CICLO {
  vector<ARCO_TEMPO> arco_tempo;
  set<ARCO_TEMPO> arco_tempo_order;
  set<int> arco_tempo_Aux;
  int aircraftType;
  float COST;
};

Ao longo do meu algoritmo, eu crio CICLOs e guardo-os em um set (pois preciso granatir que não guardarei ciclos repetidos).
Defini, então, os seguintes operators:
bool operator<(const ARCO_TEMPO& obj1, const ARCO_TEMPO& obj2) {
  if (obj1.slotTimeU < obj2.slotTimeU) {
    return true;
  }
  else {
    if (obj1.slotTimeU == obj2.slotTimeU && obj1.slotTimeV < obj2.slotTimeV) {
      return true;
    }
    else {
      if (obj1.slotTimeU == obj2.slotTimeU && obj1.slotTimeV == obj2.slotTimeV && obj1.a.i < obj2.a.i) {
        return true;
      }
      else {
        if (obj1.slotTimeU == obj2.slotTimeU && obj1.slotTimeV == obj2.slotTimeV &&obj1.a.i == obj2.a.i && obj1.a.j < obj2.a.j ) {
          return true;
        }
        else{
          return false;
        }
      }
    }
  }
}

bool operator==(const ARCO_TEMPO& obj1, const ARCO_TEMPO& obj2) {
  if (obj1.slotTimeU == obj2.slotTimeU && obj1.slotTimeV == obj2.slotTimeV &&obj1.a.i == obj2.a.i && obj1.a.j == obj2.a.j ) {
    return true;
  }
}

bool operator<(const CICLO& obj1, const CICLO& obj2) {

  if (obj1.COST < obj2.COST - 1) {
    return true;
  }
  else {
    if ( (abs(obj1.COST - obj2.COST) < 1) && obj1.aircraftType < obj2.aircraftType) {
      return true;
    }
    else {
      if (obj1.aircraftType == obj2.aircraftType && (abs(obj1.COST - obj2.COST) < 1) && obj1.arco_tempo_order.size() < obj2.arco_tempo_order.size()) {
          return true;
      }
      else {
        if (obj1.aircraftType == obj2.aircraftType && (abs(obj1.COST - obj2.COST) < 1) && obj1.arco_tempo_order.size() == obj2.arco_tempo_order.size()) {
          bool igual = true;
          set<ARCO_TEMPO>::iterator itobj1;
          set<ARCO_TEMPO>::iterator itobj2;
          for (itobj1 = obj1.arco_tempo_order.begin(), itobj2 = obj2.arco_tempo_order.begin();  itobj1 != obj1.arco_tempo_order.end(); itobj1++,itobj2++) {
            if (igual && *itobj1 < *itobj2) {
              return true;
            }
            else {
              if (*itobj1 == *itobj2) {
                igual = true;
              }
              else {
                return false;
              }
            }
          }
          return false;
        }
        else{
          return false;
        }
      }
    }
  }
}

// estrutura que guarda os ciclos criados
set<CICLO> ConjCiclos;

//crio um ciclo
CICLO cc;
// preencho esse ciclo ...

// antes de adiciona o ciclo verifico se e ele ja nao foi adicionado através da função:

bool is_CycleIT_a_new_one(CICLO &it, set<CICLO> &ConjCiclos) {

  return ConjCiclos.count(it) == 0;

}

Porém, ocorre de adicionar em ConjCiclos, um ou outro ciclo repetido.
Debugando o código, percebi que o operator == definido para a struct ARCO_TEMPO, não está funcionando.
Quando eu troco a comparacao de dois ARCOs_TEMPO no operator< da struct CICLO:
if (*itobj1 == *itobj2) {

por:
if (itobj1->a.i == itobj2->a.i && itobj1->a.j == itobj2->a.j && itobj1->slotTimeU == itobj2->slotTimeU && itobj1->slotTimeV == itobj2->slotTimeV) {

o algoritmo funciona ok, sem adicionar ciclos repetidos.
Alguém sabe me dizer o que está errado na definição do meu operator==?

A: Você retorna true quando os objetos são iguais...
bool operator==(const ARCO_TEMPO& obj1, const ARCO_TEMPO& obj2) {
  if (obj1.slotTimeU == obj2.slotTimeU && obj1.slotTimeV == obj2.slotTimeV &&obj1.a.i == obj2.a.i && obj1.a.j == obj2.a.j ) {
    return true; // OK
  }
}

...mas nunca retorna false quando os objetos são diferentes. Ao invés disso, permite que o fluxo chegue ao final da função sem retornar nenhum valor. De acordo com o padrão do C++, o comportamento nesse caso é indefinido.
Para corrigir, basta retornar false quando os objetos são diferentes:
bool operator==(const ARCO_TEMPO& obj1, const ARCO_TEMPO& obj2) {
  if (obj1.slotTimeU == obj2.slotTimeU && obj1.slotTimeV == obj2.slotTimeV &&obj1.a.i == obj2.a.i && obj1.a.j == obj2.a.j ) {
    return true;
  } else {
    return false;
  }
}

Ou, mais concisamente:
bool operator==(const ARCO_TEMPO& obj1, const ARCO_TEMPO& obj2) {
   return obj1.slotTimeU == obj2.slotTimeU && obj1.slotTimeV == obj2.slotTimeV &&obj1.a.i == obj2.a.i && obj1.a.j == obj2.a.j
}

Um pouco de conhecimento extra não faz mal a ninguém...
Se me permite um pequeno adendo: Algumas features introduzidas na versão 2011 do C++ (C++11) facilitariam bastante a sua vida, e seu compilador provavelmente já está configurado para utilizá-las.
#include <algorithm>
#include <iostream>
#include <iterator>

struct Arco {
  int i, j;

  bool operator==(const Arco& rhs) {return i == rhs.i && j == rhs.j;}
};

struct ARCO_TEMPO {
  Arco a;
  int slotTimeU;
  int slotTimeV;
  // Para structs triviais, não há a necessidade de criar construtores.
  // Bastar usar listas de inicialização (Com chaves ao invés de parênteses)

  bool operator==(const ARCO_TEMPO& rhs) {return slotTimeU == rhs.slotTimeU && slotTimeV == rhs.slotTimeV && a == rhs.a;}
};

int main() {
    // O compilador é esperto o suficiente para inicializar as structs
    // conforme a ordem dos elementos. (E ainda inicializa structs aninhadas!)
    ARCO_TEMPO t{{1,1}, 1, 1};
    ARCO_TEMPO a[] {
        {{1,1}, 1, 1}, // Igual
        {{1,1}, 1, 0}, // Diferente
        {{1,1}, 0, 1}, // Diferente
        {{1,0}, 1, 1}, // Diferente
        {{0,1}, 1, 1}  // Diferente
    };

    // Para cada item do vetor, imprime "Igual" se o item for igual a 't',
    // ou "Diferente" se o item for diferente de 't'.
    std::transform(std::begin(a), std::end(a),
        std::ostream_iterator<std::string>(std::cout),
        [&t](const ARCO_TEMPO& i) {
            return t==i?"Igual\n":"Diferente\n";
        });
}

Saída:
Igual
Diferente
Diferente
Diferente
Diferente

Ver ao vivo!


text:
Q: How can I persit the ouath tokens so that Im can use them in future? I am developing an application which require integration with twitter. I am using twitter4j api .
I have to persist the ouath tokens so that my application can interact with twitter in future.
I save the access token and access token secret . However when I am reusing them I am getting an exception token expire .
Could you please let me know the way I can reuse them and what is the expiration period of the ouath tokens ?

A: from Twitter's OAuth FAQ:

How long does an access token last?
We do not currently expire access tokens. You access token will be invalid if a user explicitly rejects your application from their settings or if a Twitter admin suspends your application. If your application is suspended there will be a note on your application page saying that it has been suspended.

A: You should use cookies to save your oauth token and oauth token secret and then make subsequent requests using by retrieving cookie data.
Like in php , i use it like this:
setcookie('oauth_token', $token->oauth_token);
setcookie('oauth_token_secret', $token->oauth_token_secret);

You can access these values by $_COOKIE['oauth_token'] and $_COOKKIE['oauth_token_secret'].but this is in php. You should see how you have to do it in JAVA.
Hope this helps you Anshul.


text:
Q: A question regarding integration over $\varnothing$ Does $\int_\varnothing f(x)dx = 0$ make any sense? Is one allowed to use $\varnothing$ this way?

A: The integral over an empty set makes perfect sense even with Riemann integration: note that the empty set is closed.


text:
Q: Given a Cerberus JSON Schema file, how can I generate a dictionary object Problem
I have a Cerberus Json schema file and I need to generate Json files based on the schemas with default values given the data_types.  The key _type in the dictionary objects is the data_type to check against.
A sample Cerberus Json Schema
{
    "schema": {
        "vars": {
            "forest_config": {
                "_type": "list",
                "_required": false,
                "_not_empty": false,
                "_item_schema": {
                    "_type": "dict",
                    "always_create_dl_here": {
                        "_required": false,
                        "_type": "bool"
                    },
                    "ldap_domain": {
                        "_type": "string",
                        "_required": false
                    },
                    "dc_dn": {
                        "_type": "string",
                        "_required": true,
                        "_not_empty": true,
                        "_regex": "^(DC|O)=[\\w\\-\\. &]+(,(DC|O)=[\\w\\-\\. &]+)*$"
                    },
                    "user_ou": {
                        "_type": "string",
                        "_required": true,
                        "_not_empty": false,
                        "_regex": "^((CN|OU)=[\\w\\-\\. &]+(,(CN|OU)=[\\w\\-\\. &]+)*)?$"
                    },
                    "group_ou": {
                        "_type": "string",
                        "_required": true,
                        "_not_empty": false,
                        "_regex": "^((CN|OU)=[\\w\\-\\. &]+(,(CN|OU)=[\\w\\-\\. &]+)*)?$"
                    },
                    "dl_group_ou": {
                        "_type": "string",
                        "_required": true,
                        "_not_empty": false,
                        "_regex": "^((CN|OU)=[\\w\\-\\. &]+(,(CN|OU)=[\\w\\-\\. &]+)*)?$"
                    }
                }
            }
        }
    }
}

I tried making my own recursive function, however I am getting stuck
        new_obj = {}
        def recursively_generate_schema_obj(dict_obj: Dict):
            if isinstance(dict_obj, dict):
                var_name = None
                for key, value in dict_obj.items():
                    if not str(key).startswith("_"):
                        var_name = key

                    if var_name and '_type' not in dict_obj:
                        new_obj[var_name] = {}
                    elif var_name and '_type' in dict_obj and dict_obj['_type'] == 'list':
                        new_obj[var_name] = [recursively_generate_schema_obj(dict_obj)]
                    else:
                        new_obj[var_name] = create_default_type_value(dict_obj['_type'])

                    recursively_generate_schema_obj(value)

        recursively_generate_schema_obj(schema_data)

    def get_default_value(data_type:str):
        if data_type == 'string':
            return ''
        elif data_type == 'dict':
            return {}
        elif data_type == 'bool':
            return False
        elif data_type == 'list':
            return []
        elif data_type == 'int':
            return 0
        elif data_type == 'enum': # this needs to be handled in the calling function
            return ''

Current Output of my code
{'schema': {}, 'vars': {}, 'forest_config': {}, None: '', 'always_create_dl_here': {}, 'ldap_domain': {}, 'dc_dn': {}, 'user_ou': {}, 'group_ou': {}, 'dl_group_ou': {}}

This is definitely wrong
it should be like
{
    "schema": {
        "vars": {
            "forest_config": [
                {
                    "always_create_dl_here": false,
                    "ldap_domain": "",
                    "dc_dn": "",
                    "user_ou": "",
                    "group_ou": "",
                    "dl_group_ou": ""
                }
            ]
        }
    }
}

Ask
Can someone help me figure this out and explain some possible better approaches?

A: You were pretty close to something that will work. I modified the function to take a var_name and json_obj along with the var_schema. It can then add the var_name to the supplied json_obj using the _type from the var_schema. If there are more variables defined in the var_schema, then it recalls the function to add each one. Passing the schema details for that variable and also the json_obj to add the variables to.
I'm not familiar with the Cerberus Json schema you mention, so you'll probably want to add some extra code in the get_default_value function. Hopefully the details for your enum type are in the schema.
def get_default_value(var_schema: dict):
    data_type = var_schema.get('_type', 'dict')
    if data_type == 'string':
        return ''
        # return var_schema.get('_regex', '')  # use this if you want to get the regex as the default value
    elif data_type == 'dict':
        return {}
    elif data_type == 'bool':
        return False
    elif data_type == 'list':
        return []
    elif data_type == 'int':
        return 0
    elif data_type == 'enum':  # this needs extra handling?
        return ''

def recursively_generate_schema_obj(var_schema: dict, var_name=None, json_obj=None):
    """ Add the supplied var_name to the supplied json_obj. The type of variable added is determined by the '_type'
    field in the supplied var_schema.

    Once the variable has been added, find variables in the supplied schema and recursively call this function to
    add any found.

    :param var_name: Name of variable to add to supplied json_obj
    :param var_schema: Schema with details of variables to add below this variable
    :param json_obj: The json object to add the variable to. This can be a dict or a list. If it's a list, then the
    supplied var_name is not used and an item of type defined in the var_schema is simply appended to the list
    :return: The json_obj
    """
    if isinstance(var_schema, dict):

        next_level = get_default_value(var_schema)
        if json_obj is None:
            json_obj = next_level
        elif isinstance(json_obj, list):
            json_obj.append(next_level)
        else:
            json_obj[var_name] = next_level

        # Find each sub field in the schema and add it to the next level
        # These are keys without an '_' or, for the items to add to a list the '_item_schema'.
        for key, value in var_schema.items():
            if not str(key).startswith("_") or key == '_item_schema':
                recursively_generate_schema_obj(value, key, next_level)

    return json_obj

schema_data = {
    'schema': {
        'vars': {
            'forest_config': {
                '_type': 'list',
                '_required': False,
                '_not_empty': False,
                '_item_schema': {
                    '_type': 'dict',
                    'always_create_dl_here': {'_required': False, '_type': 'bool'},
                    'ldap_domain': {'_type': 'string', '_required': False},
                    'dc_dn': {'_type': 'string', '_required': True, '_not_empty': True,
                              '_regex': '^(DC|O)=[\\w\\-\\. &]+(,(DC|O)=[\\w\\-\\. &]+)*$'},
                    'user_ou': {'_type': 'string','_required': True,'_not_empty': False,
                                '_regex': '^((CN|OU)=[\\w\\-\\. &]+(,(CN|OU)=[\\w\\-\\. &]+)*)?$'},
                    'group_ou': {'_type': 'string', '_required': True, '_not_empty': False,
                                 '_regex': '^((CN|OU)=[\\w\\-\\. &]+(,(CN|OU)=[\\w\\-\\. &]+)*)?$'},
                    'dl_group_ou': {'_type': 'string', '_required': True, '_not_empty': False,
                                    '_regex': '^((CN|OU)=[\\w\\-\\. &]+(,(CN|OU)=[\\w\\-\\. &]+)*)?$'}
                }
            }
        }
    }
}

new_obj = recursively_generate_schema_obj(schema_data)
print(new_obj)

The above code produces:
{
    'schema': {
        'vars': {
            'forest_config': [{
                'always_create_dl_here': False,
                'ldap_domain': '',
                'dc_dn': '',
                'user_ou': '',
                'group_ou': '',
                'dl_group_ou': ''
            }]
        }
    }
}


text:
Q: PC as Bluetooth Headset for iPhone I am trying to set up my computer (running Windows 8.1) as a headset for answering/making calls for my iPhone 4S. I have connected my iPhone through bluetooth, and can listen to music and create keyboard inputs, but cannot use Handsfree!

I have all of the services enabled for the iPhone:

I don't understand why my PC cannot act as a bluetooth headset, as Hands-free is selected! I have the latest bluetooth drivers installed for my computer. My guess is that it may be two drivers not working correctly (seen in Device Manager):

Could these two drivers (MAP MAS-iOS and Wireless iAP) not being installed be the cause of the problem? I have been searching for these drivers online and cannot find them.

A: It turns out that these features are specific to the manufacturers Bluetooth drivers. I was able to find another manufacturers drivers, and they have hands-free as a function:


text:
Q: Manually classifying graduated data outside of range in ArcGIS for Desktop? I have two shapefiles representing grids with values that are symbolized with graduated colors, shown below:

You can see that the two shapefiles encompass similar ranges of data, but assign slightly different colors to ranges in these data.  I would like to symbolize the ranges in each of the two shapefiles using the same colors for the same ranges, enabling easier comparison between the files and allowing a single legend to be used.
However, when I attempt to classify the ranges with a manual interval, ArcGIS forces what should be the uppermost range to also include the minimum value from the dataset.  You can see this in the "-81.64 - 10.00" range of the left data frame, below.  This forces the entire layer to be symbolized with this color.  Essentially, ArcGIS is requiring that the minimum value in the dataset be used as a value in one of the ranges.

Is there a way to circumvent this feature?

A: @ChrisW said:

As far as I know and can find evidence for, you cannot set a classification range below the minimum value in the data.

This got me thinking, and I actually found a way to set the classification range below the minimum value.  My original issue was built around the fact that the lowest classification range was required to contain the minimum value in the data.
However, no such restriction is placed on the other classification ranges used.  Therefore, one can force two (or more) classification ranges to fall below the minimum value in the data.  One of these will represent the preferred minimum classification range, while the other will function as a dummy range to contain the minimum value.

Here is the starting point that I used for the classification.  Each of the layers in the four data frames were classified using a defined interval of 10 ft without respect to the data ranges of the other layers.

The maximum classification range in any of the four data frames is "0.01 to 10.00", and the minimum classification range is "-110.62 to -110.00" (which will ideally become "-119.00 to -110.00").  Since I am attempting to maintain 10 foot intervals, this translates to a total of 13 intervals.

I am using the top left data frame as the source for my generic legend.  I start by opening up the Layer Properties and going to Classify.  Since I want 13 intervals to be visible, I need to select 14 intervals to have a dummy range available.  I do this by selecting Manual as the method and creating 14 classes.

With the ranges set up in their current state (with the largest values at the top), any changes to the value entered in the range will have no effect on anything other than the range at the very bottom of the list.  @ChrisW pointed out that this isn't a bug, but rather a feature of how ArcGIS assigns break values.  Here is the Layer Properties window after selecting the Manual method but before making any changes to the ranges:

To solve this issue, I temporarily reverse the sorting of the layer.  At this point, the lowest ranges are at the top, while the highest ranges are at the bottom.

Now, if I scroll to the bottom of the list of ranges (where the highest range is displayed) and begin defining the proper intervals from the bottom up, ArcGIS will remember the ranges I define:

In this image, I have defined the upper value in 5 of the 14 ranges, starting with the largest value (10.00) and working downward.

When I reach the top of the list and edit my 14th range, its minimum value will still be defined as the minimum value in the layer, since it does not have another range below it for it to pull a value from:

This does not matter, though, since it is the dummy range that I mentioned before.  At this point, I reverse the sorting of the layer once more, so the highest ranges are again at the top.  The image below shows the updated legend for the top left data frame, which now reflects the proper ranges for all four data frames, including the 14th dummy range:

The next step is to propagate these changes through to the rest of the data frames.  Some issues are apparent, though, when I try to import the symbology to the other data frames:

As @ChrisW pointed out, this is due to my decision to start with a layer that does not have the absolute minimum value across all of the data frames.  It appears that the data frame will not display any ranges that fall below the ranges that exist in the original data frame.
If you are starting with a layer like the one I did, the best solution that I have found for this is to repeat the steps that I discussed above for each of the four data frames; manually defining 14 classes, reversing the sorting of the classes, redefining the top of each range, then reverting the sorting to place the highest ranges at the top.
The simplest solution, though, is to start the classification process with the layer that has the smallest value.  The Import Symbology option may then be used properly for the other data frames.

Finally, I can delete three of the legends and either hide the dummy range in the remaining legend or convert it to graphics and delete the dummy range.

A: I came across this same problem, I think....
If I understand it right you had two (or more) datasets and you need to get the dataset scale ranges to match so that comparisons can be made.
I solved it by:

*

*Create you're first dataset as you want it to appear. Ideally with the largest data range just so that symbols can be copied over easier to the second (smaller ranged) dataset.

*Create you're second dataset but don't worry about the any symbology just yet. In the second datasets Layer Properties > Symbology tab choose the same type of classification as with the first dataset, for this example I'm using Categories > Unique Values then click the Add All Values button.

*Group values so that they fall into the corresponding ranges used in the first dataset. Select all values for a particular category and then right click and select Group. The top two categories have already been grouped in the image below, the four highlighted vales are about to be "pulled" into a third group.

*I find it easier at this stage to relabel the categories so that it's easier to keep track of. At this point you can see five of the seven categories populated.

*Finally (almost) and the crux of this problem, to add in the empty categories that exist outside the data range of the second dataset. In the Layer Properties > Symbology tab click the Add Values button and populate with the required categories above and below the data ranges as required.

*Lastly relabel the new empty categories so that the correspond with the first dataset and then recolour each category so that it matches with the firsts.

Sorry if that's a little over simplified or even plain wrong / bad practice. I've been a long time user of GIS Stack Exchange and thought it about time I started contributing so this is my first post!

A: *

*Choose the number of classes you want.

*Right click on the symbols and select save class breaks

*this saves an xml file you can open and edit in any text-editor

*edit the class breaks you want in the xml file and save

*right click on the symbols again and import the newly edited class breaks file

DONE

A: While the classification uses similar ranges, the data don't share a range. I think the solution here is to solve it in the legend and color assignments, and not the actual classification.
Start with your lower left result, and convert that legend to a graphic. Edit the text to get the ranges you want. I notice all your other images have a 10 unit range, but this one is doing 20 and it overlaps. For example three of the images have -49.99 to -40.00 but the lower left has -49.99 to -60.00, and the next class is -59.99 to -70.00. The images are also opposite ranges - ie three are lower value on the left while the lower left is lower value on the right (which reads a lot more natually to me, increasing numbers if not values from left to right).  Maybe those issues need to be addressed first to save some time rather than just a manual text edit.
Once you have a legend with ranges and a color ramp you like, you can go back to your first two layers (which are already classified correctly) and manually edit each range's color patch to match the color you decided on for the range in the legend. Since the two layers won't be displaying their own legends, it won't matter that in one of them the range is actually -89.99 to -80.00 and the other is -81.64 to -80.00 because they'll both have the same color.
Do note, however, that this will imply both data sets have the same range, which they don't. In fact it looks like there will be two color patches that are only used in one map each (the highest and lowest). You might want to put a note on each map that gives their absolute data range. I would also use 'to' instead of '-' between ranges, because with the negative values it's kind of confusing to read.

Alternative solution:
As far as I know and can find evidence for, you must have a class which starts at your minimum value. You can manually add classes (even empty ones) above or below your data range, but one class must start at the minimum value.
So, set your symbology up using the raster that contains the lowest/minimum value of all rasters. Get these symbolized. You can then edit the class label to say whatever you want. So if your lowest value was 0.4, you could still change the label to say 0.
Once you've got this done and set up with the color ramp you like, save a lyr file of the symbology. You should then be able to open your other rasters and apply that same symbology. Because the other rasters will all have values that are higher, they should classify correctly and just the minimum value itself will increase (or perhaps that class will get dropped if nothing falls within it). Which again you can change the class label to the class floor instead of actual value if that doesn't carry over with the symbology.

A: An easier but also dirtier solution that has worked for me. Don't forget to create a backup of your original data.

*

*Open the Attribute Table and Start Editing

*Edit any two values manually so the minimum and the maximum value you want your classification to be based on are included (remember the original values)

*Save and Stop Editing

*Classify based on the new extrema

*Start over and manually replace the altered values with the original values

*The existing classification won't be affected

A: I believe this is about feature legend but not rasters. If this is about rasters disregard my suggestion. I usually use these:

*

*Merge 2 (or more shapefiles) CHILDS into one, let's call it FAMILY

*create legend for FAMILY

*import symbology for every CHILD from FAMILY

Hope it helps, FP

A: I did the following workaround. I created my own class breaks in an XML document and loaded it to the classified symbology of both layers.

*

*To get a template of a class breaks-XML-document:
in the layer properties click right on the range of classification and then "save class breaks".

*Edit XML document:
enter the breaks of classes in the XML document, you can also enter numbers that will be out of range of your datasets.

*Load XML class breaks:
same menue where you saved the template (see 1), click "load class breaks"

A: It's definitely a major pain when ArcMap tries to be, um, helpful even when you really don't want it to be.
One workaround I've found is to create a new temporary dataset, and add a few points with the minimum and maximum values that you know you'll need in the output - just be sure to cover the whole range.
Create your symbology based on this fake dataset and save this symbology in a layer file:

... then Import the symbology from the *.lyr file onto your real dataset:

A: An alternate way is to combine all the values from each layer into one layer, using this way you will have the minimum and maximum values in on layer.
The illustration:
1.combine the values from all layers into one column (let's name it as All_Vals) in an excel sheet

*next to the All_Vals column add two new columns named as X and Y and fill them with zeros.

*In arcmap add the excel sheet as a table and use it to create a point feature class by using display xy data command/tool then export the event layer to a shapefile ( I'll name it NB_Point) and add it to the data frame.
4 . Convert the NB_Point shape file to much the feature class type of your layers, for example if the type of your feature layer is polygone, use the buffer tool to create polygone feature class from the NB_Point shapefile (let's name it as NB_polygon).

*Now you all you have to do is to right-click the final layer NB_polygon and apply the graduated color symbology using natural breaks classification, export it to a .lyr file to use it as the input layer when using the import layer symbology utility for each of the original layers.

Hope this helps and sorry for any misspelling.


text:
Q: XMLSerializer - Why is there an extra child layer while serializing? I'm serializing a complex C# object to XML document using XMLSerializer. The issue I'm facing is that after serializing, I'm getting an extra layer of child container that shouldn't be there. I'm not sure how it is getting serialized as. My object structure is follows:
[XmlRoot(ElementName = "order")]
public class order
{
    [XmlElement(ElementName = "orderNumber")]
    public string OrderNumber { get; set; }
    [XmlElement(ElementName = "products")]
    public Products Products { get; set; }
}

[XmlRoot(ElementName = "products")]
public class Products
{
    [XmlElement(ElementName = "product")]
    public List<Product> Product { get; set; }
}

[XmlRoot(ElementName = "product")]
public class Product
{
    [XmlElement(ElementName = "quantity")]
    public decimal Quantity { get; set; }
    [XmlElement(ElementName = "part")]
    public string part { get; set; }
   [XmlElement(ElementName = "unitPrice")]
    public decimal UnitPrice { get; set; }
}

I want to serlize it as order/products/product, however, it is getting serialized as order/products/product/product:
<order>
  <orderNumber>1</orderNumber>
  <products>
    <product>
      <product>
        <quantity>1</quantity>
        <part>222584</part>
        <unitPrice>5.0</unitPrice>
      </product>
      <product>
        <quantity>5</quantity>
        <part>222</part>
        <unitPrice>1.0</unitPrice>
      </product>
      <product>
        <quantity>15</quantity>
        <part>222244</part>
        <unitPrice>12.0</unitPrice>
      </product>
    </product>
  </products>
</order>

A: To remove extra tag over products then your xml serialization class should be as below:
[XmlRoot(ElementName = "order")]
public class order
{
    [XmlElement(ElementName = "orderNumber")]
    public string OrderNumber { get; set; }
    [XmlElement(ElementName = "products")]
    public List<Product> Products { get; set; }
}

Current class structure is written to create hierarchy
[XmlRoot(ElementName = "order")]
    [XmlElement(ElementName = "products")]
        [XmlElement(ElementName = "product")]
             [XmlRoot(ElementName = "product")]<-Final Product data here

Below extra layer is not required and just use List directly within your order.
[XmlRoot(ElementName = "products")]
public class Products
{
    [XmlElement(ElementName = "product")]
    public List<Product> Product { get; set; }
}


text:
Q: $G$ has a unique normal subgroup of order $p$ iff $G$ is cyclic center. Let $G$ be a p-group. Proof that $Z(G)$ is cyclic if and only if $G$ has a unique normal subgroup $H$ of order $p$.
I am supposed to prove it without using Sylow theorems. I already prove the first implication, I am struggling with the reverse. Here is what I have so far:
I already know that $Z(G)$ is a subgroup of $G$ then $|Z(G)|=p^k$ for some $k\in \mathbb{Z}$. Also, p divides |Z(G)|, by Cauchy's theorem there exists $a\in Z(G)$ such that $|a|=p$. $Z(G)$ is abelian so every subgroup is normal, then $\langle a \rangle $ is a normal subgroup of $G$ of order p. Thus, $\langle a \rangle = H $ and $H\subset Z(G) $ .
From this point, I don't know what else to do. I was trying to prove that $Z(G)=H$, is this true? What else can I try?
Thank you for your help.

A: Let $H$ be a normal group of order $p$, $G/H$ is a $p$-group, whose center is not trivial and $p:G\rightarrow G/H$ the quotient map.
If $|G/H|>p$ and the its center $H_1$ is distinct of $G/H$, $p^{-1}(H_1)$ is a normal subgroup distinct of $H$. If $G/H$ is commutative, it contains a normal subgroup $H_1$ distinct of $G/H$, take $p^{-1}(H_1)$.
Group with order $p^2$ must be abelian . How to prove that?
If $|G/H|=p$, $G$ is Abelian it is isomorphic to $\mathbb{Z}/p\times\mathbb{Z}/p$ or to $\mathbb{Z}/(p^2)$
There exists only two groups of order $p^2$ up to isomorphism.
https://en.wikipedia.org/wiki/P-group#Non-trivial_center


text:
Q: Error while trying to run npx create-react-app in WSL I am trying to test that npx create-react-app is working. It feels like I have tried everything under the sun and still cannot get it to work. I think it has something do with pathing but I am not exactly sure, and a little bit out of my depth here.
'\\wsl.localhost\Ubuntu-22.04\home\pat\sei\testing'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.
node:fs:1395
  handleErrorFromBinding(ctx);
  ^

Error: EPERM: operation not permitted, mkdir 'my-app'
    at Object.mkdirSync (node:fs:1395:3)
    at module.exports.makeDirSync (C:\Users\Patrick\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\fs-extra\lib\mkdirs\make-dir.js:23:13)
    at createApp (C:\Users\Patrick\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js:257:6)
    at C:\Users\Patrick\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js:223:9
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  errno: -4048,
  syscall: 'mkdir',
  code: 'EPERM',
  path: 'my-app'
}

Node.js v18.12.1

I tried to run npx create-react-app my-app. I at first I got an error with node being out of date. So I updated it. That update broke my path again, and so I uninstalled node, then reinstalled it. I then tried it again and it said that the script installed successfully. But when I go to actually use it, I get the above error message.
Update
I did a little more "experimenting" and ran this: npx create-read-app ./ and go this error
'\\wsl.localhost\Ubuntu-22.04\home\pat\sei\testing'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.
Cannot create a project named "Windows" because of npm naming restrictions:

  * name can no longer contain capital letters

Please choose a different project name.

still lost to be honest

A: So, this might not be the best solution, but a work around. If you leave the unbuntu terminal, and open powershell, run wsl. it will be the same CLI, but within powershell, and will get around the issues.


text:
Q: Define a dynamic variable name and use it before its definition I searched on the Internet but I did not find any solution for my problem, so I ask here.
Short Question
Is there a way to define a dynamic variable name in LaTex and use it before its definition?
Context
I have a large tex file; in one part I have sections included from external files. I don't want to change the content of the external files before the include as they are generated from an external source. I can still change the template of the external file, so in the files I add dynamically created label and variable based on the value of a counter.
The objective is to dynamically create a summary of this part of the document before it. I can easily reference to the dynamic label either before or after the definition. But I can only access the value of the variable after the definition.
main.tex
\begin{document}

\begin{itemize}
    \item \nameref{foo:1}: \csname fooscore1\endcsname
    \item \nameref{foo:2}: \csname fooscore2\endcsname
\end{itemize}

\newcounter{foo}

\input{section1}

\input{section2}

\begin{itemize}
    \item \nameref{foo:1}: \csname fooscore1\endcsname
    \item \nameref{foo:2}: \csname fooscore2\endcsname
\end{itemize}

\end{document}

section1.tex
\section{section1}

\stepcounter{foo}
\label{foo:\thefoo}
\expandafter\def\csname fooscore\thefoo \endcsname{10}

Counter: \thefoo\\
Score: \csname fooscore\thefoo\endcsname

section2.tex
\section{section2}

\stepcounter{foo}
\label{foo:\thefoo}
\expandafter\def\csname fooscore\thefoo \endcsname{20}

Counter: \thefoo\\
Score: \csname fooscore\thefoo\endcsname

Question
Is there any way to access the value of the fooscore1 and fooscore2 before the include (like the dynamic label)? Note that the value of the fooscores are not necessarily integers.
I try to cheat by creating a dummy section with the value of the variable as title and the variable name as label, but I cannot find a way to hide it from both the document and the table of content.
Thank you very much for your answers!

A: Simply use another label:
\documentclass{article}

\usepackage{hyperref}
\begin{document}

\begin{itemize}
    \item \nameref{foo:1}: \ref*{score:1}
    \item \nameref{foo:2}: \ref*{score:2}
\end{itemize}

\newcounter{foo}

\section{section1}
\stepcounter{foo}
\label{foo:\thefoo}
\expandafter\def\csname fooscore\thefoo \endcsname{10}
\makeatletter
\def\@currentlabel{\csname fooscore\thefoo \endcsname}
\makeatletter
\label{score:\thefoo}

Counter: \thefoo\\
Score: \csname fooscore\thefoo\endcsname

\section{section2}
\stepcounter{foo}
\label{foo:\thefoo}
\expandafter\def\csname fooscore\thefoo \endcsname{20}
\makeatletter
\def\@currentlabel{\csname fooscore\thefoo \endcsname}
\makeatletter
\label{score:\thefoo}

Counter: \thefoo\\
Score: \csname fooscore\thefoo\endcsname

\end{document}

You can also look at zref which offers extended possibilities to store values and reference them.


text:
Q: A question about transforming graphs I'm studying for a test I have tomorrow and I have a question about a review question in my book. I've never tried transforming functions with more than one $x$ value and I'm at a bit of a loss. Google searching and experimenting on Wolfram Alpha haven't helped.
I have a graph with the function $y = \sqrt{3x – x^2}$ that looks like this:

And I need to write a transformed function that looks like this:

Could someone help me out?

A: Hint.  You can break the transformation up into three steps.

*

*Turn the graph upside down.

*Move it one unit downwards.

*Move it $4$ units to the left.

Can you put these successively into algebraic language?

A: Hint : The first graph is a semicircle with centre at (1.5,0) and radius = 1.5 . The second graph is another semicircle with radius 1.5, and centre (-2.5, -1). This means that you have to transform the coordinates such that the centers aline and then choose the negative half of the circle you get. $x' = x - 4$ and $y' = y - 1$ would work.


text:
Q: Radio button text not aligned properly So i am trying to add radio button on my survey form and the button and the text is completly in different positions so here is a picture of how it looks --> enter image description here
i tried display: inline; but still nothing changed

A: The below code will work as you expected. Just add necessary attributes like name and for.

Would you recommend this survey to your friend:

 <input type="radio" name="test" value="yes">
 Yes

A: According to the picture, your input tag width is 100%, that's why you are facing this issue. Add class inside input and use this CSS your problem has been fixed.

**HTML**

Would you recommend this survey to your friend:

<input type="radio" name="test" value="yes" class="inline-radio" >
Yes


text:
Q: How to create a custom domain link using branch doesn't send any valuable information in Android Using branch.io I'm able to target specific URL in my app.
Since I use custom domain name I can't do it anymore on Android.
When I use a link like

myapp.com/#/param
  , myapp.com being registered on https://dashboard.branch.io/link-settings , I get my url in the "non_branch_link" attribute of the branch data in iOS and on browser, but not on Android where it is something like "myapp://open?link_click_id=123456789XXX".

Do you know how I can recover the initial URL or if it's a bug ?
Thank you :)

A: If you are opening the Android app via URI scheme (e.g. Chrome), that is the expected result. If you want the "non_branch_link" attribute to contain the initial URL, you must implement App Links (Android equivalent of Universal Links) to open the app directly:
I/BranchSDK: posting to https://api.branch.io/v1/install
I/BranchSDK: Post value = {"hardware_id":"39caf5fa-39ae-45c8-88b9-de1c061c6dab","is_hardware_id_real":false,"brand":"LGE","model":"Nexus 5X","screen_dpi":420,"screen_height":1794,"screen_width":1080,"wifi":false,"ui_mode":"UI_MODE_TYPE_NORMAL","os":"Android","os_version":26,"country":"US","language":"en","app_version":"1.0","facebook_app_link_checked":false,"is_referrable":1,"debug":true,"update":2,"latest_install_time":1510601387046,"latest_update_time":1527289172137,"first_install_time":1510601387046,"previous_update_time":0,"environment":"FULL_APP","uri_scheme":"directory","android_app_link_url":"https:\/\/directory.app.link\/ThHCzVJvdN","external_intent_uri":"https:\/\/directory.app.link\/ThHCzVJvdN","cd":{"mv":"-1","pn":"com.brian.directory"},"metadata":{},"instrumentation":{"v1\/install-qwt":"0","v1\/install-brtt":"32"},"sdk":"android2.18.1","branch_key":"key_test_okzKiOjpEQ59noo95HfDxfgbDsfdcPCW"}
I/BranchSDK: returned {"session_id":"528681555951304587","identity_id":"528681555917749106","link":"https://directory.test-app.link?%24identity_id=528681555917749106","data":"{\"+non_branch_link\":\"https://directory.app.link/ThHCzVJvdN\",\"+clicked_branch_link\":false,\"+is_first_session\":true}","device_fingerprint_id":"528681555808722227"}
I/Choreographer: Skipped 157 frames!  The application may be doing too much work on its main thread.
I/BRANCH SDK: {"+non_branch_link":"https:\/\/directory.app.link\/ThHCzVJvdN","+clicked_branch_link":false,"+is_first_session":true}