text:
Q: Combining templates and inheritance in tree conversion I have data stored in a C++ tree structure which I read in from a file. The tree looks like that:
class BaseNode {
  std::vector<BaseNode*> children_;
  ...
};
class WhiteNode : public BaseNode { ... };
class BlackNode : public BaseNode { ... };

After the tree is built, I would like to convert it, e.g. to a string.
In order to keep the tree code separate from the conversion code, I would like to use templates, i.e. implementing something like that:
template <class T>
T WhiteNode::Convert() { ... };

However, since the tree nodes are stored as BaseNode*, I don't know how to access such a template member function. And since template member functions cannot be inherited, I don't think this will work.
I did come up with a working solution, though:
class BaseConversion {
public:
  virtual ~BaseConversion() {}
  virtual void * FromBlack() = 0;
  virtual void * FromWhite() = 0;
};

template <class T>
class Conversion : public BaseConversion {
public:
  void * FromBlack();
  void * FromWhite();
};

class BaseNode {
  std::vector<BaseNode*> children_;
  virtual void * Convert(BaseConversion * conversion) = 0;
public:
  virtual ~BaseNode() {}
  template <class T>
  T Convert() {
    return *static_cast<T*>(Convert(new Conversion<T>));
  }
};

class WhiteNode : public BaseNode {
  void * Convert(BaseConversion * conversion) {
    return conversion->FromWhite();
  }
};

class BlackNode : public BaseNode {
  void * Convert(BaseConversion * conversion) {
    return conversion->FromBlack();
  }
};

And the transformation logic can be entirely separate:
template <>
void * Conversion<std::string>::FromWhite() {
  return new std::string("converting WHITE node to std::string ...");
}

template <>
void * Conversion<std::string>::FromBlack() {
  return new std::string("converting BLACK node to std::string ...");
}

Testing the code:
BaseNode * node = new BlackNode;
std::cout << node->Convert<std::string>() << std::endl;
node = new WhiteNode;
std::cout << node->Convert<std::string>() << std::endl;

returns the expected result:
converting BLACK node to std::string ...
converting WHITE node to std::string ...

Although this solution works, I am sure it can be done much easier. Any other, simpler solution I came up with failed, e.g. due to type erasure.
I would appreciate any help on that. Thanks!

A: Something similar to your solution but without void*.
class NodeVisitor
{
   virtual void VisitBlack(BlackNode* node);
   virtual void VisitWhite(BlackNode* node);
};

class BaseNode {
  std::vector<BaseNode*> children_;
  ...
  virtual void visit(NodeVisitor* visitor) = 0;
};

class WhiteNode : public BaseNode {
  virtual void visit(NodeVisitor* visitor) { visitor->visitWhite(this); }
};

class BlackNode : public BaseNode {
  virtual void visit(NodeVisitor* visitor) { visitor->visitBlack(this); }
};

Then
std::string convert(BaseNode* node)
{
    class ConvertVisitor
         : public NodeVisitor
    {
        ConvertVisitor(std::string* res)
            : m_res(res)
        { }

        virtual void VisitBlack(BlackNode* node)
        {
            *m_res = // convert black node to string;
        }

        virtual void VisitWhite(BlackNode* node)
        {
            *m_res = // convert white node to string;
        }

        std::string* m_res;
    };

    std::string res;
    ConvertVisitor visitor(&res);
    node->visit(&visitor);
    return res;
}


text:
Q: How to drag images from a canvas? check this fiddle.
We can drag and drop the "Drag me downX" lines in to the canvas div; the line of text will stay there while there will be a translucent line of text following the mouse. I want to have this same effect dragging the line of text out of the canvas. Yet, once the text is dropped in the canvas it cannot be moved. How can I go about achieving the above (it having the same effects as described above is very important)?
HTML

Drag me down1

Drag me down2

Drag me down3

  <canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>

JS
 $("li").draggable({
    helper: 'clone'
 });
 $("#myCanvas").droppable({
    accept: "li",
    drop: function(event, ui) {
       var context = $(this)[0].getContext("2d");
       context.font = "16px helvetica";
       context.fillText($(ui.draggable).clone().text(), ui.position.left - event.target.offsetLeft, ui.position.top - event.target.offsetTop);
    }
 });

CSS
 li{
    font-family:helvetica;
    list-style-type:none;
 }

A: Once you drop the element onto the <canvas> it loses all meaning as the text gets rasterized.  As such, there is no way to get the text out.  The best that you could do is append invisible copies of the dragged tag to the canvas and then whenever there is any drag event out of the canvas, pop an element and drag it where you want.  However, this will not get you the exact tag that you want necessarily.
If you are really looking for a challenge, you can take a look at this question which is about selecting text in a canvas after it's been rasterized. How to Make Canvas Text Selectable?

A: I think there might have been an issue because its basically an element being dragged and dropped on itself. I created a hidden canvas and superimposed the original canvas over the new one. When the drag event is fired the hidden canvas is placed on a higher z-index and gets the coordinate information to pass to the original canvas.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using EditorFor with templateFormat and a Validation I would like to rewrite this piece of code using the solution presented here: Html.TextBoxFor formatting or Html.EditorFor htmlAttributes?

    @Html.TextBoxFor(x => x.Name)
    @MyFunc()
    @Html.ValidationMessageFor(x => x.Name)

But, since the call to this template format has no parameters, how can I pass the lambda expression x => x.Name to @Html.ValidationMessageFor?
I have this parameter on the calling page and I need to send it to the EditorFor template page:
Calling page
@Html.EditorFor(m => m.Name)

Classical example EditorFor template page
@model System.DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : string.Empty, new { @class = "date-picker" })

Real example of EditorFor for this case???

    @Html.TextBoxFor(????????)
    @MyFunc()
    @Html.ValidationMessageFor(??????)

A: You can use @Html.ValidationMessage("") or @Html.ValidationMessageFor(m => m). For example

    @Html.Label("")
    @Html.TextBox("")
    @Html.ValidationMessage("")


text:
Q: My function to set margin is not working consistently I am trying to set a div just under my header, which has a position of "fixed". I am using a function to find the "clientHeight" of the header, add a few pixels and set the "marginTop to the div. Every few times I load the page or reload the page, the image isn't always in the desired position. I am relatively new to using js to make a responsive site. Only started coding a couple of months ago.
I tried setting the div ("#page") to absolute and using the "top" style attribute. That really didn't work.
I tried using relative too but that was much the same as my initial attempt.
Also I have only tested this in Chrome and Firefox (Latest versions).
Works fine in this fiddle, but not when I run it in the actual browser.
Below is the function in question.
function bodyMarginTop () {
    const header = document.querySelector("header");
    const page = document.getElementById("page");

    page.style.marginTop = (header.clientHeight + 8) + "px";
}

https://jsfiddle.net/Cpt_Crooked/yf8xj3s0/2/
Expected result:

*

*I want the white div to appear 8pxs under the header no matter the view port width, how many times the page is loaded, or which browser is being used.

Actual result:

*

*Chrome: Page loads correctly roughly 70% of the time. Sometimes it appears
too high on the page sometimes too low.

*Firefox: Same as Chrome only much less consistent as it only loads correctly roughly 10% of the time.

A: Make sure the function is called after all elements are loaded on the page by adding a  load event to the window object like so:
window.addEventListener("load", bodyMarginTop);

A: Load the DOM before running JS on the elements.
document.onreadystatechange = function () {
  if (document.readyState === 'interactive') {
    bodyMarginTop();
  }
}


text:
Q: Failed Binder Transaction No Noticeable Problems If I'm getting a Failed Binder Transaction error but it's not noticeably affecting the functionality, does it still matter?
Is it making my app less efficient?
06-08 00:54:47.110: E/JavaBinder(10110): !!! FAILED BINDER TRANSACTION !!!

This error happens at the start of an activity where I load facebook photos into image views using Picasso. Based on some questions on stack overflow, I'm guessing it has to do with that:
String facebookProfilePicUrl = "https://graph.facebook.com/"+item.get(TAG_FACEBOOKID)+"/picture?width=80&height=80";

Picasso.with(mContext)
.load(facebookProfilePicUrl)
.placeholder(R.drawable.ic_action_person)
.into(holder.fbphoto);

Thank you for your time.

A: The Binder transaction likely failed because it was too large. Try scaling down the image beforehand, and refer to this question for some more information.


text:
Q: How to put images on a map so that they disapear when another image passes over them We are working to create a pacman type of game and we cannot figure out for to get colored dots on the maze to represent the food the pacman eats. Here is our code so far:
style = {Background -> GrayLevel[0],
   BaseStyle -> {Directive[White, EdgeForm[], Opacity[1]]},
   VertexShapeFunction -> (Rectangle[#1 + .16, #1 - .16] &),
   EdgeShapeFunction -> (Rectangle[#1[[1]] + .16, #1[[2]] - .16] &)};
embedding = GraphEmbedding[GridGraph[{20, 30}]];
g = GridGraph[{20, 30}, EdgeWeight -> RandomReal[10, 1150]];
tree = FindSpanningTree[{g, 1}];
maze = Binarize[Image[Rasterize[Graph[tree, VertexCoordinates->embedding, style],
       RasterSize -> 1000], ImageSize -> 1000]];
m = 5;
DynamicModule[{diskPosition = {250, 450}, diskRadius = 15, pacman = {9, 4}},
 EventHandler[
  Show[maze, Graphics[Dynamic[{Yellow, Disk[diskPosition, diskRadius, pacman]}],
     PlotRange -> {{0, 200}, {0, 300}}]],
{"RightArrowKeyDown" :>
    If[PixelValue[maze, {diskPosition[[1]] + m, diskPosition[[2]]}] == 1,
                  pacman = {1, 6}; diskPosition[[1]] += m],
 "LeftArrowKeyDown" :>
    If[PixelValue[maze, {diskPosition[[1]] - m, diskPosition[[2]]}] == 1,
                  pacman = {9, 4}; diskPosition[[1]] += -m],
 "UpArrowKeyDown" :>
    If[PixelValue[maze, {diskPosition[[1]], diskPosition[[2]] + m}] == 1,
                  pacman = {2, 7}; diskPosition[[2]] += m],
 "DownArrowKeyDown" :>
    If[PixelValue[maze, {diskPosition[[1]], diskPosition[[2]] - m}] == 1,
                  pacman = {-2, -7}; diskPosition[[2]] += -m]}]]

This gives us a pacman that moves along the white part of the maze. Now we want to be able to put dots along the white that disappear when the pacman passes over them.
Code taken from another question:
program a wall in which an object can not pass


text:
Q: Appengine - Upgrading from standard DB to NDB - ReferenceProperties I have an AppEngine application that I am considering upgrading to use the NDB database.
In my application, I have millions of objects that have old-style db references. I would like to know what the best migration path would be to get these ReferenceProperty values converted to KeyProperty values, or any other solution that would allow me to upgrade to NDB.
(I am hoping for something that doesn't involve massive batch processing of all of the elements in the database and computing the KeyProperty based on the ReferenceProperty -- something elegant would be nice)
Examples of models that I would like to upgrade from db.Model to ndb.Model are the following:
class UserModel(db.Model):
    ....

class MailMessageModel(db.Model):
    m_text = db.TextProperty()
    m_from = db.ReferenceProperty(reference_class = UserModel)
    m_to = db.ReferenceProperty(reference_class = UserModel)

A: Good news, you don't have to make any changes to your persisted data, as ext.db and ndb read and write the exact same data.
Here's the quote from the NDB Cheat Sheet:

No Datastore Changes Needed!
In case you wondered, despite the different APIs, NDB and the old ext.db package write exactly the same data to the Datastore. That means you don't have to do any conversion to your datastore, and you can happily mix and match NDB and ext.db code, as long as the schema you use is equivalent. You can even convert between ext.db and NDB keys using ndb.Key.from_old_key() and key.to_old_key().

The cheat sheet is a great guide to convert your model definitions.  For example, changing your MailMessageModel should be as easy as:
before:
class MailMessage(db.Model):
    m_text = db.TextProperty()
    m_from = db.ReferenceProperty(reference_class=UserModel)
    m_to = db.ReferenceProperty(reference_class=UserModel)

after:
class MailMessage(ndb.Model):
    m_text = ndb.TextProperty()
    m_from = ndb.KeyProperty(kind=UserModel)
    m_to = ndb.KeyProperty(kind=UserModel)

I highly recommend using the cheat sheet to assist you with your migration.


text:
Q: How can I use SyncSort to convert data to unsigned packed format? I have a requirement to convert numeric data (stored as character on input) to either packed signed or packed unsigned formats.  I can convert to packed/signed using the "PD" format, but I'm having a difficult time getting unsigned packed data.
For instance, I need a ZD number like 14723 converted to:
042
173
Using PD, I get this (which is fine):
0173
042C
Any suggestions?  We do not have COBOL at this shop and are relying on SyncSort to handle these data conversions.  I'm not seeing a "PK" option in SyncSort, but I've missed things before!

A: So you don't want a packed-decimal, which always has a sign (even when F for unsigned) in the low-order half-byte. You want Binary Coded Decimal (BCD).
//STEP0100 EXEC PGM=SORT
//SYSOUT   DD SYSOUT=*
//SORTOUT  DD SYSOUT=*
//SYSIN    DD *
  OPTION COPY

  INREC IFTHEN=(WHEN=INIT,OVERLAY=(1,5,ZD,MUL,+10,TO=PD,LENGTH=4)),
        IFTHEN=(WHEN=INIT,BUILD=(1,3))
//SORTIN   DD *
14723

Will give you, in vertical hex:
042
173

To use an existing BCD, look at field-type PD0.


text:
Q: Trying to parse bbcode out of a string and I'm running into trouble when I have nested tags This
[b]this text is bold[/b]
[i]this text is [b]italic[/b][/i]

parse out to this (in html)
this text is bold[/b]
this text is [b]italic

this text is bold[/b]this text is [b]italic
using this function
function bbcode(input){
return input
.replace(/\[b\]([^]*)\[\/b\]/ig, '$1')
.replace(/\[i\]([^]*)\[\/i\]/ig, '$1');
}

I figure there has to be a problem with the regular expression finding each set of tags, but it appears that only the first bold tag and the last bold end tag are being parsed. Any idea how this can be fixed?

A: function bbcode(input){
    var b = /\[b\]([^[]*(?:\[(?!b\]|\/b\])[^[]*)*)\[\/b\]/ig;
    var i = /\[i\]([^[]*(?:\[(?!i\]|\/i\])[^[]*)*)\[\/i\]/ig;
    while (input.search(b) !== -1) {
        input = input.replace(b,'$1');
    }
    while (input.search(i) !== -1) {
        input = input.replace(i,'$1');
    }
    return input.replace(/\n/ig, '
');
}

BBCode:
[b]x[b]y[/b]z[/b]
[b]this text is bold[/b]
[i]this text is [b]italic[/b][/i]

Usage:
var string = '[b]x[b]y[/b]z[/b]\n[b]this text is bold[/b]\n[i]this text is [b]italic[/b][/i]';
console.log(bbcode(string));

Output:
xyz
this text is bold
this text is italic

See DEMO.


text:
Q: Performance: search for values and return the sub arrays' key Given an array like:
$nouns = array(
    "man" => array("men"),
    "octopus" => array("octopi", "octopuses"),
    "ox" => array("oxen")
);

Consisting of approximately 3000 singular - plural pairs, how would one get the singular (the key) the most efficiently, by calling, for example, array_search_loosely($nouns, "men")?
I then expect to receive an array with the value "man".
I have tried four different approaches:
Original (which uses the function array_is_assoc, which is rather self-explanatory and irrelevant to the situation)
function array_search_loosely($array, $values, $compare_keys = false) {
  $values = is_array($values) ? $values : array($values);
  foreach($array as $item_key => $item) {
    if (is_array($item)) {
      $return_key = true;
      foreach($values as $value_key => $value) {
        if (!in_array($value, $item)) {
          $return_key = false;
          break;
        }
        elseif($compare_keys === true and array_is_assoc($values)) {
          if (!in_array($value_key, array_keys($item, $value))) {
            $return_key = false;
            break;
          }
        }
      }
      if ($return_key === true) {
        $item_keys[] = $item_key;
      }
    }
    elseif(!is_array($values)) {
      if ($item === $values) {
        $item_keys[] = $item_key;
      }
    }
  }
  return (isset($item_keys))? $item_keys : false;
}

Second approach:
function array_search_loosely($array, $values, $compare_keys = false) {
    $keys = array_keys(array_filter($array, function($item) use ($values, $compare_keys) {
        return (!is_array($item) and $item === $values) or (is_array($item) and each_in_array($item, array_create($values), $compare_keys));
    }));
    return !empty($keys) ? $keys : false;
}

function each_in_array($array, $values, $compare_keys = false) {
    return $compare_keys === false ? count(array_uintersect($values, $array, function($item1, $item2) { return $item1 === $item2 ? 0 : ($item1 > $item2 ? 1 : -1); })) == count($values) : count(array_uintersect_assoc($values, $array, function($item1, $item2) { return $item1 === $item2 ? 0 : ($item1 > $item2 ? 1 : -1); })) == count($values);
}

I chose to use array_uintersect, to also allow arrays to be $items, because if I was to use array_intersect, notices would be generated for each array $item. This choice allows each_in_array() to check for array $values as well.
Also, the third optional parameter $compare_keys is not relevant for this situation, but is in other situations where I use the function.
The third and fourth approaches were mixtures of the preceding. At this point my original approach would still be the fastest, but when I run my function on a few hundred or thousand words, the operation will still cost several tens of seconds. Any suggestions on how to improve the performance of getting a plurals singular in this situation?

A: Your map in its current format is not good to do the lookup. You also need an inversion of it:
$invert = array(
  'men' => 'man',
  'octopi' => 'octopus',
  'octopuses' => 'octopus',
  'oxen' => 'ox',
);

A: $search = 'men';
$found  = '';

foreach($nouns AS $noun => $values){
   if(in_array($search, $values){
        echo 'Found what we\'re looking for.';
        $found = $nouns[$noun];
   }

}

print_r($found);

A: output:

source:
<!DOCTYPE html>

        <?php
            $nouns = array  (
                                "data" => array("data"),
                                "datum" => array("data"),
                                "man" => array("men"),
                                "octopus" => array("octopi", "octopuses"),
                                "ox" => array("oxen"),
                                "hippopotamus" => array("hippopotami", "hippopotamuses")
                            );

            function find_singular($nouns, $search)
            {
                foreach($nouns as $noun => $values)
                {
                    if(in_array($search, $values))
                    {
                        $found[] = $noun;
                    }
                }
                if(!empty($found))
                {
                    $n = count($found);
                    if($n > 1)
                    {
                        echo "$search has $n singular forms: ";
                        print_r(implode(' and ', $found).'
');
                    }
                    else
                    {
                        echo "$search is the plural of $found[0]
";
                    }
                }
                else
                {
                    echo "$search was not found.
";
                }
            }

            find_singular($nouns, "men");
            find_singular($nouns, "octopi");
            find_singular($nouns, "data");
            find_singular($nouns, "oxen");
            find_singular($nouns, "octopuses");
            find_singular($nouns, "hippopotami");
            find_singular($nouns, "kittens");
        ?>

hope this helps!
EDIT:
what is the purpose of this? I am guessing you are creating a dictionary application for a web or app interface. I don't think you're going to be able to avoid loops so long as you intend on implementing a search ability. are you storing the whole dictionary in a PHP array? I assume you are since XML and mysql queries would cost even more time. my only other suggestion would be to split the dictionary into as many arrays you can manage (perhaps a few dozen per alphabetic letter) else write a script to produce these from either the existing dictionary array or a flat file, and then implement AJAX in your search box, similar to Google's predictive search but instead of displaying possible results as the search string is typed, it would be narrowing down which array to search, silently in the background. I have a script somewhere which does this and can dig it up if this sounds viable. basically, instead of searching the whole dictionary (I have seen one with in excess of twelve million words!) per keyword, by the time the keyword is typed, sent and processed, there could be much fewer loop cycles. hardware also springs to mind - the hard disk, processor and memory speeds of the server will account for most of the equation. I have also heard that C++ is much more suited to dictionary searches and would not be too foreign an option for a PHP developer.


text:
Q: Reasons for keeping Off-Topic question I recently flagged a question as off-topic: https://stackoverflow.com/questions/18343044/how-to-delete-a-msmm-exe-virus-from-windows-xp and my flag was marked as "Helpful" yet the question still exists and hasn't been transferred to SuperUser and/or burninated.
So, I have several questions pertaining to flagging:

*If an event such as this happens, should I go back and reflag as "Needs Moderator Attention"?

*When is it appropriate to flag a question?  Is it appropriate to flag it even if there is/are one/several answers?  What if there is an accepted answer?  What if the question has one/several upvotes?

*Are there any valid reasons for this question to still exist?

*Is there a generally-accepted un-written-about "age" of questions that should be left as-is and not flagged as to not clog the queues (i.e. anything older than 1 year/6 months/7 days)?

A: *

*No.  You already told us about it.

*You don't have to evaluate the answers to flag a question.

*It should stay on the site long enough for the OP to see that it was closed (it becomes eligible for deletion by the community in two days).

*No.


text:
Q: C array of structs syntax error Here is the piece of code that I am getting error, SDL_Rect's definition is copied over from documentation:
typedef struct{
  Sint16 x, y;
  Uint16 w, h;
} SDL_Rect;

SDL_Rect clips[4];

clips[0].x = 0;
clips[0].y = 0;
clips[0].w = 100;
clips[0].h = 100;

Here is how I am compiling it:
gcc -march=native -static-libgcc -o sprite sprite.c functions.o -L/usr/lib -lSDL -lpthread -lm -ldl -lpthread -lSDL_image

Here is the error that I am getting: expected '=', ',', ';', 'asm' or '__attribute__' before '.' token for each line of clips[..] . I have tried putting paranthesis around clips[..] but It didn't work either. This is plain "C" by the way. Not C++.
Edit
I have copied over SDL_Rect here from SDL's documentation in order to show what it was. It is not actually in the source file I am using. Therefore, missing of the semicolon cannot be the issue. And this code is in the global scope.

A: This (-initialisation-) assignment is at global scope which is not possible.
It is possible to initialise the array:
SDL_Rect clips[4] = {
                        { 0, 0, 100, 100 }, /* Element 0 initial values */
                        { 1, 1, 200, 200 }  /* Element 1 initial values */
                                            /* Element 2 and 3 unspecified so
                                               zero initialised. */
                    };

If C99 compliant compiler you can explicitly state the variables being initialised:
SDL_Rect clips[4] = {
                        { .x = 0, .y = 0, .w = 100, .h = 100 }
                    };

A: Missing a ; after the SDL_Rect:
typedef struct{
  Sint16 x, y;
  Uint16 w, h;
} SDL_Rect;

A: You seem to be missing a ; after SDL_Rect in your struct definition.

A: It should be:
typedef struct{
Sint16 x, y;
Uint16 w, h;
} SDL_Rect;

Notice the semicolon at the end.

A: There miss the semicolon at the end of the structure:
typedef struct{
  Sint16 x, y;
  Uint16 w, h;
} SDL_Rect;


text:
Q: Passing pointer to an array into a function (C++) I'm trying to pass an array into my function calls for build_max_heap and max_heapify so I can modify the array after each call, but I receive an error saying "candidate function not viable: no known conversion from 'int [9]' to 'int *&'for 1st argument."
#include <iostream>
#include <string>
using namespace std;

void build_max_heap(int*& array, int size);
void max_heapify(int*& array, int size, int index);

void build_max_heap(int*& array, int size)
  {
      for(int i = size/2; i>=0; i--)
      {
          max_heapify(array, i);
      }
  }

void max_heapify(int*& array, int size, int index)
  {
      int leftChild = 2*index+1;
      int rightChild = 2*index+2;
      int largest;
      int heap_size = size;

      if( leftChild <= heap_size && array[leftChild] > array[index])
          largest = leftChild;
      else
          largest = index;

      if(rightChild <= heap_size && array[rightChild] > array[largest])
          largest = rightChild;

      if(largest != index) {
          int tempArray = array[index];
          array[index] = array[largest];
          array[largest] = tempArray;
          max_heapify(array, heap_size, largest);
      }

  }

int main()
{
      int array[]={5,3,17,10,84,19,6,22,9};
      int size = sizeof(array)/sizeof(array[0]);

      build_max_heap(array, size);

      return 0;
}

A:
int array[]={5,3,17,10,84,19,6,22,9};

While array can be decayed to a pointer int* to be passed as a function argument, it the pointer cannot be passed as a "non-const reference" int*&, because it is immutable (it is a constant address). You could have passed it as a const reference like this:
void max_heapify(int* const& array, int size, int index)
//                    ^^^^^^

However, this doesn't make much sense, you can simply pass the pointer by value (a copy of the address of the array), which results in the same: the variable at the caller wont be changed. The usual use case of const& parameters is to pass objects that are expensive to copy, such as std::string. This does not apply to pointers; making a copy of a pointer is as cheap as copying any basic variable.
You should change your functions to take the pointer by value:
void build_max_heap(int* array, int size)
void max_heapify(int* array, int size, int index)

also, correct the call to max_heapify inside build_max_heap, give it the correct number of arguments:
void build_max_heap(int* array, int size)
{
   for(int i = size/2; i>=0; i--)
   {
       max_heapify(array, size, i);  // <-- 3 arguments
   }
}


text:
Q: Recycle boundary condition I'm having the following issue that can not find a solution , by using this boundary condition
u[0, t] == 2 u[1, t]

that Mathematica does not understand, someone please help me!
s = NDSolve[
  {
   D[u[x, t], t] == -D[u[x, t], x] - u[x, t],
   u[x, 0] == 1,

   u[0, t] == 2 u[1, t]
   },

  {u[x, t]},

  {x, 0, 1}, {t, 0, 1},

  Method -> {"PDEDiscretization" -> {"MethodOfLines",
      "TemporalVariable" -> t}}]

I'm getting this error message :

NDSolve::bcedge: Boundary condition u[0,t]==2u[1,t] is not specified on
  a single edge of the boundary of the computational domain.

I have already presented a similar problem here, but the reasoning suggested is not a good solution for my case.
What strategies do you know to treat this problem ? I appreciate any help...

A: It's possible to make use of the method suggested in this post, but since this equation is simpler, we can solve it by making a change of variable
$$u(x,t)=\frac{v(x,t)}{x+1}$$
I'll use DChange for the task.
set = {D[u[x, t], t] == -D[u[x, t], x] - u[x, t], u[x, 0] == 1, u[0, t] == 2 u[1, t]};

newset = DChange[set, u[x, t] == 1/(1 + x) v[x, t]]

mol[n_Integer, o_:"Pseudospectral"] := {"MethodOfLines",
  "SpatialDiscretization" -> {"TensorProductGrid", "MaxPoints" -> n,
    "MinPoints" -> n, "DifferenceOrder" -> o}}
newsol = NDSolveValue[newset, v, {x, 0, 1}, {t, 0, tend}, Method -> mol[201]]

Plot[{newsol[x, t]/(1 + x) /. x -> 0, 2 newsol[x, t]/(1 + x) /. x -> 1} // Evaluate, {t,
  0, tend}, PlotStyle -> {Green, {Dashed, Red, Thick}}]

Plot3D[newsol[x, t]/(1 + x), {x, 0, 1}, {t, 0, tend}]

There's some noise at the discontinuity, but I think the result is still acceptable.


text:
Q: How to represent a date time for B.C. within python I am creating a application about the history. But I am getting stuck when I need to create a field with django DateTimeField to represent the date time for B.C.(aka Before Christ).
eg. Roman Empire is from 27 B.C. to 395 AD. How can I represent the from and to date with python datetime or django DateTimeField?
I need some further date calculation on these fields, so an integer is not quite well for this, any idea?

A: You can also use datautil. Datautil
Install it as :
pip install datautil

Then use it as:
from datautil.date import parse

fd = parse(u'Feb 1996')
print fd

<class 'datautil.date.FlexiDate'> 1996-02

fd.as_datetime()
datetime.datetime(1956, 1, 1, 0, 0)

bc = parse(u'1700BC')
print bc
<class 'datautil.date.FlexiDate'> -1700

Here is also a useful link.

A: Also, see the discussion on this same question from 2013 on SO:

BC dates in Python


text:
Q: How to get values from dropdown box in MVC knockout binding This is hpw i'm filing my dropdown box

$.ajax({
            url: "CheckinRelatedMember",
            type: "POST",
            data: { ClubId: localStorage.getItem("ClubId"), memacctno: localStorage.getItem("memacctno") },
            async: false,
            success: function (data) {
                var RelatedMembers;
                RelatedMembers = JSON.parse(data.CheckinRelatedMemberResult);
                self.RelMembers(RelatedMembers);

How to get Option value from knockout dropdown list. I had successfully binded an dropdown box. but my problem is while i retrieve value from   tag. option value unable to appear.

function FillCheckInRec() {
            submemacctno = document.getElementById("RelateMem")[0].value;

i need to pass selected option value to FillCheckInRec() method.

                        Select Member

                    <select id="RelateMem" class="input-medium" data-bind="options: RelMembers, optionsText:'Name',optionvalue:'AcctNo', value: 'AcctNo'"></select>

But while i pass select value into FillCheckinRec() method, value comes like this (""). how to get AcctNo From dropdown list. Please Help Me!

A: Try something like this
view:

    Select Member
    <select data-bind="options: RelMembers, optionsText:'Name',optionsValue:'AccNo', value:AcctNo"></select>

viewModel:
var ViewModel = function () {
    var self = this;
    self.RelMembers = ko.observableArray();
    self.AcctNo = ko.observable();

    $.ajax({
         url: '/echo/json/',
        type: "POST",
        data: {},
        success: function (data) {
            var RelatedMembers = [{
                'Name': 'One',
                    'AccNo': 1
            }, {
                'Name': 'Two',
                    'AccNo': 2
            }, {
                'Name': 'Three',
                    'AccNo': 3
            }]
            self.RelMembers(RelatedMembers);
        }
    });
};

ko.applyBindings(new ViewModel());

working sample here

A: Well I got fix this issue, Here is my code.

var submemacctno = $("#RelateMem").val();
 <select id="RelateMem" class="input-medium" data-bind="options: RelMembers, optionsText:'Name',optionsValue:'AcctNo', value:'AcctNo'"></select>

This is my HTML Code, Rest of everything are same.
 Thank You!


text:
Q: C# method returning formula   static void Main(string[] args)
        {
            double creditcardbalance;
            creditcardbalance = GetPositiveDouble("Enter In Credit Card Balance");

            double monthlypayementamount;
            monthlypayementamount = GetPositiveDouble("Enter In Monthly Payement Amount");

            double percentagerate;
            percentagerate = (int)GetPositiveDecimal("Enter In Percentage Rate");

            CreditCardMonths();
        }

        static void CreditCardMonths()
        {
            double dailyinterestrate;
            double payoff;
            double percentagerate = 0;
            double creditcardbalance = 0;
            double monthlypayementamount = 0;

            dailyinterestrate = (double)percentagerate / 365;
            payoff = (int)(-(1d / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount * (1 - Math.Pow(1 + dailyinterestrate, 30))) / Math.Log(1 + dailyinterestrate)) + 1;

            Console.WriteLine("It will take {0} months to pay off the loan", payoff);
            displaymenu();
            Console.ReadKey();
        }

Once declaring the method CreditCardMonths() in the main method my answer for my formula returns a negative integer when its supposed to return a positive.??
what am i missing?
my full code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DebtCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            double creditcardbalance;
            creditcardbalance = GetPositiveDouble("Enter In Credit Card Balance");
            double monthlypayementamount;
            monthlypayementamount = GetPositiveDouble("Enter In Monthly Payement Amount");

            double percentagerate;
            percentagerate = (int)GetPositiveDecimal("Enter In Percentage Rate");

            CreditCardMonths();
        }

This is piece of code works :
double creditcardbalance;
            Console.WriteLine("Enter in credit card balance:");
            creditcardbalance = double.Parse(Console.ReadLine());

            double monthlypayementamount;
            Console.WriteLine("Enter in the monthly payement amount:");
            monthlypayementamount = double.Parse(Console.ReadLine());

            double percentagerate;
            Console.WriteLine("Enter in annual percentage rate:");
            percentagerate = double.Parse(Console.ReadLine());
            // outputs
            double payoff;
            double dailyinterestrate;

            // Daily interest formula calculated by apr divided by 365
            dailyinterestrate = percentagerate / 365;
            //Introducing formula for output
            //Payoff needed to display whole numbers, although in ints output 1/30 = 0 so adding 1d (double) allows precise calculation.+1 allows it to round up to the nearest dollar.
            payoff = (int)(-(1d / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount * (1 - Math.Pow(1 + dailyinterestrate, 30))) / Math.Log(1 + dailyinterestrate)) + 1;
            //Introduce output for display

            {
                Console.WriteLine("It will take {0} months to pay off the loan", payoff);
                Console.WriteLine("Goodbye");
                // keep console open
                Console.ReadKey();

But it seems by created a method named CreditCardMonths is returns a negative integer?
Also my method for Y/N for looping is not working.
        static void CreditCardMonths()
        {
            double dailyinterestrate;
            double payoff;
            double percentagerate = 0;
            double creditcardbalance = 0;
            double monthlypayementamount = 0;

            dailyinterestrate = (double)percentagerate / 365;
            payoff = (int)(-(1d / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount * (1 - Math.Pow(1 + dailyinterestrate, 30))) / Math.Log(1 + dailyinterestrate)) + 1;

            Console.WriteLine("It will take {0} months to pay off the loan", payoff);
            displaymenu();
            Console.ReadKey();
        }

        static decimal GetPositiveDecimal(string message)
        {
            decimal value = 0;
            Console.WriteLine(message);
            value = decimal.Parse(Console.ReadLine());
            while (value <= 0)
            {
                Console.WriteLine("invalid input. Please enter a non negative Decimal");
                Console.WriteLine(message);
                value = decimal.Parse(Console.ReadLine());
            }
            return value;
        }
        static double GetPositiveDouble(string message)
        {
            double value = 0;
            Console.WriteLine(message);
            value = double.Parse(Console.ReadLine());
            while (value <= 0)
            {
                Console.WriteLine("Invalid Input . Enter In A Non Negative Number");
                Console.WriteLine(message);
                value = double.Parse(Console.ReadLine());
            }
            return value;
        }
        static void menuItem()
        {
            char menuItem;
            {
                menuItem = GetUpperCaseYN();
                ProcessMenuItem(menuItem);
            }
            Console.WriteLine("Thank you, goodbye.");
            Console.ReadLine();
        }
        static char GetUpperCaseYN()
        {
            char menuItem;
            menuItem = char.Parse(Console.ReadLine());
            menuItem = char.ToUpper(menuItem);
            while (menuItem != 'Y' && menuItem != 'N')
            {
                Console.WriteLine("Invalid Menu Item");
                menuItem = char.Parse(Console.ReadLine());
                menuItem = char.ToUpper(menuItem);
            }

            return menuItem;
        }
        static void displaymenu()
        {
            Console.WriteLine("Calculate Another? (Y/N)");
        }

        static void ProcessMenuItem(char menuItem)
        {
            switch (menuItem)
            {

                case 'Y':
                   ;
                    break;

                case 'N':
                    Console.ReadKey();
                    Console.WriteLine("Goodbye!");
                    Console.ReadKey();
                    break;
            }
            Console.ReadKey();
        }
    }
}

A: You are missing the fact that variables in one method are different variables then variables in the other methods even if they have the same names.
So for instance you have variable  percentagerate in method Main, and variable   double percentagerate in method CreditCardMonths. They are different pieces of memory - different variables.
You need to  do one of these:
Declare the variables outside of the method - on the class level.
Your methods are statis so you need to include keyword static.
static double creditcardbalance;
static double monthlypayementamount;
static double percentagerate;

static void Main(string[] args)
    {
        creditcardbalance = GetPositiveDouble("Enter In Credit Card Balance");

        monthlypayementamount = GetPositiveDouble("Enter In Monthly Payement Amount");

        percentagerate = (int)GetPositiveDecimal("Enter In Percentage Rate");

        CreditCardMonths();
    }

and don't declare them in the second method either becuase it will (so called) hide the scope.
Note: when you learn more about programming, consider passing the data that your sub-methods need to them using method parameters.
https://msdn.microsoft.com/en-us/library/0f66670z.aspx


text:
Q: PHP-Driver DataStax Cassandra DB - How to use? I've done the installation process as following:
System

PHP 7.0.5-1~dotdeb+8.1 (cli) ( NTS )
Debian 8
Nginx 1.8.1
Laravel 5.2

Java Installation
mkdir -p /usr/lib/jvm
wget URL to Oraclesite
mv mv jdk-8u77-linux-x64.tar.gz\?... jdk-8u77-linux-x64.tar.gz
tar xzf jdk-8u77-linux-x64.tar.gz
rm jdk-8u77-linux-x64.tar.gz
update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_version/bin/java" 1
update-alternatives --set java /usr/lib/jvm/jdk1.8.0_version/bin/java

Install needed packages
apt install cmake automake libtool git php7.0-dev libgmp-dev libssl-dev

Libuv Installation
cd /tmp
wget http://dist.libuv.org/dist/v1.7.5/libuv-v1.7.5.tar.gz
tar xzf libuv-v1.7.5.tar.gz
rm libuv-v1.9.0.tar.gz
cd libuv-v1.7.5
sh autogen.sh
./configure
make
make install
ldconfig

Installation Cassandra Datatrax
echo "deb http://debian.datastax.com/community stable main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list
curl -L http://debian.datastax.com/debian/repo_key | sudo apt-key add -
apt install cassandra dsc30

Check services
service cassandra status

cassandra.service - LSB: distributed storage system for structured
  data    Loaded: loaded (/etc/init.d/cassandra)    Active: active
  (running) since Mon 2016-04-11 01:11:04 CEST; 19min ago   Process: 506
  ExecStart=/etc/init.d/cassandra start (code=exited, status=0/SUCCESS)
  CGroup: /system.slice/cassandra.service

nodetool status

Datacenter: datacenter1
  ======================= Status=Up/Down |/ State=Normal/Leaving/Joining/Moving
  --  Address    Load       Tokens       Owns (effective)  Host ID                               Rack UN  127.0.0.1  139.06 KB  256          100.0%
  1ab0e99a-41a5-4007-b9ca-de58dc88e318  rack1

cqlsh

Connected to Test Cluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra
  3.0.4 | CQL spec 3.4.0 | Native protocol v4]
  Use HELP for help.

Installation php-driver
(PECL Installation isn't working. I think it's because of only php7 setup)
git clone https://github.com/datastax/php-driver.git
cd php-driver
git submodule update --init
cd ext
./install.sh
make test -> all tests passed

Add Driver to PHP Extensions
echo -e "; DataStax PHP Driver\nextension=cassandra.so" >> /etc/php/7.0/cli/php.ini

// UPDATE - added extension to fpm/php.ini file.
echo -e "; DataStax PHP Driver\nextension=cassandra.so" >> /etc/php/7.0/fpm/php.ini

Restart nginx and php7.0-fpm
service nginx restart
service php7.0-fpm restart

Question:
If I wanna use the following code it says me class Cassandra not found.
Webpage: https://github.com/datastax/php-driver#datastax-php-driver-for-apache-cassandra
$cluster = Cassandra::cluster()->build();

Thank you for helping.

A: Since you are trying to execute your PHP script using nginx+fpm you will need to update the appropriate php.ini file (e.g. /etc/php7/fpm/php.ini).
Add the driver module to your nginx+fpm installation
echo -e "; DataStax PHP Driver\nextension=cassandra.so" >> /etc/php/7.0/fpm/php.ini

To ensure the the driver is being properly loaded via CLI you can execute the following:
php -m | grep cassandra

or
php -i | grep -A 10 "^cassandra$"

php -m will print out all the extension/modules that PHP was able to load whereas php -i will display more verbose information about your PHP installation configuration.

A: UPDATE 1
When I execute the following 2 commands I get the following two results, which looks quite successful.
php -m | grep cassandra

cassandra

php -i | grep -A 10 "^cassandra$"

cassandra
Cassandra support => enabled C/C++ driver version => 2.2.2 Persistent
Clusters => 0 Persistent Sessions => 0
Directive => Local Value => Master Value cassandra.log =>
cassandra.log => cassandra.log cassandra.log_level => ERROR => ERROR

But still the error no class Cassandra.
UPDATE 2
Everything working now.
php > $cluster = Cassandra::cluster()->build();
php > var_dump($cluster);
object(Cassandra\DefaultCluster)#2 (0) { }
php >


text:
Q: CockroachDB cluster maximal size? Does a CockroachDB cluster have a maximum limit of number of nodes?
Can it include millions or billions of nodes?

A: Richard's answer is actually misleading.
According to the reference in his answer (https://www.cockroachlabs.com/docs/stable/performance.html), the number 81 is just how many nodes cockroachlab uses to perform the tpc-c benchmark. And there's also a quote in that page saying "CockroachDB has no theoretical scaling limit and, in practice, can achieve near-linear performance at 256 nodes".

A: The recommended maximum number of nodes is 81.
See: https://www.cockroachlabs.com/docs/stable/performance.html


text:
Q: How do you indent/outdent items in a custom list with Task Content Type? I had to create a custom list (with content type of Task) instead of creating a task list because of another issue where task lists will not allow filtering in the calendar view. Now I'm running into an issue where the Indent/Outdent (i.e. Hierarchy options) are not available for my custom list. Is there any way to add the indent/outdent options to a custom list?
It looks like I also can't add items in the custom list to the timeline. Is there any way to add these functions to a custom list?

A: I've noticed that some other users have asked the similar questions... But the Hierarchy as well as the Timeline options are available for the Tasks list. They are the Tasks list features, not for other lists. So, using a custom list to achieve the goal as a Tasks list is not feasible. Hope the information can help you sort out the query. Good Luck, buddy~


text:
Q: Sql Server query with python I need to know how to query a table in sql server. Everywhere i look it says to use pyodbc but they didn't make one for 3.4 .

A: There isn't an official pyodbc for Python 3.4. However, as bernie mentions in his comment, you can try the 3.3 version. Additionally, the University of California, Irvine provides an unofficial build for pyodbc for Python 3.4. There is also the pypyodbc package, as an option.
In any case, once you decide on which to utilize, you can use it by doing something like this. Realize this a very simple query.
import pyodbc
# Create connection
con = pyodbc.connect(driver="{SQL Server}",server=SERVERNAME,database=DATA_BASE_INFO,uid=username,pwd=password)
cur = con.cursor()
db_cmd = "SELECT * FROM table_name"
res = cur.execute(db_cmd)
# Do something with your result set, for example print out all the results:
for r in res:
    print r

In the line that beings con =, there are several values for you to fill in.

*

*server needs to be server host information (either IP or DNS name), and possibly a port (default is 1435) "dns.to.host.com,1435"

*uid is the username you are logging in with

*pwd is the password of the user you are logging in with


text:
Q: How can I set styling twice in the same functions with react? I wish to use css-transition to animate an object:

      setStyle () {
        const style = {}
        if (this.state.fullScreen) {
          style.background = 'white'
          style.position = 'absolute'
          style.transition = 'top 2s'
          style.top = '20px'
        }

        //here I wish to set style.top = 0
        return style
      }

I wish to first set the style.top = 20px (this is where the item is already  and then re render the dom and then set the style.top = 0 to trigger the animation. How can this be done?
state declaration:

 constructor (props) {
    super(props)
    this.state = {
      active: -1,
      fullScreen: false,
      fullScreenStyle: {
        background: 'transparent',
        position: 'static',
        top: 'auto'
      }
    }
    this.flky = {}
  }

  setStyle () {
    if (this.state.fullScreen) {
      this.setState({
        fullScreenStyle.background: 'white,
        fullScreenStyle.position: 'absolute'
        fullScreenStyle.top: '20px'
      })
    }

A: To rerender the Dom you have two options:
1) by setting the state use setState.
2) by using lifecycle function that is forceUpdate()
But you have to take care before using forceupdate function because it stops other operations and invoke render function, using setState is recommended.
In this you can do one thing:
constructor(props)
{
  super(props)
  this.state={
    style:{
        background = 'white',
        position = 'absolute',
        transition = 'top 2s',
        top:'20px'
     }
   }
}

  setStyle () {
    //you can set state as follows
    if (this.state.fullScreen) {
     this.setState({
      style:{background: 'white'},
      style:{position:'absolute'},
      style:{transition: 'top 2s'},
      style:{top: '20px'}
      )}
    }

    //here I wish to set style.top = 0
    else
    {
       this.setState({ style:{background: 'white'},
      style:{position:'absolute'},
      style:{transition: 'top 2s'},
      style:{top: '0px'}
      )}
     }

  }


text:
Q: Can't interact with a window (HWND) cpp I want to be able to minimize/maximize a window of a process that I create with ShellExecuteEx().
First, I find the process ID and its HWND (I made sure it was the good HWND with Spy++).
Next, I try to minimize with ShowWindow(hwnd) or with ShowWindow(GetForegroundWindow(), SW_MINIMIZE).
But it doesn't work. I made sure the process was elevated (administrator rights).  This seems to work with any other windows, such as the one for Notepad, RocketLeague, or whatever.  But this one window doesn't react.  When I call SetForegroundWindow(hwnd) I can see it flashing in the Taskbar, so I'm sure it is the right HWND for my application to use.
Any idea of what the issue might be?

A: Use SPY++ to find className and windowName, then you can:
HWND hWnd = ::FindWindow(className, windowName);
::ShowWindow(hWnd, SW_MINIMIZE);

A: SendMessage(GetForegroundWindow(), WM_SYSCOMMAND, SC_MINIMIZE, 0);


text:
Q: loading webpages in iframe don't start spinning circle I have a web page with multiple iframes. In Google Chrome, when I click in one iframe a link to load in another it doesn't start the blue spinner circle on the tab of the browser. That was working until this week and is anoying that if it takes 10 secs to load the user doesn't see it, and think that needs to click on the link again.
Is there a chrome new policy on this or a fix I can use to start and stop the spinner?
I cleaned the browser history with no effect, and the webpage code hasn't change.

A: This is a change that the Chromium dev team has done on purpose, and are not planning on changing it back:
Here is the discussion where they have essentially said that this is not a bug, and will not be fixed:
https://bugs.chromium.org/p/chromium/issues/detail?id=769803#c8
They've essentially said that it's a feature request. Perhaps if enough people request it, they will change it back?


text:
Q: Ajax submit is not happening properly Guys this is my first question. I have a table which displays the students name and the input fields to enter their exam marks. The table header shows the subjects(its in a while loop) and has an input field to enter max marks for all of them. This max marks is updated thru Ajax. Its not happening properly. If we press submit first time, nothing will happen. If we press submit second time, it submits. If we press third time, it updates twice, if we press fourth time, it updates thrice (the success message shows thrice)
Code -
<script>
$(document).ready(function(){
$("#maxmarks<?php echo "$m";?>").validate({

    rules:{

        maxmarks:{

        number: true,

        }

    },
    messages:{

        maxmarks:{

            number: "Please enter a valid marks",

        }

    },
    submitHandler: function(form){

        $("#maxmarks<?php echo "$m";?>").submit(function(){

            $.ajax({

                url : 'components/teacher/performance/maxupdate.php',
                type : 'POST',
                data : $("#maxmarks<?php echo "$m";?>").serialize(),
                success : function(res){

                    $('#resultreturn').prepend(res);

                }
            });
            return false;
        });

    }
 });
 });
 </script>

The form has the same id as the script above. Can someone tell me what is the problem?

A: You have the submit handler twice. Once as submitHandler:, then you do it again as .submit()
One or the other - not both.
The first time the form is submitted it creates the submit handler (as you told it to with .submit()) but doesn't actually run it.
The second time it runs it (since you created it earlier), and then creates it again. Each time you run it you get more of them.


text:
Q: why there is no graph whose largest eigenvalue, $\lambda_1$, lies in the intervals $(0,1)$ or $(1,\sqrt{2})$? why there is no graph whose largest eigenvalue, $\lambda_1$, lies in the intervals $(0,1)$ or $(1,\sqrt{2})$? I think it's becaues of if  a graph doesn't have any edge then  $\lambda_1=0$, if it has one edge, then $\lambda_1=1$ and finally if it has two edges, then
$\lambda_1=\sqrt{2}$. For the graphs with more edges, $\lambda_1\geq \sqrt{2}$. Is it correct?
Thank you for the help.

A: You should be more precise: a graph with two edges can still have largest eigenvalue $1$ if those two edges don't share any endpoints. What you mean is: a connected graph with two edges has largest eigenvalue $\sqrt 2$.
Except for that nitpick, you are correct, because the largest eigenvalue of a graph is at least the largest eigenvalue of any subgraph. Any graph either

*

*is empty, and all its eigenvalues are $0$, or

*has no components with more than one edge, and all its eigenvalues are $1$, $0$, or $-1$, or

*has a component with at least two edges, in which case that component contributes an eigenvalue of at least $\sqrt 2$, by the result above.

We could in theory continue this reasoning if we wanted to. No graph has a largest eigenvalue in the interval $(\sqrt 2, \frac{1+\sqrt5}{2})$, because $\sqrt2$ is the only possible eigenvalue of a connected graph with $2$ edges, and $\frac{1+\sqrt5}{2}$ is the smallest eigenvalue of a connected graph with $3$ edges.


text:
Q: Swap call to 0x contract failing I am trying to build an arbitrage bot (learning) using AAVE flashloans, 0x and 1 Inch exchange swaps. While my flashloan call is successful but swap call to 0x exchange fails and revert 'SWAP_CALL_FAILED'. To examine I have tested both of my swap functions individually (by making them external payable and calling) and they work perfectly fine. But when I use them in my contract 0x swap fail.
Question - Could it be because the _zrxSwap (0x swap function) is an internal function? I can't seem to understand the reason.
My contract code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
import "./aave/FlashLoanReceiverBase.sol";
import "./aave/ILendingPoolAddressesProvider.sol";
import "./aave/ILendingPool.sol";
import "hardhat/console.sol";
import "./interfaces/IOneInchExchange.sol";

// A partial WETH interface.
interface IWETH is IERC20 {
    function deposit() external payable;
    function withdraw(uint256) external;
}

// Flashloan contract
contract Flashloan is FlashLoanReceiverBase {
    uint public walletBalance = 0;
    address payable beneficiary;
    // The WETH contract.
    IWETH public immutable WETH;

// One Inch Exchange Config
address ONE_INCH_EXCHANGE = 0x111111125434b319222CdBf8C261674aDB56F3ae;

// ZRX Config -- Mainet
address ZRX_EXCHANGE_PROXY_ADDRESS = 0xDef1C0ded9bec7F1a1670819833240f027b25EfF;

// Struct to pass calldata
struct MyCustomData {
    address loanToken;
    uint256 loanAmount;
    uint256 repayAmount;
    address arbToken;
    bytes zrxData;
    bytes oneData;
}

constructor(
    address _addressProvider,
    address payable _beneficiary,
    IWETH weth
    ) FlashLoanReceiverBase(_addressProvider) public {
        beneficiary = _beneficiary;
        WETH = weth;
    }

/**
    This function is called after your contract has received the flash loaned amount
 */
function executeOperation(
    address _reserve,
    uint256 _amount,
    uint256 _fee,
    bytes calldata _params
)
    external
    override
{
    MyCustomData memory mcd = abi.decode(_params, (MyCustomData));
    require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?");
    walletBalance = _amount;

    // Arbitrage
    _arb(mcd.loanToken, mcd.arbToken, mcd.loanAmount, mcd.zrxData, mcd.oneData);

    uint totalDebt = _amount.add(_fee);

    transferFundsBackToPoolInternal(_reserve, totalDebt);
}

function _arb(address _fromToken, address _toToken, uint256 _fromAmount, bytes memory _0xData, bytes memory _calldata) internal {
    // Track original balance
    uint256 _startBalance = IERC20(_fromToken).balanceOf(address(this));

    // Perform the arb trade
    _trade(_fromToken, _toToken, _fromAmount, _0xData, _calldata);

    // Track result balance
    uint256 _endBalance = IERC20(_fromToken).balanceOf(address(this));

    // Require that arbitrage is profitable
    require(_endBalance > _startBalance, "End balance must exceed start balance.");
}

function _trade(address _fromToken, address _toToken, uint256 _fromAmount, bytes memory _0xData, bytes memory _calldata) internal {
    // Track the balance of the token RECEIVED from the trade
    uint256 _beforeBalance = IERC20(_toToken).balanceOf(address(this));

    // Swap on 0x: give _fromToken, receive _toToken
    _zrxSwap(_fromToken, _fromAmount, _0xData);

    // Calculate the how much of the token we received
    uint256 _afterBalance = IERC20(_toToken).balanceOf(address(this));

    // Read _toToken balance after swap
    uint256 _toAmount = _afterBalance - _beforeBalance;

    // Swap on 1Split: give _toToken, receive _fromToken
    _oneSplitSwap(_toToken, _fromToken, _toAmount, _calldata);
}

// Swap back tokens on 0x exchange
function _zrxSwap(address _from, uint256 _amount, bytes memory _calldata) internal {
    // Approve tokens

    IERC20 _fromIERC20 = IERC20(_from);

    // Approve zrx contract
    require(_fromIERC20.approve(ZRX_EXCHANGE_PROXY_ADDRESS, uint256(-1)));

    // Swap tokens
    (bool success, ) = ZRX_EXCHANGE_PROXY_ADDRESS.call{value:  _amount}(_calldata);
    require(success, 'SWAP_CALL_FAILED');

    // Reset approval
    _fromIERC20.approve(ZRX_EXCHANGE_PROXY_ADDRESS, 0);
}

// Swap back tokens on 1 Inch exchange
function _oneSplitSwap(address _from, address _to, uint256 _amount, bytes memory _calldata) internal {
    // Setup contracts
    IERC20 _fromIERC20 = IERC20(_from);
    IERC20 _toIERC20 = IERC20(_to);

    IOneInchExchange _oneExchangeContract = IOneInchExchange(ONE_INCH_EXCHANGE);
    // Approve tokens
    _fromIERC20.approve(address(_oneExchangeContract), uint256(-1));

    // Unpack the params
    (IOneInchCaller caller, IOneInchExchange.SwapDescription memory desc, IOneInchCaller.CallDescription[] memory calls) = abi
        .decode(_calldata, (IOneInchCaller, IOneInchExchange.SwapDescription, IOneInchCaller.CallDescription[]));

    // Swap tokens: give _from, get _to
    uint256 returnAmount = _oneExchangeContract.swap{ value: msg.value }(caller, desc, calls);
    require(returnAmount > 0, '1INCH_SWAP_CALL_FAILED');

    // Reset approval
    _fromIERC20.approve(address(_oneExchangeContract), 0);
}

// Transfer ETH into this contract and wrap it into WETH.
function depositWETH()
    external
    payable
{
    WETH.deposit{value: msg.value}();
}
/**
    Flash loan 1000000000000000000 wei (1 ether) worth of `_asset`
 */

function flashloan(
    address _loanToken,
    uint256 _loanAmount,
    address _arbToken,
    bytes memory _zrxData,
    bytes memory _calldata,
    uint256 _gas
) public onlyOwner {
    uint256 _repayAmount = _loanAmount.add(_gas);
    bytes memory _params = abi.encode(MyCustomData({
            loanToken: _loanToken,
            loanAmount: _loanAmount,
            repayAmount: _repayAmount,
            arbToken: _arbToken,
            zrxData: _zrxData,
            oneData: _calldata
            }));
    uint amount = _loanAmount * 1e18;

    ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());

    lendingPool.flashLoan(address(this), _loanToken, amount, _params);
  }
}

My Tx call:
const tx = {
    from: owner,
    to: flashloanAddress,
    gas: 30000000,
    data: flashloanContract.methods.flashloan(
        fromAssetAddress,
        1,
        toAssetAddress,
        zrx_data,
        one_exchange_data,
        total_gas
    ).encodeABI(),
  }


text:
Q: Batch malfunction This is a script my friend wrote for fun and there are two things that I can't figure out why it's not working. One question number 12 is always right no mater what the input. Also if you hit enter all the way through the questionnaire it automatically selects number 1 and I'm not sure why.
@echo off
    color 0c
title food quiz!

:begin
echo.
echo       Hello! and welcome to the ...FOOD QUIZ...
echo.
echo  To enter your answer, choose your answer, press space, then type the number
echo your answer was listed as and press enter.
pause.
cls

set score=0
:Q1
echo.
echo question 1
echo.
echo    In which country did creme brulee originate?
echo.
echo 1. Italy
echo 2. Japan
echo 3. France
echo.
pause

set /p x=number
if %x%==1 goto A

if %x%==2 goto B

if %x%==3 goto C

:A
cls
echo.
echo Sorry!... creme brulee is a french dish.
pause
goto Q2

:B
cls
echo.
echo Sorry!... creme brulee is a french dish.
pause
goto Q2

:C
cls
echo.
echo Correct!
pause
set /a score=score+1
goto Q2

:Q2
cls
echo.
echo question 2
echo.
echo    A waz wan is a celebratory ___ course meal from the Kashmir valley of india.
echo.
echo 1. 10
echo 2. 25
echo 3. 36
echo.
pause
cls

set /p x=number
if %x%==1 goto A1

if %x%==2 goto B1

if %x%==3 goto C1

:A1
cls
echo.
echo Sorry!... a waz wan is a 36 course meal.  only for special occasions.
pause
cls
goto Q3

:B1
cls
echo.
echo Sorry!... a waz wan is a 36 course meal.  only for special occasions.
pause
cls
goto Q3

:C1
cls
echo.
echo Yes!  waz wans are only for special occasion.
pause
cls
set /a score=score+1
goto Q3

:Q3
cls
echo.
echo question 3
echo.
echo    What is "chiqueti"? (pronounced chiketi)
echo.
echo 1. small gourmet snacks favored by the gondoleirs of venice.
echo 2. sausages from finland.
echo 3. small bite sized rolls served as streetfood in the phillipines.
echo.
pause
cls

set /p x=number
if %x%==1 goto A2

if %x%==2 goto B2

if %x%==3 goto C2

:A2
cls
echo.
echo Correct!
pause
cls
set /a score=score+1
goto Q4

:B2
cls
echo.
echo Nope! Chiqueti are small gourmet snacks favored by the gondoleirs of venice.
pause
cls
goto Q4

:C2
cls
echo.
echo Nope! Chiqueti are small gourmet snacks favored by the gondoleirs of venice.
pause
cls
goto Q4

:Q4
cls
echo.
echo question 4
echo.
echo    Haggis is the national dish of which Country in the united Kingdom?
echo.
echo 1. England
echo 2. Scotland
echo 3. Wales
pause
cls

set /p x=number
if %x%==1 goto A3

if %x%==2 goto B3

if %x%==3 goto C3

:A3
cls
echo.
echo Incorrect! haggis is the national dish of scotland.  haggis is the ground up
echo pluck of a sheep, mixed with oats and   echo onions, then stuffed in a sheep stomach and steamed.
echo.
pause
cls
goto Q5

:B3
echo.
echo Yep! haggis is the ground up pluck of a sheep, mixed with oats and onions, then stuffed in a sheep stomach and steamed.
echo.
pause
cls
set /a score=score+1
goto Q5

:C3
cls
echo.
echo Incorrect! haggis is the national dish of scotland.  haggis is the ground up
echo pluck of a sheep, mixed with oats and onions, then stuffed in a sheep stomach and steamed.
echo.
pause
cls
goto Q5

:Q5
cls
echo.
echo question 5
echo.
echo    What is Borscht?
echo.
echo 1. an entree.
echo 2. a dessert.
echo 3. a soup like side dish.
echo.
pause
cls

set /p x=number
if %x%==1 goto A4

if %x%==2 goto B4

if %x%==3 goto c4

:A4
cls
echo.
echo Sorry! Borscht is a russian soup like side dish.
echo.
pause
cls
goto Q6

:B4
cls
echo.
echo Sorry! Borscht is a russian soup like side dish.
echo.
pause
cls
goto Q6

:C4
cls
echo.
echo Yes! Borscht is usually a liquidy vegetable puree, sometimes containing milk.
echo.
pause
cls
set /a score=score+1
goto Q6

:Q6
echo.
echo question 6
echo.
echo    Bleenies (aka bleens) are a popular streetfood of which country?
echo.
echo 1. Norway
echo 2. Russia
echo 3. romania
echo.
pause
cls

set /p x=number
if %x%==1 goto A5
if %x%==2 goto B5
if %x%==3 goto C5

:A5
echo.
echo Incorrect! Bleenies are a popular streetfood of Russia.
echo.
pause
cls
goto Q7

:B5
echo.
echo Yes!
echo.
pause
cls
set /a score=score+1
goto Q7

:C5
echo.
echo Incorrect! Bleenies are a popular streetfood of Russia.
echo.
pause
cls
goto Q7

:Q7
echo.
echo question 7
echo.
echo    Kahlia is a Moraccan dish...What is "kahlia"?
echo.
echo 1. Meat, preserved in its own fat.
echo 2. A type of lamb stew with dates.
echo 3. A tea containing cinnamon, reportedly an aphrodisiac.
echo.
pause
cls

set /p x=number
if %x%==1 goto A6
if %x%==2 goto B6
if %x%==3 goto C6

:A6
echo.
echo Yes!  Kahlia can be cooked with eggs and served as a breakfast food.
echo.
pause
set /a score=score+1
cls
goto Q8

:B6
echo.
echo Sorry! Kahlia is meat preserved in fat.
echo.
pause
cls
goto Q8

:C6
echo.
echo Sorry! Kahlia is meat preserved in fat.
echo.
pause
cls
goto Q8

:Q8
echo.
echo question 8
echo.
echo    Muktuk is eaten by the native people of Alaska.  What is muktuk?
echo.
echo 1. Raw seal skin with a layer of blubber.
echo 2. Raw dolphin skin with a layer of blubber.
echo 3. Raw whale skin with a layer of blubber.
echo.
pause
cls

set /p x=number
if %x%==1 goto A7
if %x%==2 goto B7
if %x%==3 goto c7

:A7
echo.
echo Sorry! Muktuk is Raw whale skin with a layer of blubber.
echo.
pause
cls
goto Q9

:B7
echo.
echo Sorry! Muktuk is Raw whale skin with a layer of blubber.
echo.
pause
cls
goto Q9

:C7
echo.
echo Yep!
echo.
pause
set /a score=score+1
cls
goto Q9

:Q9
echo.
echo question 9
echo.
echo Muktuk can be used to make which native Alaskan delicacy?
echo.
echo 1. Lunuk.
echo 2. Tunuk.
echo 3. Dunuk.
echo.
pause
cls

set /p x=number
if %x%==1 goto A8
if %x%==2 goto B8
if %x%==3 goto C8

:A8
echo.
echo Nope! Muktuk is used to make Dunuk. Dunuk is a fermented whale oil used as a sauce for other whale products.
echo.
pause
cls
goto Q10

:B8
echo.
echo Nope! Muktuk is used to make Dunuk. Dunuk is a fermented whale oil used as a sauce for other whale products.
echo.
pause
cls
goto Q10

:C8
echo.
echo Yes! Dunuk is a fermented whale oil used as a dipping sauce for other whale products.
pause
set /a score=score+1
cls
goto Q10

:Q10
echo.
echo question 10
echo.
echo    Kopi Luwak is which type of beverage?
echo.
echo 1. A Balinese broth made from rhino beetle larvae.
echo 2. A coffee made from digested coffe beans excreted from the wild civet cat.
echo 3. A cold smoothie like drink also made from muktuk.
echo.
pause
cls

set /p x=number
if %x%==1 goto A9
if %x%==2 goto B9
if %x%==3 goto C9

:A9
echo.
echo Incorrect!  Kopi Luwak is a coffee made from digested and excreted coffee beans ingested by the civet cat.
echo.
pause
cls
goto Q11

:B9
echo.
echo Yes! Kopi Luwak is a coffee made from digested and excreted coffee beans ingested by the civet cat.
echo.
pause
set /a score=score+1
cls
goto Q11

:C9
echo.
echo Incorrect!  Kopi Luwak is a coffee made from digested and excreted coffee beans ingested by the civet cat.
echo.
pause
cls
goto Q11

:Q11
echo.
echo question 11
echo.
echo What is "Hicarl"?
echo.
echo 1. fermented meat from the greenlandic shark.
echo 2. A Finish greeting used only to greet people named Carl.
echo 3. A native Maori pork dish.
echo.
pause
cls

if %x%==1 goto A10
if %x%==2 goto B10
if %x%==3 goto C10

:A10
echo.
echo Yes!
echo.
echo Hicarl is made in Iceland using the Greenlandic shark.
echo.
pause
set /a score=score+1
cls
goto Q12

:B10
echo.
echo No!
echo.
echo Hicarl is made in Iceland using the Greenlandic shark.
echo.
pause
cls
goto Q12

:C10
echo.
echo No!
echo.
echo Hicarl is made in Iceland using the Greenlandic shark.
echo.
pause
cls
goto Q12

:Q12
echo.
echo question 12
echo.
echo Where is it beleived that coffee originated?
echo.
echo 1. Ethiopia
echo 2. Hawaii
echo 3. Colombia
echo.
pause
cls

if %x%==1 goto A11
if %x%==2 goto B11
if %x%==3 goto C11

:A11
echo.
echo YES!
echo.
echo It is said that an Ethiopian herder observed that his goats became very frisky after eating the bean of the coffee tree.
echo.
pause
cls
set /a score=score+1
goto end

:B11
echo.
echo WRONG :(
echo.
echo It is said that an Ethiopian herder observed that his goats became very frisky after eating the bean of the coffee tree.
echo.
pause
cls
goto end

:C11
echo.
echo WRONG :(
echo.
echo It is said that an Ethiopian herder observed that his goats became very frisky after eating the bean of the coffee tree.
echo.
pause
cls
goto end

:end
echo Congrats! you have finished the food quiz!
echo              -----------------
echo your score is     %score%
echo             -----------------
echo.
echo 1. Play again
echo 2. exit.
echo.
pause
cls

set /p x=number
if %x%==1 goto begin
if %x%==2 exit

A: It does not think you chose "1" look in this code:
:Q1

rem You need this:
cls

echo stuff
set /p x=
if %x% == ?? goto A1

rem And this:
goto Q1

:A1

That will stop it form going to A1.
And for Q12 you need the set /p x= it's not there. :)
Edit: And you can use set /a score+=1 not set /a score=score+1.

A: set /p x=number will not set %x% if you just hit enter. It just leaves %x% as it is. To correct it add a set x=0 before set /p x=number. Also you can easily implement some error-checking (answers other than "1", "2" and "3"
As an Example:
:Q2
echo Question and answers

set x=0
set /p x=number
if %x%==1 goto A2
if %x%==2 goto B2
if %x%==3 goto C2
echo "wrong input"
goto :Q1

Also you should overthink the usage of cls they seem to be on odd places ^^
By correcting your code, you will notice the reason for the behavior of Q12 yourself - there is missing something.


text:
Q: Converting "3H 30m" into 3.5 I am creating a SQL report for someone in which exists a column called Labour Hours of Engineer. In the column, the answers are shown as "3H 30M".
I want to change it to decimal. For example, "3H 30M" becomes 3.5.
Or another example is if an engineer works for 23 minutes, in the column, the answer should be 0.38 (rounded to 2 decimal places). 0.38 is the answer when you divide 23 mins by 60.
My current Formula is:
CONVERT(VARCHAR(40), CAST(Labour AS INT)%(24*60)/60) + '.' + CONVERT(VARCHAR(40),  CAST(Labour AS INT)%60)

Any way to achieve this, please share.

A: Assuming that the 'H' and 'M' are always there, one method would be some use of CHARINDEX to find the 'H' and return the "first" characters and also strip those first characters. For minutes, you can just use simple division to get the decimal value
DECLARE @Time varchar(7) = '3H 30M';

SELECT @Time,
       CONVERT(int,LEFT(@Time,CHARINDEX('H',@Time)-1)) + (CONVERT(decimal(2,0),REPLACE(STUFF(@Time,1,CHARINDEX('H',@Time),''),'M',''))/60);

A: This code will cover Hour minute or only minute
select Convert(decimal(26,2),
IIF(Labour like '%H%',(Convert(int, substring(Labour,0,(CHARINDEX('H',Labour)))) * 60 )+IIF(Labour like '%M%',Convert(int, substring(Labour,CHARINDEX('H',Labour)+1,CHARINDEX('M',Labour)-CHARINDEX('H',Labour)-1)),0)
,IIF(Labour like '%M%',Convert(int, substring(Labour,0,CHARINDEX('M',Labour))),0)) /60.00)


text:
Q: How to get access token for Microsoft Graph for logged in user? I am working on a .net Core 2 web app with Angular 5 frontend using Azure AD for authentication.
We have based our Graph implementation off of the aspnetcore connect sample.
https://github.com/microsoftgraph/aspnetcore-connect-sample
We have two implementations of their GetUserAccessTokenAsync method in the GraphAuthProvider.cs
https://github.com/microsoftgraph/aspnetcore-connect-sample/blob/master/MicrosoftGraphAspNetCoreConnectSample/Helpers/GraphAuthProvider.cs
We are able to get the token for the app, see bottom snippet, but the one below for retrieving the token for the logged in user is throwing the ServiceException.
Obviously the array of Users in the cca variable does not contain any users but we cannot figure out why. Are there any examples of using Microsoft Graph on a web api backend called from a Angular frontend?
Due to additional server side processing we need the calls to go through the web-api so we cannot call directly to Graph for these.
Gets Graph access token on behalf of logged in user
 public async Task<string> GetUserAccessTokenAsync(string userId)
    {
        _userTokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance();

        var cca = new ConfidentialClientApplication(
            _clientId,
            _redirectUri,
            _credential,
            _userTokenCache,
            null);

        if (!cca.Users.Any()) throw new ServiceException(new Error
        {
            Code = "TokenNotFound",
            Message = "User not found in token cache. Maybe the server was restarted."
        });

        try
        {
            var result = await cca.AcquireTokenSilentAsync(_scopes, cca.Users.First());
            return result.AccessToken;
        }

        // Unable to retrieve the access token silently.
        catch (Exception)
        {
            throw new ServiceException(new Error
            {
                Code = GraphErrorCode.AuthenticationFailure.ToString(),
                Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
            });
        }
    }

Gets Application Graph access Token
 public async Task<string> GetClientAccessTokenAsync()
    {
        _appTokenCache = new SessionTokenCache(_clientId, _memoryCache).GetCacheInstance();

        var cca = new ConfidentialClientApplication(
            _clientId,
            _clientAuthority,
            _redirectUri,
            _credential,
            null,
            _appTokenCache);

        try
        {
            var result = await cca.AcquireTokenForClientAsync(_appScopes);
            return result.AccessToken;
        }
        catch (Exception)
        {
            throw new ServiceException(new Error
            {
                Code = GraphErrorCode.AuthenticationFailure.ToString(),
                Message = "Unable to authenticate. Unable to retrieve the access token for client."
            });
        }
    }
}


text:
Q: Inverse Image Mapping with Corner Detection I am trying to identify playing cards in images. After I have successfully detected edges using Canny ( http://imgur.com/a/l4Kjd ), I know that I must use the inverse perspective transform to map the playing card for a straight look so that I can use template matching to identify the card. Is corner detection a viable method to engineering the inverse perspective of a single, or multiple, card? And if so, what would be a good corner detection -> inverse perspective transform technique combination to employ?
For the record I'm trying to implement this in my own code, as apposed to relying heavily on OpenCV, but any guidance to achieving this goal would be appreciated.

A: it is not a complate answer,just to show my idea this simple code helps to understand how contours can be filtered to analyze easily.
i think implementing a simple identifier (for pictureless cards) is possible by counting of countours that inside the card's contour. (sorry for my poor english)
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main( int, char** argv )
{
    Mat src,src_gray;
    src = imread(argv[1]);
    if (src.empty())
    {
        cerr << "No image supplied ..." << endl;
        return -1;
    }
    cvtColor( src, src_gray, COLOR_BGR2GRAY );
    src_gray = src_gray <127;

    // to simplicify contours
    dilate(src_gray,src_gray,Mat(),Point(-1,-1),2);
    erode(src_gray,src_gray,Mat(),Point(-1,-1),10);

    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    vector<Point> approx;

    findContours( src_gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE );
    src = Scalar(255,255,255);

    int counter = 0;
    for( size_t i = 0; i< contours.size(); i++ )
    {
        approxPolyDP(contours[i],approx,15,true);

        Scalar color;

        if( approx.size() == 4 & contourArea(approx) > 5000 )
            color = Scalar(0,0,255);

        {
            drawContours(src,contours,i,Scalar(0,255,0),1, LINE_AA, hierarchy, 1);
            polylines(src,approx,true,color);
            if( approx.size() == 3 ) counter++;
        }
    }
    putText(src, format("%d",counter), Point(100, 100),FONT_HERSHEY_SIMPLEX, 2, Scalar(255,0,0), 4);
    imshow( "result", src );

    waitKey(0);
    return(0);
}

result images :

EDIT: code is updated


text:
Q: CUDA: Matrix + Matrix, segmentation fault when printing solution matrix in host I'm trying to make a simple operation of adding a matrix to another one in CUDA, but I get a segmentation fault when I try to check the resault, here's the code:
/* Includes, system */
#include <stdio.h>

#include <cuda.h>
#include <cuda_runtime.h>
#define N 15000

/* DEVICE CODE */
__global__ void sumaMatrices(int *d_matrix1, int *d_matrix2, int *d_matrixSolucion){

    int idThread = blockIdx.x*blockDim.x + threadIdx.x;

    if (idThread < N)
    {
        d_matrixSolucion[idThread] = d_matrix1[idThread] + d_matrix2[idThread];
    }
}

__host__ void printMatrix(int **matrix)
{
    int i, j;
    //only 4 so the file is not too big
    for (i = 0; i < 4; i++)
    {
        for (j = 0; j < 4; j++)
        {
            printf("%d", matrix[i][j]);
            printf("  ");
        }
        printf("\n");
    }
    printf("\n");
}

/* HOST CODE*/
int main(int argc, char** argv)
{
    int i;

    int **h_matrix1;
    int **h_matrix2;
    int **h_matrixSolucion;

    int *d_matrix1;
    int *d_matrix2;
    int *d_matrixSolucion;

    h_matrix1 = (int**)malloc(N * sizeof(int*));
    for (i = 0; i < N; i++)
    {
        h_matrix1[i] = (int*)malloc(N * sizeof(int*));
    }

    h_matrix2 = (int**)malloc(N * sizeof(int*));
    for (i = 0; i < N; i++)
    {
        h_matrix2[i] = (int*)malloc(N * sizeof(int*));
    }

    h_matrixSolucion = (int**)malloc(N * sizeof(int*));
    for (i = 0; i < N; i++)
    {
        h_matrixSolucion[i] = (int*)malloc(N * sizeof(int*));
    }

    cudaMalloc((void**)& d_matrix1,N*N*sizeof(int));
    cudaMalloc((void**)& d_matrix2,N*N*sizeof(int));
    cudaMalloc((void**)& d_matrixSolucion,N*N*sizeof(int));

    fillMatrix(h_matrix1);
    fillMatrix(h_matrix2);
    fillMatrixTo0(h_matrixSolucion);

    for(i = 0; i < N; i++)
    {
        cudaMemcpy(&d_matrix1[i*N], h_matrix1[i], N*sizeof(int), cudaMemcpyHostToDevice);
        cudaMemcpy(&d_matrix2[i*N], h_matrix2[i], N*sizeof(int), cudaMemcpyHostToDevice);
    }

    int tamBloque = 256;
    int tamGrid = N/tamBloque + 1;
    sumaMatrices<<<tamGrid, tamBloque>>>(d_matrix1, d_matrix2, d_matrixSolucion);

    //nos traemos la información del device
cudaThreadSynchronize();
for(i = 0; i < N; i++)
{
    cudaMemcpy(h_matrixSolucion[i], &d_matrixSolucion[i*N],tamGrid*sizeof(h_matrixSolucion[0]),cudaMemcpyDeviceToHost);
}

    printMatrix(h_matrix1);
    printMatrix(h_matrix2);
    printMatrix(h_matrixSolucion);
}

If I comment that last line the progams doens't give any error.
I'm guesss the problem is that I don't storage the information properly in the kernel (this line: d_matrixSolucion[idThread] = d_matrix1[idThread] + d_matrix2[idThread];) but I am pretty new to CUDA and I don't really know how to solve it.
EDIT: Now that I've changed the way I get the information back from the device this is what is printing:
0  1  2  3
1  2  3  4
2  3  4  5
3  4  5  6
2  3  4  5
3  4  5  6
4  5  6  7
5  6  7  8
2  4  6  8
0  0  0  0
0  0  0  0
0  0  0  0
The first 2 matrix are the ones with the information and the other one is the solution, but only has 1 line filled.

A: There are a variety of errors in your code.

*

*There was not definition for fillMatrix

*Your underlying host allocations performed with malloc are not guaranteed to be contiguous, therefore you cannot transfer the data back in a single cudaMemcpy operation, but you must use a loop, like the loop you used to transfer data to the GPU

*Your host allocations aren't quite right but they don't present an actual problem.  This:
h_matrix1[i] = (int*)malloc(N * sizeof(int*));

should be this:
h_matrix1[i] = (int*)malloc(N * sizeof(int));

and likewise for the other similar instances.

*Your grid (total number of threads) sizing is not correct.  Your kernel uses one thread to perform one elementwise addition.  Therefore, for a NxN matrix, you need NxN threads, not just N as you are creating and testing against.
The following code has these issues fixed and seems to work correctly for me:
$ cat t2.cu
/* Includes, system */
#include <stdio.h>

#include <cuda.h>
#include <cuda_runtime.h>
#define N 15000

/* DEVICE CODE */
__global__ void sumaMatrices(int *d_matrix1, int *d_matrix2, int *d_matrixSolucion){

    int idThread = blockIdx.x*blockDim.x + threadIdx.x;

    if (idThread < N*N)
    {
        d_matrixSolucion[idThread] = d_matrix1[idThread] + d_matrix2[idThread];
    }
}

__host__ void printMatrix(int **matrix)
{
    int i, j;
    //only 4 so the file is not too big
    for (i = 0; i < 4; i++)
    {
        for (j = 0; j < 4; j++)
        {
            printf("%d", matrix[i][j]);
            printf("  ");
        }
        printf("\n");
    }
    printf("\n");
}

/* HOST CODE*/
int main(int argc, char** argv)
{
    int i;

    int **h_matrix1;
    int **h_matrix2;
    int **h_matrixSolucion;

    int *d_matrix1;
    int *d_matrix2;
    int *d_matrixSolucion;

    h_matrix1 = (int**)malloc(N * sizeof(int*));
    for (i = 0; i < N; i++)
    {
        h_matrix1[i] = (int*)malloc(N * sizeof(int));
        for (int j = 0; j < N; j++) h_matrix1[i][j] = 1;
    }

    h_matrix2 = (int**)malloc(N * sizeof(int*));
    for (i = 0; i < N; i++)
    {
        h_matrix2[i] = (int*)malloc(N * sizeof(int));
        for (int j = 0; j < N; j++) h_matrix2[i][j] = 2;
    }

    h_matrixSolucion = (int**)malloc(N * sizeof(int*));
    for (i = 0; i < N; i++)
    {
        h_matrixSolucion[i] = (int*)malloc(N * sizeof(int));
        for (int j = 0; j < N; j++) h_matrixSolucion[i][j] = 0;
    }

    cudaMalloc((void**)& d_matrix1,N*N*sizeof(int));
    cudaMalloc((void**)& d_matrix2,N*N*sizeof(int));
    cudaMalloc((void**)& d_matrixSolucion,N*N*sizeof(int));

    for(i = 0; i < N; i++)
    {
        cudaMemcpy(&d_matrix1[i*N], h_matrix1[i], N*sizeof(int), cudaMemcpyHostToDevice);
        cudaMemcpy(&d_matrix2[i*N], h_matrix2[i], N*sizeof(int), cudaMemcpyHostToDevice);
    }

    int tamBloque = 256;
    int tamGrid = (N*N)/tamBloque + 1;
    sumaMatrices<<<tamGrid, tamBloque>>>(d_matrix1, d_matrix2, d_matrixSolucion);

    cudaThreadSynchronize();
    for(i = 0; i < N; i++)
    {
        cudaMemcpy(h_matrixSolucion[i],&d_matrixSolucion[i*N],N*sizeof(int),cudaMemcpyDeviceToHost);
    }

    printMatrix(h_matrix1);
    printMatrix(h_matrix2);
    printMatrix(h_matrixSolucion);
}
$ nvcc -o t2 t2.cu
$ cuda-memcheck ./t2
========= CUDA-MEMCHECK
1  1  1  1
1  1  1  1
1  1  1  1
1  1  1  1

2  2  2  2
2  2  2  2
2  2  2  2
2  2  2  2

3  3  3  3
3  3  3  3
3  3  3  3
3  3  3  3

========= ERROR SUMMARY: 0 errors
$


text:
Q: How do you detect and print the current drilldown in the CrystalReportViewer control? When using Business Objects' CrystalReportViewer control, how can you detect and manually print the report the user has currently drilled into? You can print this automatically using the Print() method of the CrystalReportViewer, but I want to be able to do a manual printing of this report.
It is possible to print the main ReportSource of the CrystalReportViewer, but I need to know what report the user has drilled into and then do a manual printing of that particular drill down. Any ideas?

A: I'm not sure which version of Crystal Reports you are using, but if it is XIR2 or earlier then this isn't possible.  I haven't used the newer versions so I can't tell you.  One thing that I've done to solve this in the past was to have the drill actually link to another report altogether.  It depends on how your viewers actually view the reports (either via a thick-client viewer, the developer, or the web portal) on whether this will work however.  Good luck!

A: detect: yes!
webpage:
<CR:CrystalReportViewer ...
    ondrill="CrystalReportViewer1_Drill"
    ondrilldownsubreport="CrystalReportViewer1_DrillDownSubreport" />

code behind:
 protected void CrystalReportViewer1_Drill(object source, CrystalDecisions.Web.DrillEventArgs e)
 {
  //drill from graph to list of elements
 }
protected void CrystalReportViewer1_DrillDownSubreport(object source, CrystalDecisions.Web.DrillSubreportEventArgs e)
 {
   //drill from main report to subreports
 }

print current: no!
protected void CrystalReportViewer1_DrillDownSubreport(object source, CrystalDecisions.Web.DrillSubreportEventArgs e)
{
    reportDocument.OpenSubreport(e.NewSubreportName).ExportToHttpResponse(format, Response, true, title);
}

exporting subreports throws an exception "not allowed for subreports".
solution
CrystalReportsViewer's button works also on drilldown...
<CR:CrystalReportViewer    HasExportButton="true" ....


text:
Q: remove_filter excerpt_more from a plugin class I'm trying to remove a filter from within my plugin class. I need to remove the 'continue reading' link from the_excerpt. The base theme is the twenty ten theme and they are applying a filter twentyten_auto_excerpt_more. I cannot remove the filter, I assume because I'm within a class:
class MyAwesomeClass {

private static $instance;

public static function instance() {
    if ( !isset( self::$instance ) ) {
        self::$instance = new MyAwesomeClass;
        self::$instance->setup_actions_and_filters();
    }
    return self::$instance;
}

private function __construct() {}

public function setup_actions_and_filters() {
    add_filter( 'excerpt_more', array( $this, 'change_excerpt_more' ) );
}

public function change_excerpt_more( $excerpt ) {
    remove_filter( 'excerpt_more', 'twentyten_auto_excerpt_more' );
    return '';
}

}

MyAwesomeClass::instance();

The filter I am trying to remove:
add_filter( 'excerpt_more', 'twentyten_auto_excerpt_more' );

Is there a way of doing this?

A: The priority value has to match on remove_filter. I am guessing that it does not. Try:
remove_filter( 'excerpt_more', 'twentyten_auto_excerpt_more' );

Or find add_filter( 'excerpt_more', 'twentyten_auto_excerpt_more' and check the priority, then make it match.

A: It turns out that it was get_the_excerpt filter that needed removing, in either case it has to be done through after_setup_theme:
public function setup_actions_and_filters() {
    add_action( 'after_setup_theme', array( $this, 'run_plugin_setup' ) );
}

public function run_plugin_setup() {
    remove_all_filters( 'get_the_excerpt' );
}

Hope this helps someone.


text:
Q: How Make iPhone to silent mode on/off using objective c I am creating one app in which i want to detect that iphone is on silent mode or not.
I have already gone  thought the below link
Detecting the iPhone's Ring / Silent / Mute switch using AVAudioPlayer not working?
Switching between silent mode and ring mode on an iPhone
many people says that it is against the iPhone policy. but i have seen many app which is also giving this functionality
check the below app link
https://itunes.apple.com/us/app/silentalert/id506092189?mt=8
I also want to change the silent mode of the iPhone same as the above app is doing.
Is anyone know about that ?

A: There is way but your application will be rejected by Apple (I am not sure, may be not). Add a MPVolumeView to your view, but do not show it to the user (for this purpose you can change the frame according to your view). You can get the sound level from this control. Here is the code (iOS +7 is tested):

    - (void)someMethod
    {
        MPVolumeView *systemVolumeSlider = [[MPVolumeView alloc] initWithFrame:  CGRectMake(-100, -100, 16, 16)];
        [systemVolumeSlider setUserInteractionEnabled:NO];
        systemVolumeSlider.showsRouteButton = NO;
        [self.view addSubview: systemVolumeSlider];
        [systemVolumeSlider sendSubviewToBack:self.view];

        [[AVAudioSession sharedInstance] setActive:YES error:NULL];

        float currentSoundLevel = [self getVolumeLevel];
        NSLog(@"volume level : %f", currentSoundLevel); // if it is 0, the phone is in silent mode

        // do your job here...

        [[MPMusicPlayerController applicationMusicPlayer] setVolume:1.0]; // 1.0 is the max level

        // do your job here...
     }

    - (float)getVolumeLevel
    {
        MPVolumeView *slide = [MPVolumeView new];
        UISlider *volumeViewSlider;
        for (UIView *view in [slide subviews]){
            if ([[[view class] description] isEqualToString:@"MPVolumeSlider"])
                volumeViewSlider = (UISlider *) view;
        }
        return [volumeViewSlider value];
    }


text:
Q: Pandas read_csv giving a larger dataframe than the one I wrote it with using pd.to_csv() I have a dataframe in one file I am writing to a csv using pd.to_csv() and then in another file I am opening that csv into a dataframe using pd.read_csv() but they are different sizes? The number of rows it the dataframe is larger when I am reading the csv back in the other file. Any thoughts on what this could be?
So here the snippet of code in question. I cleared the csv before running again and the shape of the df before writing to the csv was (32636, 28).
Opening it up the shape is (68450, 29).
I am only running this on 2 files currently.
writing csv code
edit:
The json is twitter api data if that helps.


text:
Q: How to select by 1 xbar date/second in kdb+ I am trying to run a select on a table whereby the data in the table ranges across multiple days, thus it does not conform to daily data that the documentation eludes to.
Application of the xbar selection accross multiple days obviously results in data that is not ordered i.e. select last size, last price by 1 xbar time.second on data that includes 2 days would result in:
second   | size price
====================
00:00:01 | 400  555.5
00:00:01 | 600  606.0
00:00:02 | 400  555.5
00:00:02 | 600  606.0

How can one add the current date in the selection such that the result like what is done in pandas can still be orderly across multiple days e.g: 2019-09-26 16:34:40
Furthermore how does one achieve this whilst maintaining a date format that is compatible with pandas once stored in csv?

A: NB: It is easiest for us to assist you if you provide code that can replicate a sample of the kind of table that you are working with. Otherwise we need to make assumptions about your data.
Assuming that your time column is of timestamp type (e.g. 2019.09.03D23:11:54.711811000), a simple solution is to xbar by one as a timespan, rather than using the time.second syntax:
select last size, last price by 0D00:00:01 xbar time from data

Using xbar keeps the time column as a timestamp rather than casting it to second type.
If your time column is of some other temporal type then you can still use this method if you have a date column in your table that you can use to cast time to a timestamp. This would look something like:
select last size, last price by 0D00:00:01 xbar date+time from data

A: I would suggest to group by both date and second, and the sum them
update time: date+time from
    select last size, last price
        by date: `date$time, time: 1 xbar `second$time from data

Or the other shorter and more efficient option is to sum date and second right in the group clause:
select last size, last price by time: (`date$time) + 1 xbar `second$time from data


text:
Q: What's the Best Way to Catch the Return Key in a PasswordBox? (WPF/XAML) What's the best way to catch the return key in a PasswordBox? (WPF/XAML)
I have a TextBox field and a PasswordBox field on my login form (for username and password entry). I also have a login button which invokes the method that performs the login validation process.
I need to make the Return key react the same way in the PasswordBox, so that the user can have the option enter their username and password and simply hit Return to log in.
Does anyone know how this is done in WPF? Any help is appreciated.

A: There is an even easier mechanism to activate the button's code. WPF Button class provides a property called IsDefault. When set to true, if you press return while some objects in the window have focus, the code of the click event of the button will be fired automatically. This mechanism works like a charm with the passwordbox.

A: You can handle the KeyDown event on the PasswordBox (and TextBox if desired) and then use the following event handler --
private void OnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key != Key.Return && e.Key != Key.Enter)
        return;
    e.Handled = true;
    HandleEnter();
}

A: You could try using a RoutedCommand.
You can set it on the Command property of the Button.
You can also add a KeyGesture to the InputBindings of your loginform to bind the Enter key to trigger your RoutedCommand.
Then add a CommandBinding in the CommandBindings of your loginform to bind the RoutedCommand to Executed handlers in your code and perform or trigger your login validation process.