text:
Q: How can I create temperature specific color chart in iOS In this question I need some algorithmic or logical help from you guys. If this is possible in some ways...
So I have to develop/write a function that receive a temperature value as an input (C° or F°), and return the specific color against the temperature exactly in this picture. For example if we input 0C° the color value should be return as Cyan (Hex value: 29eff6 OR RGB: 41,239,246)
Reference Image

I have searched a lot on different sites but found nothing related this. There are kelvin color codes for 1000K° plus and these are not related to my problem.
Any help on this would be greatly appreciated.

A: range.png:
Here is an example of a simple/fake solution I mentioned in a comment:
import UIKit

func mapValue(value: CGFloat, inMin: CGFloat, inMax: CGFloat, outMin: CGFloat, outMax: CGFloat) -> CGFloat {
    // when the input value is lower than `inMin` use `inMin`
    // when the input value is bigger than `inMax` use `inMax`
    let value = max(min(value, inMax), inMin)

    let div = inMax - inMin
    guard div > 0 else {
        return inMin
    }

    return (value - inMin) / div * (outMax - outMin) + outMin
}

func getColor(for degreesCelsius: CGFloat) -> UIColor {
    // your color-range-image
    let rangeImage = UIImage(named: "range.png")!

    // the size of your color-range-image
    let imageSize = rangeImage.size

    let inMin: CGFloat = -50 // the lowest value as seen from the image
    let inMax: CGFloat = 55 // the highest value as seen from the image

    // the mapped input value
    let mappedInput = mapValue(value: degreesCelsius,
                               inMin: inMin, inMax: inMax,
                               outMin: 0, outMax: imageSize.width - 1)

    // position of the pixel in the image whose color should be extracted
    let pos = CGPoint(x: mappedInput, y: 0)

    return rangeImage.getPixelColor(pos: pos)
}

// get the color of 37°C
let color = getColor(for: 37)

For extracting the UIColor of an UIImage at a certain position you could use:
// taken from https://stackoverflow.com/a/40237504/4511639
extension UIImage {
    func getPixelColor(pos: CGPoint) -> UIColor {

        let pixelData = self.cgImage!.dataProvider!.data
        let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

        let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4

        let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
        let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
        let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
        let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)

        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
}

A: What you need is convert Temperature to RGB color. For that you can use:

*

*Star B-V color index to apparent RGB color
You image however suggest you are using wavelength colors instead of temperature colors:

*

*RGB values of visible spectrum
as your gradient has nothing to do with real temperature then just use the code in the link. Then just linearly interpolate between temperature and wavelength like:
wavelength = 400 + (800-400)*(T-t0)/(t1-t0) [nm]

where T is your temperature and t0,t1 are the gradient edge temperatures in the same units as T for example:
t0=-50C
t1=+50C

if you play with t0,t1 you might shift the colors to left and right. You can also use any other interpolation not just linear. Or even interpolate the image RGB like I did in both of the linked QAs.
In case you wanted the real thing (which you clearly stated you don't but those who venture here due to your title might) then the real problem is how to convert temperature into BV index. I cannot find any equation for it now. The only stuff I found is
equation:

table:
    T[K]    BV
O5  42 000  -0.33
O9  34 000  -0.31
B0  30 000  -0.30
B2  20 900  -0.24
B5  15 200  -0.17
B8  11 400  -0.11
A0  9 790   -0.02
A2  9 000   0.05
A5  8 180   0.15
F0  7 300   0.30
F2  7 000   0.35
F5  6 650   0.44
F8  6 250   0.52
G0  5 940   0.58
G2  5 790   0.63
G5  5 560   0.68
G8  5 310   0.74
K0  5 150   0.81
K2  4 830   0.91
K5  4 410   1.15
M0  3 840   1.40
M2  3 170   1.49
M5  3 170   1.64

dependece graph::

So you either interpolate it or approximate from table/graph or compute it algebraically from the equation (looks like quadratic equation to me).
if I did not make any mistake than:
bv0=(+sqrt((729.0*T*T) + 52900000000.0) - (58*T) + 230000.0 ) / 46.0*T
bv1=(-sqrt((729.0*T*T) + 52900000000.0) - (58*T) + 230000.0 ) / 46.0*T

my guts are telling me that bv0 is the one as bv1 would be too much negative. but It looks like the Wiki equation is just very poor approximation so its inverse is even worse ...
On top of all this if you got specific parameters of the object and environment than you need to change the color by it by adding scattering and mixing body color if you want more realistic colors.


text:
Q: Unable to access lambda function from s3 hosted react application I have a react application which has a post method requesting data from a lambda function. It is working fine in my local machine. But when I deployed the application on s3 bucket and try to access it through s3 endpoint, it gives me 405 Method not allowed error. After search I found that post method will not work with s3 endpoint, So again I tried with rest api endpoint, but it shows file name xml. I am able to access application when I add index page to rest api endpoint, But here also I am getting 412 error in post method. So in any case I am getting error with post method. Can someone help me with that. I don't know what I am missing. Below is my code:
const apiUrl = process.env.NODE_ENV === 'production' ? process.env.REACT_APP_PROD_API_URL : process.env.REACT_APP_DEV_API_URL;

const params = (query: string) =>  ({
  headers: {
    "Accept": "application/sparql-results+json",
    "Accept-Encoding": "gzip",
    "Content-Type": "application/x-www-form-urlencoded"
  },
  method: "POST",
  body: `query=${encodeURIComponent(query)}`
})

const fetchClinicalStudies = async () => {
    const clinicalStudiesQuery = `
      PREFIX dcterms: <http://purl.org/dc/terms/>
      PREFIX disco:   <http://rdf-vocabulary.ddialliance.org/discovery#>

      SELECT ?id ?label
      WHERE {
      ?id a disco:Study ;
          dcterms:title ?label .
      }
      ORDER BY ?label`

      const response = await fetch(apiUrl ?? '', params(clinicalStudiesQuery))
      return response;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tagging PDF files on CD/DVD and opening them with the associated viewer Simple thing. I have a lot - and I do mean, A LOT (if it was possible to colour this in red, it probably would be red as well) of PDF/dejavu/word/plain jpeg files; mostly articles from my professional domain. Memories fade, and the mind works on something else, and more often than not I find myself seraching for that thing, I saw somewhere.
Titles, as it is customary in academia, rarely give anything away in relation to the content.
Is there somewhere a system which enables me to keep those files with their original names (relating to our library system) but that indexes them, and tags them, so I can search by titles and by tags, and by clicking on the interesting work open them in their associated viewer.
That way I can burn one part of my personal library to a CD/DVD ... upon placing them in the drive, a system(?) would open, giving me the names of the articles on the disc, or the ability to view the tags, ... I find what I want, and it opens them in Sumatra/Adove/Foxit... ?
Does such precious thing exists?

A: I had good experience with tag2find on Windows.I used zotero firefox extension.
Now, I'm using google documents.


text:
Q: Howto prevent spoofed posting to a PHP like/unlike system I am trying to make a like/unlike system, when a user clicks like on a post, his/her user id (which is stored in a session) and the post id will be stored in a database through an ajax call.
Then I thought what if some user make a html form with invisible input field (which has one of his post ids) on another domain and give its link to a user who checked remember me later or is viewing my site.
The user will click the button and The form will POST post id to my site, session contains user id and these will be stored in database.
No good solution comes to my mind. Is there any way more reliable than HTTP referrer to prevent this?
Thanks in advance

A: One way is to insert a secret variable into the HTML which is specific to a user's session. This can prevent cross site forgery.
In PHP you'd generate a random 'key' and store it in the session:
$_SESSION['myFormVar'] = md5(mt_rand());

Then in a form, you'd add as a hidden variable:
<input type="hidden" name="chkVar" value="<?=$_SESSION['myFormVar']?>"/>

You should submit your form via POST and preferably over HTTPS, making it harder (but not impossible) to intercept the value of chkVar.
In the code that processes your posted form, compare the posted chkVar against your session variable. In an ideal world, you'd have a unique chkVar per request, however using one which is the same for an entire session often works fine and guards against most csrf attacks.

A: You are talking about CSRF exploit.
This is a good security question.
It's generaly managed with a key that is only known by the server.
This key have to be used in all your forms.
Here is a little tutorial to protect against it

A: The only thing you should be sending is the post id, the user id should be picked up automatically in the script you are calling through AJAX. Assuming you have validated the user is logged in, you have both pieces of information without any further security risk.


text:
Q: Filtering specific iterators for template functions I am developing a set of functions that takes advantage of containers that have packed and sequential memory storage (for memory copies).  They have function signatures in the style of most STD functions, input/output iterators point to elements and denote ranges.  For instance, a function could look like this:
template< typename InputIterator, typename OutputIterator >
OutputIterator fooBar( InputIterator& first, InputIterator& last,
                       OutputIterator& result );

I wish to verify that the iterators passed are legal, that is packed and sequential.  For the STD containers, this is limited to std::vector and std::array.  Unfortunately, I can't rely on the iterator 'category' trait, because the random access trait does not imply seqential storage.  An example of this is microsofts concurrent_vector class, documented here parallel containers
In addition, I can't accept all iterators from the vector and array classes either, for instance i need to reject reverse iterators, and std::vector<bool> iterators are unsuitable because of the proxy class that it uses.
I've attempted to create my own traits class to distinguish and filter the iterators with the constraints that i describe above, but i'm running into template syntax problems.  I am looking for feedback from others on how they would approach this problem.
Thanks

A: I don't think you can do this. Iterators are an abstraction whose whole purpose is to make the iteration process independent of the underlying architecture. There is no information in the standard iterators that denote the underlying memory structure or even anything remotely similar.
On your std-algorithm-like functions, it's generally advised to pass iterators by value, since they should be cheap / small objects. It should be especially noted that your function would never be able to be called as fooBar(c.begin(), c.end(), some_out_it);, since it takes the the input iterators by reference-to-non-const.
As a last point, you can filter out reverse iterators by testing whether the iterator type is a specialization of std::reverse_iterator<Iter>, since atleast the Container::(const_)reverse_iterator type of standard containers are required to be one.


text:
Q: How to pass data to different page using AngularJS? Quite new to angularJS and trying to pass information from one page to another.
Currently this controller displays a list of customers in a table format, with one column being the "More info".
 ** adminSearch.html **

 ...

     {{custObj.id}}
     {{custObj.name}}
      More Info

 ...

Controller:
** adminSearch.js **
app.controller('adminSearch', ['$scope', function($scope) {
$scope.customers = [{id:1, name:'John', email:'John@example.com', phone:'555-1276', account:123456, mylH: '1'},
             {id:2, name:'Mary', email:'Mary@example.com', phone:'800-BIG-MARY', account:123456, mylH: '1'},
             {id:3, name:'Mike', email:'Mike@example.com', phone:'555-4321', account:123456, mylH: '0'}];}]);

What I want is when the user clicks "More Info" from the table for one of the customer, it should go to a new page displaying all the information about that customer...
Not sure what the new page needs but I am guessing it needs a new controller:
  ** customerInfo.html **

 ...

  ** customerInfo.js **
  app.controller('customerInfo', ['$scope', function($scope) {
  }]);

Thanks for your help is advance!

A: from what i understand is that you need to navigate from one html file to another html file and pass the customer details for that page. then i would suggest to use ui router to navigate through pages. please refer this link https://scotch.io/tutorials/3-simple-tips-for-using-ui-router


text:
Q: Is there any good JAVA lib for playing with WSDL's and WS-* bindings? Is there any good JAVA lib for playing with reading from WSDL's and connecting to WS-* bindings?

A: Take a look at Apache Axis2 - one of the most popular java webservices framework. It has multiple Java - XML binding methods (e.g. JAXB, ADB).
A good alternative would be Metro (from Sun, part of the GlassFish stack) or Apache CXF (previously called XFire)
For a summary: Wikipedia

A: Does Apache CXF or Apache Axis suit your needs?

A: In case you want play and write WSDL elements you can use Wsdl4J JSR implementation which is what even Axis uses behind the scene.
This gives u a nice API to read and write WSDL elements


text:
Q: Can't scroll while using pointer-events: auto; property I'm using pointer-event. and the problem is i can't use scroll no more. how can i scroll ?
pointer-events: auto;

div{
  pointer-events: none;
  height: 100px;
  overflow: scroll;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,

A:

div{
  user-select: none;
  height: 100px;
  overflow: scroll;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,

Don't use pointer-events - use user-select


text:
Q: C# regex data from website I am trying to make an addon to a game named Tibia.
On their website Tibia.com you can search up people and see their deaths.
forexample:
http://www.tibia.com/community/?subtopic=characters&name=Kixus
Now I want to read the deaths data by using Regex in my C# application.
But I cannot seem to work it out, I've been spending hours and hours on
http://myregextester.com/index.php
The expression I use is :

(.*?)?#160;CET	((?:Died|Killed) at Level ([^ ]*)|and) by (?:<[^>]*>)?([^<]*).

But I cannot make it work.
I want the Timestamp, creature / player Level, and creature / player name
Thanks in advance.
-Regards

A: It's a bad idea to use regular expressions to parse HTML. They're a very poor tool for the job. If you're parsing HTML, use an HTML parser.
For .NET, the usual recommendation is to use the HTML Agility Pack.

A: As suggested by Joe White, you would have a much more robust implementation if you use an HTML parser for this task. There is plenty of support for this on StackOverflow: see here for example.
If you really have to use regexs
I would recommend breaking your solution down into simpler regexs which can be applied using a top down parsing approach to get the results.
For example:

*

*use a regex on the whole page which matches the character table
I would suggest matching the shortest unique string before and after the table rather than the table itself, and capturing the table using a group, since this avoids having to deal with the possibility of nested tables.

*use a regex on the character table that matches table rows

*use a regex on the first cell to match the date

*use a regex on the second cell to match links

*use a regex on the second cell to match the players level

*use a regex on the second cell to match the killers name if it was a creature (there are no links in the cell)

This will be much more maintainable if the site changes its Html structure significantly.
A complete working implementation using  HtmlAgilityKit
You can dowload the library from the HtmlAgilityKit site on CodePlex.
// This class is used to represent the extracted details
public class DeathDetails
{
    public DeathDetails()
    {
        this.KilledBy = new List<string>();
    }

    public string DeathDate { get; set; }
    public List<String> KilledBy { get; set; }
    public int PlayerLevel { get; set; }
}

public class CharacterPageParser
{
    public string CharacterName { get; private set; }

    public CharacterPageParser(string characterName)
    {
        this.CharacterName = characterName;
    }

    public List<DeathDetails> GetDetails()
    {
        string url = "http://www.tibia.com/community/?subtopic=characters&name=" + this.CharacterName;
        string content = GetContent(url);

        HtmlDocument document = new HtmlDocument();
        document.LoadHtml(content);

        HtmlNodeCollection tables = document.DocumentNode.SelectNodes("//div[@id='characters']//table");

        HtmlNode table = GetCharacterDeathsTable(tables);
        List<DeathDetails> deaths = new List<DeathDetails>();

        for (int i = 1; i < table.ChildNodes.Count; i++)
        {
            DeathDetails details = BuildDeathDetails(table, i);
            deaths.Add(details);
        }
        return deaths;
    }

    private static string GetContent(string url)
    {
        using (System.Net.WebClient c = new System.Net.WebClient())
        {
            string content = c.DownloadString(url);
            return content;
        }
    }

    private static DeathDetails BuildDeathDetails(HtmlNode table, int i)
    {
        DeathDetails details = new DeathDetails();

        HtmlNode tableRow = table.ChildNodes[i];

        //every row should have two cells in it
        if (tableRow.ChildNodes.Count != 2)
        {
            throw new Exception("Html format may have changed");
        }

        HtmlNode deathDateCell = tableRow.ChildNodes[0];
        details.DeathDate = System.Net.WebUtility.HtmlDecode(deathDateCell.InnerText);

        HtmlNode deathDetailsCell = tableRow.ChildNodes[1];
        // get inner text to parse for player level and or creature name
        string deathDetails = System.Net.WebUtility.HtmlDecode(deathDetailsCell.InnerText);

        // get player level using regex
        Match playerLevelMatch = Regex.Match(deathDetails, @" level ([\d]+) ", RegexOptions.IgnoreCase);
        int playerLevel = 0;
        if (int.TryParse(playerLevelMatch.Groups[1].Value, out playerLevel))
        {
            details.PlayerLevel = playerLevel;
        }

        if (deathDetailsCell.ChildNodes.Count > 1)
        {
            // death details contains links which we can parse for character names

            foreach (HtmlNode link in deathDetailsCell.ChildNodes)
            {
                if (link.OriginalName == "a")
                {
                    string characterName = System.Net.WebUtility.HtmlDecode(link.InnerText);
                    details.KilledBy.Add(characterName);
                }
            }
        }
        else
        {
            // player was killed by a creature - capture creature name
            Match creatureMatch = Regex.Match(deathDetails, " by (.*)", RegexOptions.IgnoreCase);
            string creatureName = creatureMatch.Groups[1].Value;
            details.KilledBy.Add(creatureName);
        }
        return details;
    }

    private static HtmlNode GetCharacterDeathsTable(HtmlNodeCollection tables)
    {
        foreach (HtmlNode table in tables)
        {
            // Get first row
            HtmlNode tableRow = table.ChildNodes[0];

            // check to see if contains enough elements
            if (tableRow.ChildNodes.Count == 1)
            {
                HtmlNode tableCell = tableRow.ChildNodes[0];
                string title = tableCell.InnerText;

                // skip this table if it doesn't have the right title
                if (title == "Character Deaths")
                {
                    return table;
                }
            }
        }

        return null;
    }

And an example of it in use:
 CharacterPageParser kixusParser = new CharacterPageParser("Kixus");

        foreach (DeathDetails details in kixusParser.GetDetails())
        {
            Console.WriteLine("Player at level {0} was killed on {1} by {2}", details.PlayerLevel, details.DeathDate, string.Join(",", details.KilledBy));
        }

A: try this :
http://jsbin.com/atupok/edit#javascript,html
and continue from there .... I did the most job here :)
edit
http://jsbin.com/atupok/3/edit
and start using this tool
http://regexr.com?2vrmf
not the one you have.

A: You can also use Espresso tool to work out proper regular expression.
To properly escape all special characters that are not parts of regular expression you can use Regex.Escape method:
string escapedText = Regex.Escape("");


text:
Q: Php Error. Notice: Undefined property: mysqliConn::$affected_rows I have this code in OOP Php
include ('connection.php');

class NestedSet
{
/*Properties*/

/**
 * Mysqli object
 * @var object
 */
protected $db;

/**
 * Name of the database table
 * @var string
 */
public $table = 'tree';

/**
 * Primary key of the database table
 * @var string
 */
public $pk = 'id';

/**
 * Namefield in the database table
 * @var unknown_type
 */
public $name = 'name';

/*Methods*/

/**
 * Stores a Mysqli object for further use
 * @param object $mysqli Mysqli object
 * @return boolean true
 */
public function __construct() {
    $this->db = mysqliConn::init();
    return true;
}

 protected static $instance = NULL;

// public static function get_instance()
// {
//     //if ( NULL === self::$instance )
//      //   self::$instance = new self;

//    // return self::$instance;
// }

/**
 * Creates the root node
 * @param string $name Name of the new node
 * @return boolean true
 */

public function createRootNode($name) {
    $this->db->query("LOCK TABLES " . $this->table . " WRITE");
    $sql = "SELECT rgt FROM " . $this->table . " ORDER BY rgt DESC LIMIT 1";
    $result = $this->db->query($sql);
    if ($this->db->affected_rows == 0) {
        $lft = 1;
        $rgt = 2;
    } else {
        $obj = $result->fetch_object();
        $lft = $obj->rgt + 1;
        $rgt = $lft + 1;
    }
    $sql = "INSERT INTO " . $this->table . " (" . $this->name . ", lft, rgt) VALUES ('" . $name . "', " . $lft . ", " . $rgt . ");";
    $this->db->query($sql);
    $this->db->query("UNLOCK TABLES");
    return true;
}

}

?>

I create a new object for the class NestedSet in an other file called index.php
    <?php

    include("nested_set.php");

    $nested = new NestedSet(); //Create a NestedSet object
    $nested->createRootNode('root');

    ?>

I can write on db but the $rgt and $lft stays 2 and 1;
and this error is displayd :
"Notice: Undefined property: mysqliConn::$affected_rows in C:\wamp\www\hr-test\nested_set.php on line 67"

Any idea on what im doing wrong?
Thank you!!
CODE FOR connection.php
   <?php

   define('SERVER', 'localhost');
   define('USERNAME', 'root');
   define('PASSWORD', '');
   define('DATABASE', 'hr_test2');

 class mysqliConn
 {
 private static $instance;
 private $connection;

 private function __construct()
 {
    $this->connection = new mysqli(SERVER,USERNAME,PASSWORD,DATABASE);
 }

 public static function init()
 {
    if(is_null(self::$instance))
    {
        self::$instance = new mysqliConn();
    }

    return self::$instance;
 }

 public function __call($name, $args)
 {
    if(method_exists($this->connection, $name))
    {
         return call_user_func_array(array($this->connection, $name),    $args);
    } else {
         trigger_error('Unknown Method ' . $name . '()', E_USER_WARNING);
         return false;
    }
}

}
?>

A: Because a mysqli->query() returns a mysqli_result object which will contain information about the result of the query you need to use $result and not $this->db->
Also the mysqli_result object does not contain an affected_rows property you should use the num_rows property which does exist, but on the $result object instead.
You can also simplify the concatenation of the query string you create, although you should really use prepared statements.
public function createRootNode($name) {
    $this->db->query("LOCK TABLES " . $this->table . " WRITE");
    $sql = "SELECT rgt FROM " . $this->table . " ORDER BY rgt DESC LIMIT 1";
    $result = $this->db->query($sql);

    // if ($this->db->affected_rows == 0) {
    if ($result->num_rows == 0) {
        $lft = 1;
        $rgt = 2;
    } else {
        $obj = $result->fetch_object();
        $lft = $obj->rgt + 1;
        $rgt = $lft + 1;
    }

    $sql = "INSERT INTO {$this->table} ( {$this->name}, lft, rgt)
            VALUES ('$name', $lft , $rgt)";

    $this->db->query($sql);
    $this->db->query("UNLOCK TABLES");
    return true;
}


text:
Q: DAX - Summarize on different granularity level I have the following "fact" table in Excel 2013:
+----------+-------+-----------+---------------+----------------+
| Employee | Month | Branch_Id | Branch Target | Employee sales |
+----------+-------+-----------+---------------+----------------+
| John     |     1 | A         |           100 |             20 |
| John     |     2 | A         |           100 |             10 |
| Dave     |     1 | B         |            80 |             30 |
| Dave     |     2 | B         |            80 |              5 |
| Paul     |     1 | A         |           100 |             20 |
| Paul     |     2 | A         |           100 |             60 |
+----------+-------+-----------+---------------+----------------+

The column "Branch Target" is delivered by a Join clause from table "Targets":
+--------+--------+
| Branch | Target |
+--------+--------+
| A      |    100 |
| B      |     80 |
+--------+--------+

Now, I wish to have a dynamic  calculation of two fields: "Branch Target" and "Employee Sales", so the final output will be as follow:
+--------+--------+-------+
| Branch | Target | Sales |
+--------+--------+-------+
| A      |    100 |   110 |
| B      |     80 |    35 |
+--------+--------+-------+

I'm struggling with the Target coulmn since a SUM function will summrize according to all the rows it apears in the Fact table and - i.e. - for branch A it will yeild 400.
I thought of using an average (400/4 = 100) for adjusting it, however it is not a dynamic solution and doesn't hold when I remove the Branch "grouping" from the output pivot.
Appreciate your help.
Asaf

A: Remove the target from the big fact table (let's call that the Sales table). Add the targets table to Power Pivot. Add a new table with one row per Branch and call it branch. Branch in the Sales fact table should foreign key to the new Branch table. Branch in the targets table should foreign key to the new Branch table. Hide (right click and Hide from Client tools) the branch column in the Fact table and the targets table. Create a simple sum measure for your Branch target:
Branch Target := SUM('Targets'[Target])

That's it. Basically load your tables at their native grain into Power Pivot and it will do the rest.
The other best practice you will notice in the above is that if you have two tables with measures you need to have a separate dimension table.


text:
Q: Heroku-cli: docker run exited with 127 after trying to deploy docker image of NodeJS app I tried to deploy my docker image to heroku using heroku-cli,
but I got this error:
$: heroku container:run web
docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"\": executable file not found in $PATH": unknown.
 ▸    Error: docker run exited with 127

This docker image works fine in local with command docker run -d -p 3000:3000 webApp
Already tried to add PATH variable inside heroku, but it didn't help.
Tried to find out what does heroku container:run web run behind but still zero result.
I also found that the documentation of heroku container is obsolete, they said to run heroku container:release web, but after I check heroku help container there is no heroku container:release.


text:
Q: Can NodeJS MySQL Database be accessed by other computer programs? I need to setup mysql database. So, that NodeJS server and external program can access the same mysql database. So, I installed mysql with npm install mysql on the terminal. I test ran nodejs mysql sample code. It works; created database and table. But now, I want this other program to get access to this mysql database. Can this be done? or Do I have to actually install MySQL driver for my system?

A: The mysql package is just a way for Node.js to access a MySQL database. Other programs will also be able to access the same database if you install the appropriate drivers/libraries for them.

A: You have to install the drivers here called connctors  for all languages that are used and don't have them integrated.


text:
Q: Error while creating variadic class in C++ I am trying to create a class that when provided with a list of pairs of iterator begin and ends generates a sequence of vectors that give the cartesian product of the elements in the input vectors.
The code works when 2 pairs of iterators are given to the initializer of the class. However, when another pair is added, it fails to compile.
iterators.h
template<typename InputIterator,typename ...InputIterators>
class Product{
    typedef  typename std::iterator_traits<InputIterator>::value_type base_value;
    InputIterator base,end,curr;
    Product* next = nullptr;
    void reset(){
        curr = base;
    }
public:
    explicit Product(InputIterator begin,InputIterator end,InputIterators... args) :base(begin),end(end){
        curr = begin;
        next = new Product(args...);
    }
    explicit Product(InputIterator begin,InputIterator end):base(begin),end(end){
        curr=begin;
    }
    bool has_next(){
        if (!next){
            return curr+1!=end;
        }
        return next->has_next() || (curr+1)!=end;
    }
    Product& operator++(){
        if (!next){
            curr++;
            return *this;
        }
        if(!next->has_next()){
            curr++;
            next->reset();
            return *this;
        }
        ++(*next);
        return *this;
    }

    std::vector<base_value> operator*(){
        if(!next){
            return std::vector<base_value>({*curr});
        }
        std::vector<base_value> ans = *(*next);
        ans.insert(ans.begin(),*curr);
        return ans;
    }

};

main.cpp
#include<vector>
#include"itertools.h"
int main(){
    std::vector<int> a = {0,1,2,3},b = {4,5,6};
    auto q = Product(a.begin(),a.end(),b.begin(),b.end());

    auto w =  *q;
    for(auto i:w){
        std::cout<<i<<' ';
    }
    std::cout<<std::endl;
while(q.has_next()) {
    ++q;
     w = *q;
    for (auto i:w) {
        std::cout << i << ' ';
    }
    std::cout << std::endl;
}
}
    return 0;
}

error
In file included from main.cpp:4:
itertools.h:91:20: error: no matching constructor for initialization of 'Product<std::__1::__wrap_iter<int *>, std::__1::__wrap_iter<int *>, std::__1::__wrap_iter<int *>, std::__1::__wrap_iter<int *>, std::__1::__wrap_iter<int *> >'
        next = new Product(args...);
                   ^       ~~~~
main.cpp:11:14: note: in instantiation of member function 'Product<std::__1::__wrap_iter<int *>, std::__1::__wrap_iter<int *>, std::__1::__wrap_iter<int *>, std::__1::__wrap_iter<int *>, std::__1::__wrap_iter<int *> >::Product' requested here
    auto q = Product(a.begin(),a.end(),b.begin(),b.end(),b.begin(),b.end());
             ^
itertools.h:93:14: note: candidate constructor not viable: requires 2 arguments, but 4 were provided
    explicit Product(InputIterator begin,InputIterator end):base(begin),end(end){
             ^
itertools.h:89:14: note: candidate constructor not viable: requires 6 arguments, but 4 were provided
    explicit Product(InputIterator begin,InputIterator end,InputIterators... args) :base(begin),end(end){
             ^
itertools.h:81:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 4 were provided
class Product{
      ^
itertools.h:81:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 4 were provided
1 error generated.

A: Here's a workup of 1201ProgramAlarm's answer (reduced to a minimal reproducible example).  I couldn't find a way to deduce Product's template parameter.
#include <iostream>
#include <iterator>
#include <vector>

template <typename InputIterator>
class Product{
    InputIterator base, end,curr;
    Product* next = nullptr;

public:
    template <typename ... InputIterators>
    explicit Product (InputIterator begin, InputIterator end, InputIterators ... args) : base (begin), end (end){
        std::cout << "templated constructor\n";
        curr = begin;
        next = new Product (args...);
    }

    explicit Product (InputIterator begin, InputIterator end) : base (begin), end (end){
        std::cout << "untemplated constructor\n";
        curr=begin;
    }
};

int main(){
    std::vector<int> a = {0,1,2,3}, b = {4,5,6}, c = {7,8,9};
    auto q = Product <std::vector<int>::iterator> (a.begin (), a.end (), b.begin (), b.end (), c.begin (), c.end ());
}

Output:
templated constructor
templated constructor
untemplated constructor

Live demo

A: When you call new Product and pass it 6 iterators, your template class have 5 template parameters (the InputIterator, which is used by the first two parameters, and 4 other types in InputIterators).
In the constructor, you try to create a new Product but with two fewer parameters (4). The compiler finds constructors that take either 2 or 6 parameters (which it reports in the notes that go with the error). It cannot instantiate a 4 parameter constructor, because InputIterators... args is 4 (possibly different) types and needs 4 parameters.
One possible workaround would be to create a templated constructor that can essentially redefine what all the extra parameters are for.


text:
Q: Display won't follow sleep settings, uses disabled screensaver instead I've been on the Yosemite and noticed only as of just this morning that my screen was on with a screen saver running.
I have screen savers set to never start, and I have Display sleep set to 10 minutes under Energy Saver.  I went away from my computer again today and came back to find the display on again with the screen saver on again.  I realize I could have processes disrupting display sleep, but why would the screen saver come on if it's been told not to?
Is this some new Yosemite issue?  How might I fix it?

A: I noticed the same effect in full Yosemite installation: screensaver starts when the computer (macbook air) is put down to sleep. If we add to this the battery "eating" behaviour I observed as well. I have unchecked every item that can use power, icloud and handsoff included, but the system itself needs a lot more energy than Mavericks. The general picture of power management seems to be worse than ever.


text:
Q: How do I begin to use this Java library? Teaching myself Java, still very new. Last night I learned how to import this library into my project in Android Studio. But now I'm confused as to how to actually start using it.
I know that Java works with classes and that supposedly a library is just a collection of classes (and probably others things too...) that you can begin using once you import it. But the author of this library told me to just use this:
BackgroundMail bm = new BackgroundMail(context);
bm.setGmailUserName("sendername@gmail.com");
bm.setGmailPassword("sender_email_password");
bm.setMailTo("receiver@gmail.com");
bm.setFormSubject("Subject");
bm.setFormBody("Body");
bm.send();

But when I try to put that into another one of my classes, I get red errors all over the place. So then I tried to create a Java class within my app's files and I still got red errors. Could someone kindly help me, a total beginner, get started here? I'd like to use this library to send an email in the background of my app.
To import the library:
I followed this answer: https://stackoverflow.com/a/35369267/5241266 and used Approach 2.
MainActivity.Java: this is where I put the import code.
package moviehelper.moviesfree;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.creativityapps.gmailbackgroundlibrary.BackgroundMail;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

For now, I have not added the block of code that the author told me to use (see above).
The Gradle Console error:
I get the following error when doing Build -> Make Project:
error: package com.creativityapps.gmailbackgroundlibrary does not exist

import com.creativityapps.gmailbackgroundlibrary.BackgroundMail;

My project tree: I think there might be some problem with this structure. It looks like the library was added as its own project? Although I'm not sure.

A: If you don't want to use the JitPack approach as documented in the instructions, then look at the settings.gradle file in the Github example.
It includes both modules (app and the library).
Then, once that is setup, you can compile project(:libraryName) in the app/build.gradle file's dependencies section. Again, see the Github sample for the syntax.
With those two steps (plus one to download the library), it should be importable within the app code.

A: Assuming you followed along with the other steps on the readme, at the top of your code you need to tell the source file to import the classes:
import com.creativityapps.gmailbackgroundlibrary.BackgroundMail;

public class MainActivity extends AppCompatActivity {
    [your code]
}

I would also recommend looking through the sample code included in the github project

A: You are doing some wrong steps friend. You can follow this
Find your gradle file with name buid.gradle (Project: [ YOUR_PROJECT_NAME ] )
Then find and add this line
allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

You are done 50% now. Now press SHIFT+CTRL+ALT+S and wait for a window.
On the Window, select DEPENDENCY TAB on top.
Click on + BUTTON at top right. Click on Library Dependency.
Now paste com.github.yesidlazaro:GmailBackground:1.2.0 there.
Click on OK and exit the window. Gradle recompiles.
Now simply put your code, If RED syntax error showing, Click at the code where error is showing and when a BLUE pop comes, Press ALT+ENTER.
Everything done..!


text:
Q: Block one component getting CSS from another component angular6 I have a component named profile-data.component that uses Angular Material mat-tab-group component, i used this Angular Material component in tournament-list.component first.
Now my mat-tab-group inside profile-data.component is getting the css from the tournament-list.component is there any way to block this?
My folder structure looks like this.
app
  profile
    profile-data
      profile-data.component

   tournament
     tournament-list
       tournament-list.component

This is my profile-data.component.css
.acc-settings{
   border-radius: 25px;
   display:inline-block;
   font-size: 30px;
   background-color: blue;
   color:white;
   padding-left: 10px;
   padding-right: 10px;
 }
 .line {
   width: 100%;
   height: 0;
   border: 1px solid blue;
   display:inline-block;
  }
  .mat-tab-body-content{
    color: blue;
  }

And my tournament-list.component.css
.mat-tab-body-content{
  color:white;
  text-align: center;
}

And I am getting the color white instead of the blue

A: Use ViewEncapsulation - Scoping Your Styles in Angular With ViewEncapsulation When set to Native - This is the encapsulation mode that would be ideal and it uses the Shadow DOM to scope styles only to that specific component.
In your component decorator use this property as follows:
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.Native
})


text:
Q: Check string in an array I have strings stored in an array and need to check if the 5th character of each string is a number or not. The code I used is:
If Mid(arr(i), 5, 1) = IsNumeric(True) Then
      MsgBox("Number")
End If

It is giving an error:

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Boolean' is not valid.

A: You originally tagged your question as vba, but VBA doesn't throw System.InvalidCastException, or any other exception for that matter; vb.net does.
IsNumeric(True) returns True if True is numeric. You want to verify if the string retrieved from the array is numeric; give it the string retrieved from the array as a parameter:
If IsNumeric(Mid(arr(i), 4, 1)) Then
    MsgBox("Number")
End If

Your code reads like VB6/VBA though, because of this:
Imports Microsoft.VisualBasic

That namespace contains VB6-like things that you don't need to use at all. The beauty of .net is that everything is an object, so assuming the array is an array of String, you can call the actual String instance methods instead of VB6's Mid function.
Dim theFifthCharacter As String = arr(i).Substring(4, 1)

Or, because you're only interested in 1 character, and a String is itself an IEnumerable(Of Char), you can do this:
Dim theFifthCharacter As Char = arr(i)(4)

Notice the off-by-one - in .net indices start at 0, so if you want the 5th item you'll fetch index 4.
Now, if you want to see if it's numeric, you can try to parse it:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
    'numeric: digitValue contains the numeric value
Else
    'non-numeric: digitValue contains an Integer's default value (0)
End If

Lastly, if you want a message box, use WinForms' MessageBox instead of VB6's MsgBox:
Dim digitValue As Integer
If Int32.TryParse(theFifthCharacter, digitValue) Then
    'numeric: digitValue contains the numeric value
    MessageBox.Show(string.Format("Number: {0}", digitValue))
Else
    'non-numeric: digitValue contains an Integer's default value (0)
    MessageBox.Show("Not a number")
End If

A: A more correct way to do this would be:
If Char.IsDigit(arr(i)(4)) Then

A: Your syntax is incorrect. It should be:
If IsNumeric(Mid(arr(i), 5, 1)) Then


text:
Q: Discordjs : console log = length is undefnied I'm getting the error length is undefined
Code:
const Discord = require("discord.js")
const config = require("./config.json")
const bot = new Discord.Client();
const fs = require("fs");
bot.commands = new Discord.Collection();

fs.readdir("./commands/", (err, files) => {

  if (err) console.log(err);

  let jsfile = files.filter(f => f.split(".").pop() === "js");
  if (jsfile.length <= 0) {
    console.log("Je ne trouve pas les commandes");
    return;
  }

  jsfile.forEach((f, i) => {
    let props = require(`./commands/${f}`);
    console.log(`${f} chargée!`);

  });

  fs.readdir("./events/", (error, f) => {
    if (error) console.log(error);
    console.log(`${f.length} events en chargement`);
  })

A: fs.readdir is an async function which either returns error or list of files in directory. You need to check whether error was returned or files were found, and only proceed to process returned data if no error was returned. Read more nodejs fs. Try this
  fs.readdir("./events/", (error, f) => {
    if (error) {
       console.log(error);

    } else {
       // only check length if no errors
       // otgherwise f is null and we can not call f.length
       console.log(`${f.length} events en chargement`);
    }

  })


text:
Q: Open Shift remote Git repository reset or delete I am testing and triying to use openshift for first time ever,
and i did not realize the size limitation in space included git repository too.
Now my remote git repository is full, and i cannot do nothing with it.
Is there a way to remotely purge, or reset my git repository and start from scracth without having to delete the application?

A: If you just need the code without the history (the current source), you can do the following.

*

*Make a backup of the current git repo anywhere in case you need it someday.

*Delete the .git folder on your OpenShift

*Start a new repository with the git init and now work on a new repository.

Keep in mind that you have the old one as backup in case you need it someday.


text:
Q: Difference between LSI SAS3081E-R vs. LSI SAS3081E-S SAS/ATA HBAs I'm trying to figure out if there are any differences between the "R" vs. the "S" of this SAS controller. As far as I can tell, the "S" is a Sun Microsystems re-branded version. I can't find much solid documentation on the "S" version.
Most documentation that I find is on Oracle's documentation website, but mostly it's about setting up RAID on the HBA, not the specs themselves. I know Intel and (apparently) Sun re-brand the controller as their own but I'm curious to know if there are any minor/major differences that Sun may have made.
Thanks!

A: That's exactly the difference, nothing more or less, HP also rebranded the same controller too.


text:
Q: ID from tabs to form with javascript? Ok, so Im totally new to javascript, but I would need to do following:
on my page I have tabs (done with javascript) and then I have search form. Now I need from those tabs a id to put to that form.
I have tabs1 tabs2 tabs3 and all those href="#1", href="#2" and so on. I would need to get that number out of that tab to form input value. So if use clicks Tab2, it would automatically put "2" as a value in one of my inputs of my form. How to do that? Thanks!

A: Explaination in HTML comments:

Tab1
<form name="form_name" action="" method="post">

<input type="hidden" name="field_name" value="1" />

</form>


text:
Q: Laravel export is not working on server, But working fine on localhost following is the code which I used for export functionality
public function export(){
        $users = DB::table('users')->where('user_type','Farmer')->orWhere('user_type','Dealer')->select('id','name','middlename','surname','mobile','state','district','taluka','user_type')->get()->map(function ($item, $key){
            return (array) $item;
        })
        ->all();

        $usersArray = [];
        foreach ($users as $user) {
             $usersArray[] =$user;
        }

        Excel::create('users',function($excel)use($usersArray) {
            $excel->setTitle('users');
            $excel->setCreator('Laravel');
            $excel->setDescription('users file');
            $excel->sheet('sheet1',function($sheet)use($usersArray) {
            $sheet->fromArray($usersArray,null,'A1',true,true);
            });

        })->download('xlsx');
    }

This code is working fine on localhost,no issue at localhost, But on server it is showing error that "This site can't be reached", I am unable to figure it out that what is the issue on server.
I even try some other solutions on stackoverflow but unable to work.

A:      $users = DB::table('users')
               ->where('user_type','Farmer')
               ->orWhere('user_type','Dealer')
               ->select('id', 'name', 'middlename', 'surname', 'mobile', 'state', 'district', 'taluka','user_type')
               ->get()->map(function ($item, $key){
                    return (array) $item;
               })->all()->toArray();

After using ->toArray(), the variable $users variable will be an array
Now coming to your point,
Possibilites of Error
1) Folder permission to create a temp file
2) Allowed memory size exceeded, you can change the memory size to unlimited in php.ini file or in your code by setting ini_set('memory_limit','-1');
3) Give write permission to the storage directory of laravel setup in the server.
4) check the apache/nginx log for some other possibilities of error, as it is a 500 error response it should be logged into the log file of apache/nginx.
My suggestion is to use league/csv packages or box/spout packages with laravel Excel related works.

A: Just a hint, you don't have to make $usersArray by own, just use toArray() method after all().
Is there any message in your nginx/apache log?

A: PHPExcel ZipArchive not found after lot of trouble finally this solution is worked for me. I just append PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP); this line before $zipClass = PHPExcel_Settings::getZipClass(); In File PHPExcel/Reader/Excel2007.php, and Now my export function is running on server too.


text:
Q: Error (404) Importing a PBIX file (from blobstorage) into a PowerBI Group I am getting trying to upload >1gb pbix from blobstorage in A4 capacity backed workspace using PostImportInGroupAsync API call:
var inf = new Microsoft.PowerBI.Api.Models.ImportInfo()
                {
                    FileUrl = uploadUrl,
                };
var import = await client.Imports.PostImportInGroupAsync(new Guid("878be823-1928-474c-98d2-848ade1e4890"), "newmyreportdda", inf,ImportConflictHandlerMode.Overwrite);

but getting Bad request:
Microsoft.Rest.HttpOperationException: 'Operation returned an invalid status code 'BadRequest''

Microsoft.Rest.HttpOperationException   HResult=0x80131500
Message=Operation returned an invalid status code 'BadRequest' Source=Microsoft.PowerBI.Api

StackTrace:
at Microsoft.PowerBI.Api.ImportsOperations.<PostImportInGroupWithHttpMessagesAsync>d__25.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.PowerBI.Api.ImportsOperationsExtensions.<PostImportInGroupAsync>d__25.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at PowerBIAuth.Program.<Main>d__5.MoveNext()
in C:\Users\vz112ss\Downloads\PowerBIAuthNew\PowerBIAuth\PowerBIAuth\Program.cs:line 50

  This exception was originally thrown at this call stack:
    [External Code]
    PowerBIAuth.Program.Main(string[]) in Program.cs


text:
Q: Relating username table with another table in android studio using SQlite Databse I want to display a guest list inserted by the user under a specific user and so i want to know how do I relate the user ID to the guest ID.
I want to attach the user id to the guest id, please help me out.
Can you please help me out as to how to add a foreign key or a third table and how to relate it using a query.
My database code is listed below:
package com.mangal.myapplication.ui.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.mangal.myapplication.ui.Models.GuestModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {

    //User Login and Register columns
    public static final String DB_NAME ="event.db";
    public static final String TABLE_NAME="users";
    public static final String COL_ID="ID";

    // Guest Table columns
    private static final String TABLE_NAME_GUESTS="Guests";
    private static final String COL_GUESTS_ID="ID_GUESTS";
    private static final String COL_NAME_GUESTS="name";
    private static final String COL_STATUS_GUESTS="status";

    // SQL statement of the guests table creation
    private static final String SQL_CREATE_TABLE_GUESTS = "CREATE TABLE " + TABLE_NAME_GUESTS + "("
            + COL_GUESTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COL_NAME_GUESTS + " TEXT NOT NULL, "
            + COL_STATUS_GUESTS + " INTEGER NOT NULL, "

            +");";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table users(ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)");
        db.execSQL(SQL_CREATE_TABLE_GUESTS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists users");
        db.execSQL("drop table if exists " + TABLE_NAME_GUESTS);

        onCreate(db);

    }

    public boolean addUser(String username,String pwd){
        SQLiteDatabase db= this.getWritableDatabase();
        ContentValues contentValues= new ContentValues();
        contentValues.put("username",username);
        contentValues.put("password",pwd);
        long result= db.insert("users",null,contentValues);
        if (result==-1) return false;
        else return true;
    }

    public boolean inserttGuest(GuestModel model){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL_NAME_GUESTS , model.getGuest());
        values.put(COL_STATUS_GUESTS , 0);
        long res= db.insert(TABLE_NAME , null , values);
        if(res == -1){
            Log.d("not added","the guest was not added");
            return false;
        }else {
            Log.d("added", "the guest was added");
            return true;
        }
    }

    public void updateStatus(int id , int status){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL_STATUS_GUESTS , status);
        db.update(TABLE_NAME , values , "ID=?" , new String[]{String.valueOf(id)});
    }

    public List<GuestModel> getAllGuests(String User_name){

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = null;
        List<GuestModel> modelList=new ArrayList<>();

        try {
            cursor = db.query(TABLE_NAME , null , null , null , null , null , null);
            if (cursor !=null){
                if (cursor.moveToFirst()){
                    do {
                        GuestModel guest= new GuestModel();
                        guest.setId(cursor.getInt(cursor.getColumnIndex(COL_ID)));
                        guest.setGuest(cursor.getString(cursor.getColumnIndex(COL_NAME_GUESTS)));
                        guest.setStatus(cursor.getInt(cursor.getColumnIndex(COL_STATUS_GUESTS)));
                        modelList.add(task);

                    }while (cursor.moveToNext());
                }
            }
        }finally {
            cursor.close();
        }
        return modelList;
    }

}

A: since you never specified about how you want the relationship,here I am assuming you want to link the guest to a certain user id
first of all to have relationships based on foreign keys, you need to enable foreign keys on sqlite for every connection as by  default its currently disabled.
String enable_foreign_keys ="PRAGMA foreign_keys = ON";

secondly is how you create your tables .
Guest table change :

private static final String SQL_CREATE_TABLE_GUESTS = "CREATE TABLE "

*

*TABLE_NAME_GUESTS + "("
+ COL_GUESTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_NAME_GUESTS + " TEXT NOT NULL, "
+ COL_STATUS_GUESTS + " INTEGER NOT NULL, "+");";

to :
private static final String SQL_CREATE_TABLE_GUESTS = "CREATE TABLE " +TABLE_NAME_GUESTS + "("+ COL_GUESTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COL_NAME_GUESTS + " TEXT NOT NULL, "
            + COL_STATUS_GUESTS + " INTEGER NOT NULL, user_id INTEGER NOT NULL,FOREIGN KEY(user_id) REFERENCES users(ID));";

Meaning every time you insert a guest with user_id,UserID must exist in the users table
if you want to do a many to many relationship ,consider creating another table with columns user_id and guest.there, many users can be linked to one guest and vice verser.


text:
Q: Windows home premium I keep getting a java script alert popup box that says Hello new user that I must type OK to..  How can I stop it from appearing?  I have tried asking that it be illiminated but doen't help.

A: When you next get that pop up, hit CTRL+SHIFT+ESC.  After Task Manager Pops up, you should see the window under Applications or Processes.  Right-Click, and select Open File Location.  The folder will open up, and show you what the file is, and where it is located.
Just to be safe, I wouldn't just delete it outright.  It sounds like a test script, but some research would be best before doing so.  If you can post that screen shot, with the file name, that would help greatly.


text:
Q: Weblogic 403 exception I have installed oracle weblogic server 12c with eclipse bundled within it. I have created a simple application with index.html as a start page.
Whenever i tried to run the applucation, I got the following error.
Error 403--Forbidden
From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

my web.xml is like this,
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>org.test.ws</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

How can I fix it?


text:
Q: Function Declaration that removes keywords stored in an array from a string I have a function declaration that I need to use. Its purpose is to remove various keywords (that should not have been in the string) contained in an array from a string contained in the console.log.
This will make the string readable. Please Help, I'm currently learning.
By removing "not", "hello" from the string, this will give "If string includes words in array, remove them JavaScript".
function correctString(string, Keywords) {
    let spec1 = Keywords;
    let spec2 = spec1.pop();
    return string.replace(spec2, "");
}

console.log(correctString("If stringnot includes whelloords in array, remove them JavaScript", ["not", "hello"]));

I was able to remove the "hello" keyword from the string with the pop method. However, I cannot find a method that removes the other keyword "not" from the string... I tried to use different methods such as .filter, .splice, .slice.

A: Is this what you're trying to accomplish? See this MDN document and especially the statement in the first paragraph that "The original string is left unchanged." You may also be interested in replaceAll().

function correctString(text, Keywords) {
    Keywords.forEach( v => {
      console.log(v + ": " + text.indexOf(v));
      text = text.replace(v,"");
      console.log(text);
      });
    return text;
}

console.log(correctString("If stringnot includes whelloords in array, remove them JavaScript", ["not", "hello"]));


text:
Q: Can I use a persons web behaviour to affect journey builder Can I use the web behaviour of a known user to impact on journey builder in Marketing Cloud (I assume I need some tracking code installed??).
some use cases would be:

*

*We've sent a user an email.  If within 3 days they've not visited
page  then send them a reminder.  If they've visited page
then send them info about page

*A known user has visited page .  Send an email two days later
with some related information.

If the answers to the above are yes - then how :)
Cheers
Jo

A: You need to configure your journey for use case 1 as follows:

*

*Create entry source(suitable to your scenario. It might be a data
extension or Audience or whatever), followed by your email.

*Put a wait activity for 3 days.

*Use an engagement split with 'message metrics' as 'Clicks' and on true path
configure your email with info about the link and on false path send reminder.

Please clarify how do you mark your user as know user. Are you calling one who has already clicked on the link as your know user. And is this user visiting your page(I am assuming Landing Page) by again clicking on the link provided in your email or how else. Please provide more details.


text:
Q: I have three font type -Gotham-bold, Gotham-medium, Gotham-thin, so do I need to use three times @font-face? Actually I have three files in the fonts folder. These are Gotham-Bold.ttf, Gotham-Medium.ttf, Gotham-Thin.ttf..... So do I need to use the @font-face three times for those three types. Please anybody help me.
I have currently used the code like the following:
    @font-face {
    font-family: 'Gotham';
    src: url('fonts/Gotham-Bold.eot'); /* IE9 Compat Modes */
    src: url('fonts/Gotham-Bold.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('fonts/Gotham-Bold.woff') format('woff'), /* Modern Browsers */
         url('fonts/Gotham-Bold.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('fonts/Gotham-Bold.svg#svgFontName') format('svg'); /* Legacy iOS */
     font-weight: normal;
     font-style: normal;
     }

     @font-face {
      font-family: 'Gotham';
      src: url("/fonts/Gotham-Bold.eot");
     }
    @font-face {
      font-family: 'Gotham';
      src: url("/fonts/Gotham-Bold.woff") format("woff");
    }

Thanks.

A: That is correct, you'll need an @font-face for each weight of the font you want to use.
@font-face {
  font-family: 'Gotham';
  src: url('fonts/Gotham-Bold.eot'); /* IE9 Compat Modes */
  src: url('fonts/Gotham-Bold.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
     url('fonts/Gotham-Bold.woff') format('woff'), /* Modern Browsers */
     url('fonts/Gotham-Bold.ttf')  format('truetype'), /* Safari, Android, iOS */
     url('fonts/Gotham-Bold.svg#svgFontName') format('svg'); /* Legacy iOS */
   font-weight: 700;
   font-style: normal;
 }

@font-face {
  font-family: 'Gotham';
  src: url('fonts/Gotham-Medium.eot'); /* IE9 Compat Modes */
  src: url('fonts/Gotham-Medium.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
     url('fonts/Gotham-Medium.woff') format('woff'), /* Modern Browsers */
     url('fonts/Gotham-Medium.ttf')  format('truetype'), /* Safari, Android, iOS */
     url('fonts/Gotham-Medium.svg#svgFontName') format('svg'); /* Legacy iOS */
   font-weight: 400;
   font-style: normal;
 }

@font-face {
  font-family: 'Gotham';
  src: url('fonts/Gotham-Thin.eot'); /* IE9 Compat Modes */
  src: url('fonts/Gotham-Thin.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
     url('fonts/Gotham-Thin.woff') format('woff'), /* Modern Browsers */
     url('fonts/Gotham-Thin.ttf')  format('truetype'), /* Safari, Android, iOS */
     url('fonts/Gotham-Thin.svg#svgFontName') format('svg'); /* Legacy iOS */
   font-weight: 300;
   font-style: normal;
 }

Then you can use your fonts as so:
body {
   font-family: 'Gotham';
}

// For normal
.normal {
  font-weight: 400;
}

// For bold
.bold,
strong {
  font-weight: 700;
}

// For thin
.light {
  font-weight: 300;
}

A: Yes, you need to declare each font-type as a separate @fontface. Each would be a different font-family in that case.
Like so:
@font-face {
  font-family: 'GothamThin';
  /* links to all gotham thin files, font-weight/style declaration */
}
@font-face {
  font-family: 'GothamMedium';
  /* links to all gotham medium files, font-weight/style declaration */
}
@font-face {
  font-family: 'GothamBold';
  /* links to all gotham bold files, font-weight/style declaration */
}

Only include the fonts you are using, though.. if you don't use Gotham Thin anywhere on the page, don't include it (for speed).


text:
Q: Saving SSIS package to local machine Right now I'm able to upload an SSIS package from my local computer to SQL Server with my C# program:
Microsoft.SqlServer.Dts.Runtime.Application app;
app = new Microsoft.SqlServer.Dts.Runtime.Application();

string pkg = @"C:\Temp\myPackage.dtsx";
Package loadedPkg = app.LoadPackage(pkg, null);

app.SaveToSqlServerAs(loadedPkg, null, "myNewPackage", "myServer", null, null);

This works great. Now I want to do the opposite of this, save an SSIS package from the SQL Server to my local computer. I'm using the Microsoft documentation here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.dts.runtime.application?view=sqlserver-2017
It doesn't seem to have any methods to save to a computer. I see the "load" methods, but I haven't been able to get those to work. I think they just prep a package to be uploaded to the server, like in my previous example. Is this possible through the same "Application" class?
edit: For anyone reading this in the future: the "pkgIn" path from @Hadi's answer already has "MSDB" built into the path, so if you need "\MSDB\packages" or whatever, just use "\packages"

A: You have to use SaveToXml() Function to achieve that.
app.SaveToXml("C:\Temp\myNewPackage.dtsx", pkg, null);

You can refer to this link:

*

*Application.SaveToXml(String, Package, IDTSEvents) Method

Update 1
Try using a similar code:
Package pkgIn = new Package();
pkgIn = app.LoadFromSqlServer("\\myNewPackage", "yourserver", null, null, null);
app.SaveToXml("C:\Temp\myNewPackage.dtsx", pkgIn , null);

You can refer to this link for more information about loading package from SQL Server:

*

*Application.LoadFromSqlServer(String, String, String, String, IDTSEvents) Method


text:
Q: point inside a polygon with edges parallel to the axes I've solved Polygon problem problem at interviewstreet, but it seems too slow. What is the best solution to the problem?
There are N points on X-Y plane with integer coordinates (xi, yi). You are given a set of polygons with all of its edges parallel to the axes (in other words, all angles of the polygons are 90 degree angles and all lines are in the cardinal directions. There are no diagonals). For each polygon your program should find the number of points lying inside it (A point located on the border of polygon is also considered to be inside the polygon).
Input:
First line two integers N and Q. Next line contains N space separated integer coordinates (xi,yi). Q queries follow. Each query consists of a single integer Mi in the first line, followed by Mi space separated integer coordinates (x[i][j],y[i][j]) specifying the boundary of the query polygon in clock-wise order.
Polygon is an alternating sequence of vertical line segments and horizontal line segments.
    Polygon has Mi edges, where (x[i][j],y[i][j]) is connected to (x[i][(j+1)%Mi], y[i][(j+1)%Mi].
    For each 0 <= j < Mi, either x[i][(j+1)%Mi] == x[i][j] or y[i][(j+1)%Mi] == y[i][j] but not both.
    It is also guaranteed that the polygon is not self-intersecting.
Output:
For each query output the number of points inside the query polygon in a separate line.
Sample Input #1:
16 2
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
3 0
3 1
3 2
3 3
8
0 0
0 1
1 1
1 2
0 2
0 3
3 3
3 0
4
0 0
0 1
1 1
1 0

Sample Output #1:
16
4

Sample Input #2:
6 1
1 1
3 3
3 5
5 2
6 3
7 4
10
1 3
1 6
4 6
4 3
6 3
6 1
4 1
4 2
3 2
3 3

Sample Output #2:
4

Constraints:
1 <= N <= 20,000
1 <= Q <= 20,000
4 <= Mi <= 20
Each co-ordinate would have a value of atmost 200,000
I am interested in solutions in mentioned languages or pseudo code.
EDIT: here is my code but it's O(n^2)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Polygon
{
// avoding System.Drawing dependency
public struct Point
{
    public int X { get; private set; }
    public int Y { get; private set; }

    public Point(int x, int y)
        : this()
    {
        X = x;
        Y = y;
    }

    public override int GetHashCode()
    {
        return X ^ Y;
    }

    public override bool Equals(Object obj)
    {
        return obj is Point && this == (Point)obj;
    }

    public static bool operator ==(Point a, Point b)
    {
        return a.X == b.X && a.Y == b.Y;
    }

    public static bool operator !=(Point a, Point b)
    {
        return !(a == b);
    }
}

public class Solution
{
    static void Main(string[] args)
    {
        BasicTestCase();
        CustomTestCase();
        // to read from STDIN
        //string firstParamsLine = Console.ReadLine();
        //var separator = new char[] { ' ' };
        //var firstParams = firstParamsLine.Split(separator);
        //int N = int.Parse(firstParams[0]);
        //int Q = int.Parse(firstParams[1]);

        //List<Point> points = new List<Point>(N);

        //for (int i = 0; i < N; i++)
        //{
        //    var coordinates = Console.ReadLine().Split(separator);
        //    points.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
        //}

        //var polygons = new List<List<Point>>(Q); // to reduce realocation
        //for (int i = 0; i < Q; i++)
        //{

        //    var firstQ = Console.ReadLine().Split(separator);
        //    int coordinatesLength = int.Parse(firstQ[0]);
        //    var polygon = new List<Point>(coordinatesLength);
        //    for (int j = 0; j < coordinatesLength; j++)
        //    {
        //        var coordinates = Console.ReadLine().Split(separator);
        //        polygon.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
        //    }
        //    polygons.Add(polygon);
        //}

        //foreach (var polygon in polygons)
        //{
        //    Console.WriteLine(CountPointsInPolygon(points, polygon));
        //}

    }

    private static void BasicTestCase()
    {
        List<Point> points = new List<Point>(){ new Point(0, 0),
                                                new Point(0, 1),
                                                new Point(0, 2),
                                                new Point(0, 3),
                                                new Point(1, 0),
                                                new Point(1, 1),
                                                new Point(1, 2),
                                                new Point(1, 3),
                                                new Point(2, 0),
                                                new Point(2, 1),
                                                new Point(2, 2),
                                                new Point(2, 3),
                                                new Point(3, 0),
                                                new Point(3, 1),
                                                new Point(3, 2),
                                                new Point(3, 3) };

        List<Point> polygon1 = new List<Point>(){   new Point(0, 0),
                                                    new Point(0, 1),
                                                    new Point(2, 1),
                                                    new Point(2, 2),
                                                    new Point(0, 2),
                                                    new Point(0, 3),
                                                    new Point(3, 3),
                                                    new Point(3, 0)};

        List<Point> polygon2 = new List<Point>(){   new Point(0, 0),
                                                    new Point(0, 1),
                                                    new Point(1, 1),
                                                    new Point(1, 0),};

        Console.WriteLine(CountPointsInPolygon(points, polygon1));
        Console.WriteLine(CountPointsInPolygon(points, polygon2));

        List<Point> points2 = new List<Point>(){new Point(1, 1),
                                                new Point(3, 3),
                                                new Point(3, 5),
                                                new Point(5, 2),
                                                new Point(6, 3),
                                                new Point(7, 4),};

        List<Point> polygon3 = new List<Point>(){   new Point(1, 3),
                                                    new Point(1, 6),
                                                    new Point(4, 6),
                                                    new Point(4, 3),
                                                    new Point(6, 3),

                                                    new Point(6, 1),
                                                    new Point(4, 1),
                                                    new Point(4, 2),
                                                    new Point(3, 2),
                                                    new Point(3, 3),};

        Console.WriteLine(CountPointsInPolygon(points2, polygon3));
    }

    private static void CustomTestCase()
    {
        // generated 20 000 points and polygons
        using (StreamReader file = new StreamReader(@"in3.txt"))
        {
            string firstParamsLine = file.ReadLine();
            var separator = new char[] { ' ' };
            var firstParams = firstParamsLine.Split(separator);
            int N = int.Parse(firstParams[0]);
            int Q = int.Parse(firstParams[1]);

            List<Point> pointsFromFile = new List<Point>(N);

            for (int i = 0; i < N; i++)
            {
                var coordinates = file.ReadLine().Split(separator);
                pointsFromFile.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
            }

            var polygons = new List<List<Point>>(Q); // to reduce realocation
            for (int i = 0; i < Q; i++)
            {

                var firstQ = file.ReadLine().Split(separator);
                int coordinatesLength = int.Parse(firstQ[0]);
                var polygon = new List<Point>(coordinatesLength);
                for (int j = 0; j < coordinatesLength; j++)
                {
                    var coordinates = file.ReadLine().Split(separator);
                    polygon.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
                }
                polygons.Add(polygon);
            }

            foreach (var polygon in polygons)
            {
                Console.WriteLine(CountPointsInPolygon(pointsFromFile, polygon));
            }

        }
    }

    public static int CountPointsInPolygon(List<Point> points, List<Point> polygon)
    {
        // TODO input check
        polygon.Add(polygon[0]); // for simlicity
        // check if any point is outside of the bounding box of the polygon
        var minXpolygon = polygon.Min(p => p.X);
        var maxXpolygon = polygon.Max(p => p.X);
        var minYpolygon = polygon.Min(p => p.Y);
        var maxYpolygon = polygon.Max(p => p.Y);
        // ray casting algorithm (form max X moving to point)
        int insidePolygon = 0;
        foreach (var point in points)
        {
            if (point.X >= minXpolygon && point.X <= maxXpolygon && point.Y >= minYpolygon && point.Y <= maxYpolygon)
            {       // now points are inside the bounding box
                    isPointsInside(polygon, point, ref insidePolygon);
            } // else outside
        }
        return insidePolygon;

    }
    private static void isPointsInside(List<Point> polygon, Point point, ref int insidePolygon)
    {
        int intersections = 0;

        for (int i = 0; i < polygon.Count - 1; i++)
        {
            if (polygon[i] == point)
            {
                insidePolygon++;
                return;
            }
            if (point.isOnEdge(polygon[i], polygon[i + 1]))
            {
                insidePolygon++;
                return;
            }
            if (Helper.areIntersecting(polygon[i], polygon[i + 1], point))
            {
                intersections++;
            }
        }

        if (intersections % 2 != 0)
        {
            insidePolygon++;
        }
    }
}

static class Helper
{
    public static bool isOnEdge(this Point point, Point first, Point next)
    {
            // onVertical
            if (point.X == first.X && point.X == next.X && point.Y.InRange(first.Y, next.Y))
            {
                return true;
            }
            //onHorizontal
            if (point.Y == first.Y && point.Y == next.Y && point.X.InRange(first.X, next.X))
            {
                return true;
            }
            return false;
    }

    public static bool InRange(this int value, int first, int second)
    {
        if (first <= second)
        {
            return value >= first && value <= second;
        }
        else
        {
            return value >= second && value <= first;
        }
    }

    public static bool areIntersecting(Point polygonPoint1, Point polygonPoint2, Point vector2End)
    {
        // "move" ray up for 0.5 to avoid problem with parallel edges
        if (vector2End.X < polygonPoint1.X )
        {
            var y = (vector2End.Y + 0.5);
            var first = polygonPoint1.Y;
            var second = polygonPoint2.Y;
            if (first <= second)
            {
                return y >= first && y <= second;
            }
            else
            {
                return y >= second && y <= first;
            }
        }
        return false;
    }
}

}

A: A faster solution is to place the points into a quadtree.
A region quadtree might be easier to code, but a point quadtree is probably faster.  If using a region quadtree then it can help to stop subdividing the quadtree when the number of points in a quad falls below a threshold (say 16 points)
Each quad stores the number of points it contains, plus either a list of coordinates (for leaf nodes) or pointers to smaller quads.  (You can omit the list of coordinates when the size of the quad reaches 1 as they must all be coincident)
To count the points inside the polygon you look at the largest quad that represents the root of the quadtree.

*

*Clip the polygon to the edges of the quad

*If the polygon does not overlap the quad then return 0

*If this is a quad of size 1x1 then return the number of points in the quad

*If the polygon totally encircles the quad then return the number of points in the quad.

*If this is a leaf node then test each point with the plumb line algorithm

*Otherwise recursively count the points in each child quad

(If a quad only has one non-empty child then you can skip steps 1,2,3,4,5 to go a little faster)
(The tests in 2 and 4 do not have to be totally accurate)

A: I would try casting a ray up from the bottom to each point, tracking where it crossed into the polygon (passing a right-to-left segment) or back out of the polygon (passing a left-to-right segment). Something like this:
count := 0
For each point (px, py):
   inside := false
   For each query line (x0, y0) -> (x1, y1) where y0 = y1
      if inside
         if x0 <= px < x1 and py > y0
            inside = false
      else
         if x1 <= px <= x0 and py >= y0
            inside = true
   if inside
      count++

The > vs. >= in the two cases is so that a point on the upper edge is considered inside. I haven't actually coded this up to see if it works, but I think the approach is sound.

A: Does trapezoidal decomposition work for you?

A: I refer you to Jordan Curve Theorem and the Plumb Line Algorithm.
The relevant pseudocode is
int crossings = 0
for (each line segment of the polygon)
    if (ray down from (x,y) crosses segment)
        crossings++;
if (crossings is odd)
    return (inside);
else return (outside);

A: Here is the solution from authors - a bit obfuscated, isn't it?
#include <iostream>
#include <ctime>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;

typedef long long int64;
const int N = 100000, X = 2000000001;
const int Q = 100000, PQ = 20;
struct Point {
    int x, y, idx;
    Point(int _x = 0, int _y = 0, int _idx = 0) {
        x = _x;
        y = _y;
        idx = _idx;
    }
} arr_x[N], arr_y[N];
struct VLineSegment {
    int x, y1, y2, idx, sign;
    VLineSegment(int _x = 0, int _y1 = 0, int _y2 = 0, int _sign = 1, int _idx = 0) {
        x = _x;
        y1 = _y1;
        y2 = _y2;
        sign = _sign;
        idx = _idx;
    }
    bool operator<(const VLineSegment& v) const {
        return x < v.x;
    }
} segs[Q * PQ];

struct TreeNode {
    int idx1, idx2, cnt;
    TreeNode *left, *right;
    TreeNode() { left = right = 0; cnt = 0; }
    ~TreeNode() { if(left) delete left; if(right) delete right; }

    void update_stat() {
        cnt = left->cnt + right->cnt;
    }

    void build(Point* arr, int from, int to, bool empty) {
        idx1 = from;
        idx2 = to;
        if(from == to) {
            if(!empty) {
                cnt = 1;
            } else {
                cnt = 0;
            }
        } else {
            left = new TreeNode();
            right = new TreeNode();
            int mid = (from + to) / 2;
            left->build(arr, from, mid, empty);
            right->build(arr, mid + 1, to, empty);
            update_stat();
        }
    }
    void update(Point& p, bool add) {
        if(p.idx >= idx1 && p.idx <= idx2) {
            if(idx1 != idx2) {
                left->update(p, add);
                right->update(p, add);
                update_stat();
            } else {
                if(add) {
                    cnt = 1;
                } else {
                    cnt = 0;
                }
            }
        }
    }
    int query(int ya, int yb) {
        int y1 = arr_y[idx1].y, y2 = arr_y[idx2].y;
        if(ya <= y1 && y2 <= yb) {
            return cnt;
        } else if(max(ya, y1) <= min(yb, y2)) {
            return left->query(ya, yb) + right->query(ya, yb);
        }
        return 0;
    }
};

bool cmp_x(const Point& a, const Point& b) {
    return a.x < b.x;
}
bool cmp_y(const Point& a, const Point& b) {
    return a.y < b.y;
}

void calc_ys(int x1, int y1, int x2, int y2, int x3, int sign, int& ya, int& yb) {
    if(x2 < x3) {
        yb = 2 * y2 - sign;
    } else {
        yb = 2 * y2 + sign;
    }
    if(x2 < x1) {
        ya = 2 * y1 + sign;
    } else {
        ya = 2 * y1 - sign;
    }
}

bool process_polygon(int* x, int* y, int cnt, int &idx, int i) {
    for(int j = 0; j < cnt; j ++) {
        //cerr << x[(j + 1) % cnt] - x[j] << "," << y[(j + 1) % cnt] - y[j] << endl;
        if(x[j] == x[(j + 1) % cnt]) {
            int _x, y1, y2, sign;
            if(y[j] < y[(j + 1) % cnt]) {
                _x = x[j] * 2 - 1;
                sign = -1;
                calc_ys(x[(j + cnt - 1) % cnt], y[j], x[j], y[(j + 1) % cnt], x[(j + 2) % cnt], sign, y1, y2);
            } else {
                _x = x[j] * 2 + 1;
                sign = 1;
                calc_ys(x[(j + 2) % cnt], y[(j + 2) % cnt], x[j], y[j], x[(j + cnt - 1) % cnt], sign, y1, y2);
            }
            segs[idx++] = VLineSegment(_x, y1, y2, sign, i);
        }
    }
}
int results[Q];

int n, q, c;

int main() {
    int cl = clock();
    cin >> n >> q;
    for(int i = 0; i < n; i ++) {
        cin >> arr_y[i].x >> arr_y[i].y;
        arr_y[i].x *= 2;
        arr_y[i].y *= 2;
    }
    int idx = 0, cnt, x[PQ], y[PQ];
    for(int i = 0; i < q; i ++) {
        cin >> cnt;
        for(int j = 0; j < cnt; j ++) cin >> x[j] >> y[j];
        process_polygon(x, y, cnt, idx, i);
    }
    sort(segs, segs + idx);
    memset(results, 0, sizeof results);
    sort(arr_y, arr_y + n, cmp_y);
    for(int i = 0; i < n; i ++) {
        arr_y[i].idx = i;
        arr_x[i] = arr_y[i];
    }
    sort(arr_x, arr_x + n, cmp_x);
    TreeNode tleft;
    tleft.build(arr_y, 0, n - 1, true);
    for(int i = 0, j = 0; i < idx; i ++) {
        for(; j < n && arr_x[j].x <= segs[i].x; j ++) {
            tleft.update(arr_x[j], true);
        }
        int qcnt = tleft.query(segs[i].y1, segs[i].y2);
        //cerr << segs[i].x * 0.5 << ", " << segs[i].y1 * 0.5 << ", " << segs[i].y2 * 0.5 << " = " << qcnt << " * " << segs[i].sign << endl;
        results[segs[i].idx] += qcnt * segs[i].sign;
    }
    for(int i = 0; i < q; i ++) {
        cout << results[i] << endl;
    }
    cerr << (clock() - cl) * 0.001 << endl;
    return 0;
}