text:
Q: continious output streaminsight Is it possible to get a continuous output stream With streaminsight? My problem is that when I make a query on the inputstream with a hopping/tumbling window, the query doesnt give me any output when there are no input events. This sounds normal but is it possible to get a window mechanism that gives me output every 5 seconds also when there are no input events?
this is my code maybe the problem becomes clear after this:
var inputStream = CepStream<ServiceBusMessage>.Create("Inputstream Portal Orders");

// Counts the number of messages in a window of 5 seconds
var countStream = from w in inputStream.TumblingWindow(outputConfig.windowSize)
                  select w.Count();

var queryTemplate = app.CreateQueryTemplate("Count Window Portal Orders", "des...", countStream);

var queryBinder = new QueryBinder(queryTemplate);
queryBinder.BindProducer<ServiceBusMessage>("Inputstream Portal Orders", inputAdapter, config, EventShape.Point);

// Just an simple outputadapter
queryBinder.AddConsumer<long>("output", outputAdapter, outputConfig, EventShape.Point, StreamEventOrder.ChainOrdered);

var query = app.CreateQuery("Counter portal orders", "des...", queryBinder);

query.Start();

The output that I want for let say this input:
example input
input time 1: x
input time 2: x
input time 6: x
input time 16: x

expecting output:
2 events in last 5 seconds
1 events in last 5 seconds
0 events in last 5 seconds
1 events in last 5 seconds

Hope this window mechanism is possible within streaminsight, I googled for a lot of things read the developers guide but noting that handles contentious output or something similar.
Hope someone can help me!

A: There are no windowing mechanisms that have the behavior you are wanting.
How are you using the output? There might be another way to tackle the problem.


text:
Q: Surrogate pair that does not start in D800–DBFF I am parsing a docx file (in Java) and it has a 32-bit Chinese character using the values F0, A0, 9C, 8E. But the unicode spec says that the high surrogate value needs to be in the range D800–DBFF.
What/why/how is the first value allowed to be F0A0?
And Java converts this to E2, 96, AB, E2, 96, AB somehow. Any idea what's going on with that?
Update:
Ok, this is in the document.xml (in the docx file) which is set to UTF-8. I'm reading it using dom4j. So the issue could well be how it is reading it into a String or writing it back out.
How should this be represented in the String object?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Injecting javascript into page via url I'm trying to run a javascript code via url to change values of the form in the page.
Here is the content of the HTML page.

<form method='post'>
Name: <input type='text' id='name' value='' />

Family: <input type='text' id='family' value='' />

Email: <input type='text' id='email' value='' />

<input type='submit' value='Submit' />

</form>

Now, I enter the following value in the URL section of chrome:
javascript:document.getElementById('name').value = 'string1';

What happens is my whole page will go blank and only the value "string1" will be displayed in the page.
However, running the following code works properly:
javascript:document.getElementById('name').value = 1;

It will change the value of the name field to 1.
I'm wondering what is causing this problem.
Note: The purpose of this work is to inject code into webview in android.
Any advice is appreciated.

A: Try this.
javascript:document.getElementById('name').value = 'string1'; undefined;

Tack on a 'undefined;' to any script that returns a string.

A: That is because you are using single quotes after the attribute value
value=''

and you changing it's value in javascript using
document.getElementById('name').value='string1';

so the html becomes
<input type='text' id='name' value=''string1''

you can fix it using
value=""

or using
document.getElementById('name').value="string1";

A: well i tried the following code

<form method='post'>
Name: <input type='text' id='name' value='' />

Family: <input type='text' id='family' value='' />

Email: <input type='text' id='email' value='' />

<input type='submit' value='Submit' />

</form>
<button onclick="change()">Click me</button>

and it works just fine the problem is in your script
do you created a function to change the value or just putted the code in a script tag like this


text:
Q: What is the "right" Way to Provide a Zend Application With a Database Handler Assuming you're hewing closely to the conventions of a ZendApplication, where should you be setting up a database handler for application developers to access?
I know how to setup a ZendDb adapter.  What I want to know is, in the context of the Zend Framework, how should developers be instantiating their DB handlers so they don't have to worry about multiple instantiations across one request, supplying credentials each time, etc.
For example, when a developer is using Code Igniter and needs to run an arbitrary query, there's a database handler on the controller.
$this->db->query(....

What's the Zend equivalent of this convention?  To be clear, I can think of half a dozen way to accomplish this using the tools that the Zend Framework provides.  What I'm looking for is how Zend Framework, in the general case, wants you to do this.

A: The idea is that your Bootstrap reads a config file and you declare config entries to describe the database adapter you want to create:
[bootstrap]
resources.db.adapter = Pdo_Mysql
resources.db.params.dbname = "mydatabase"
resources.db.params.username = "webuser"
resources.db.params.password = "XXXX"
resources.db.isDefaultTableAdapter = true

If you use the config keys following the right convention, this automatically signals the Bootstrap base class to create and initialize a Zend_Application_Resource_Db object, and stores it in the bootstrap resource registry.
Later in your Controller, you can access the resource registry.
note: I've edited this code after testing it a bit more.
class SomeController extends Zend_Controller_Action
{
    public function init()
    {
        $bootstrap = $this->getInvokeArg("bootstrap");
        if ($bootstrap->hasPluginResource("db")) {
            $dbResource = $bootstrap->getPluginResource("db");
            $db = $dbResource->getDbAdapter();
        }
    }
}

Alternatively, you can write a custom init method in your Bootstrap class, to save an object in the default Zend_Registry:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
  protected function _initDb()
  {
    if ($this->hasPluginResource("db")) {
      $dbResource = $this->getPluginResource("db");
      $db = $dbResource->getDbAdapter();
      Zend_Registry::set("db", $db);
    }
  }
}

Now you can access your db object in one step instead of three:
class SomeController extends Zend_Controller_Action
{
    public function init()
    {
        $db = Zend_Registry::get("db");
    }
}

Personally, I would use the second technique, because then I have to access the resource registry only once, in my bootstrap.  In the first example I would have to copy the same block of code to all of my Controllers.


text:
Q: Find the minimum distance between the curves $y^2-xy-2x^2 =0$ and $y^2=x-2$ How to find the minimum distance between the curves $y^2-xy-2x^2 =0$ and $y^2=x-2$
Let $y^2-xy-2x^2 =0...(1)$ and $y^2=x-2...(2)$
In equation (1) coefficient of $x^2 =-2; y^2=1, 2xy =\frac{-1}{2}$
We know that a second degree equation where $ab-h^2 =0 $  represent a parabola,
$ab-h^2>1$ represent an ellipse
$ab-h^2 <0$ represent a hyperbola
Here $ab-h^2 <0$ therefore equation (1) represents hyperbola and equation (2) is parabola. ( where a,b, h are coefficients of $x^2,y^2,xy$ respectively.
Now how to get the minimum distance between the two curves please suggest .. thanks.

A: $$y^2= 2x^2+xy \iff (y-2x)(x+y)=0 \iff y = -x \text{ or } y = 2x$$
so that is a couple of lines.
Hence you want to find the shortest distance from $y=-x$ or $y=2x$ to the parabola $y^2=x-2$.  Let this be denoted by the line segment with end points $(a, -a)$ or $(a, 2a)$  and $(b^2+2, b)$.
Then we need the min of $(a-b^2-2)^2+(a+b)^2$ or $(a-b^2-2)^2+(2a-b)^2$.
Case 1:
We have by Cauchy Schwarz
$$((a-b^2-2)^2+(a+b)^2)((-1)^2+1^2) \ge (-a+b^2+2+a+b)^2= ((b+\tfrac12)^2+\tfrac74)^2 \ge \frac{7^2}{4^2}$$
so we get a minimum distance of $\frac{7}{4\sqrt2}$.
Case 2:
We have again by Cauchy Schwarz
$$((a-b^2-2)^2+(2a-b)^2)((-2)^2+1^2) \ge (-2a+2b^2+4+2a-b)^2= (2(b-\tfrac14)^2+\tfrac{31}8)^2 \ge \frac{31^2}{8^2}$$
so we get a minimum distance of $\frac{31}{8\sqrt5}$.
As the second case happens to be higher, the shortest distance is $\dfrac7{4\sqrt2}$.

A: Let
$$
f(x,y) = y^2-xy-2x^2\\
g(x,y) = y^2-x+2.
$$
The segment of minimum distance has the direction of the normal line to both the conics. The normal line has the direction of the gradient. Hence you could try to solve the following system:
$$
\begin{cases}
\nabla f((x,y) + \lambda \nabla g(x,y)) = \mu\nabla g(x,y)\\
f((x,y)+\lambda\nabla g(x,y)) = 0\\
g(x,y) = 0
\end{cases}
$$
where
$$
\nabla f(x,y) = (-y-4x, 2y-x)\\
\nabla g(x,y) = (-1,2y)
$$

A: When the shortest distance is achieved, the normal to the two curves coincide.
We are lucky that the first curve degenerates in $x+y=0$ and $2x-y=0$, giving two normal directions $(1,1)$ and $(2,-1)$.
Then, taking the gradient of the second expression, we express parallelism:
$$(-1,2y)\times(1,1)=-1-2y=0,$$
$$y=-\frac12,x=\frac94,$$
and compute the distance to the line
$$d=\frac{|\frac94-\frac12|}{\sqrt2}=\frac7{4\sqrt2}.$$ Similarly,
$$(-1,2y)\times(2,-1)=1-4y=0,$$
$$y=\frac14,x=\frac{33}{16},$$
$$d=\frac{|2\frac{33}{16}-\frac14|}{\sqrt5}=\frac{31}{8\sqrt5}.$$
Finally,
$$\sqrt\frac{49}{32}<\sqrt{\frac{961}{320}}.$$

A: $y^2-xy-2x^2=0$, factorize it we get $(y-2x)(y+x)=0$, so the graph is two straight line $-2x+y=0$ or $x+y=0$.
Points on $y^2=x-2$ can be written as $(t^2+2,t)$, the distance from $(t^2+2,t)$ to $-2x+y=0$ is $\frac{|-2(t^2+2)+t|}{\sqrt{(-2)^2+1^2}}= \frac{|2t^2-t+4|}{\sqrt{5}}=\frac{|2(t-1/4)^2+31/8|}{\sqrt{5}}$.
The distance from $(t^2+2,t)$ to $x+y=0$ is $\frac{|t^2+2+t|}{\sqrt{(1)^2+1^2}}= \frac{|(t+1/2)^2+7/4|}{\sqrt{2}}$.
$\frac{7}{4\sqrt2}<\frac{31}{8\sqrt5}$ so $\frac{7}{4\sqrt2}=\frac{7\sqrt{2}}{8}$ is minimum distance.

A: The first conic is two straight lines, of which the one which is closest to the parabola is the line $x+y=0$.
So you just need to find the point P on the parabola where the gradient is $-1$, and find the point where the normal at P meets this line.


text:
Q: Exercise 1.8.13 in Grimmett & Stirzaker's 'Probability and Random Processes' The question asks to prove Waring's theorem shown below:
$P(N_k)=\sum_{i=0}^{n-k}(-1)^i$ ${k+1}\choose{k}$ $S_{k+i}$ where $S_j= \sum_{i_1<i_2<...i_j} P(A_1 \cap A_2 ... \cap A_j )$
Where $P(N_k)$ is the probability of selecting exactly k out of a possible N events occurs.
I'm then asked to use the theorem to calculate the probability that out of the purchase of six packets of Corn flakes (each of which contains one of 5 possible busts), you end up with exactly three distinct busts.
The answer is:
$P(N_3) =$${5}\choose{3}$ $\alpha_3$ - ${5}\choose{4}$ ${4}\choose{3}$ $\alpha_4$+${5}\choose{3}$ $\alpha_5$
Where $\alpha_j$ is the probability that the j most recent vice-chancellors are obtained.
I'm confused by the solution in several respects:
1.) Why is $\alpha_j$ is the probability that the j most recent vice-chancellors rather than just any 3 from 5 as I would expect when applying the theorem.
2.) Why is the second term multiplied by 2 binomial coefficients (mathematically I see that to get 3 from 4 you need to know how many sets of 4 you have, but this does not appear to be given in the original formula?)
3.) How should I express the answer in terms on the original theorem nomenclature?
We are starting from having 3 items so $i=3$?
The number of individual events is k=3?
The total possible number of events is $n=5$?
but if this were correct the formula should read:
$P(N_3)=\sum_{i=3}^{2}(-1)^3$ ${k+1}\choose{k}$ $S_{k+i}$ where $S_j= \sum_{i_1<i_2<...i_j} P(A_1 \cap A_2 ... \cap A_j )$
This is clearly wrong?
Also why does the face that there are 6 packets being opening not appear in the formula? Surely as you increase the number of packets the probability of having 3 distinct busts should increase?

A: Let $f_j$ be the indicator function of $A_j$ and $g_k$ that of $n_k$.
Write $[n]=\{1,\ldots,n\}$. Then
\begin{align}
g_k&=\sum_{I:I\subseteq[n]\atop |I|=k}
\prod_{j\in I}f_j
\prod_{j\notin I}(1-f_j)\\
&=\sum_{I:I\subseteq[n]\atop |I|=k}
\sum_{J:I\subseteq J\subseteq[n]}(-1)^{|J|-k}\prod_{j\in J}f_j\\
&=\sum_{J:|J|\subseteq [n]\atop |J|\ge k}
(-1)^{|J|-k}\prod_{j\in J}f_j\sum_{I:\subseteq J\atop|I|=k}1\\
&=\sum_{J:|J|\subseteq [n]\atop |J|\ge k}
(-1)^{|J|-k}\binom{|J|}k\prod_{j\in J}f_j\\
&=\sum_{m=k}^n(-1)^{m-k}\binom mk\sum_{J:|J|\subseteq [n]\atop |J|=m}\prod_{j\in J}f_j.
\end{align}
Now take expectation of both sides.

A: (I realize this is an old question, but posting in case others come here like I did trying to understand the solution.) The connection between Waring's theorem and the stated probability of $N_3$,
$$
   \mathbb{P}(N_3) = {5 \choose 3}\alpha_3 - {5 \choose 4}{4 \choose 3}\alpha_4 + {5 \choose 3}\alpha_5\text{,}
$$
is as follows. Let $A_i$ be the event that a copy of the the $i$th bust is obtained, $1 \leq i \leq 5$, and for $1 \leq j \leq 5$, let
$$
   \alpha_j = \mathbb{P}(A_{i_1} \cap A_{i_2} \cap \cdots \cap A_{i_j})\text{,}
$$
given six packets purchased. The probability $\alpha_3$ is calculated in exercise 1.3.4, and the other two may be calculated similarly. Then,
$$
\begin{aligned}
   \mathbb{P}(N_3)
   &= \sum_{i=0}^{5-3}(-1)^{i}{3+i \choose 3}\sum_{i_1 < i_2 < \cdots < i_{3+i}}\mathbb{P}(A_{i_1} \cap A_{i_2} \cap \cdots \cap A_{i_{3+i}})\\
   &=     \sum_{i_1 < i_2 < i_3}\alpha_3 - {4 \choose 3}\sum_{i_1 < i_2 < i_3 < i_4}\alpha_4 - {5 \choose 3}\sum_{i_1 < i_2 < i_3 < i_4 < i_5}\alpha_5\\
   &=     {5 \choose 3}\alpha_3 - {4 \choose 3}{5 \choose 4}\alpha_4 - {5 \choose 3}{5 \choose 5}\alpha_5\\
   &=     {5 \choose 3}\alpha_3 - {5 \choose 4}{4 \choose 3}\alpha_4 - {5 \choose 3}\alpha_5\text{.}\\
\end{aligned}
$$
(The approximation I arrive at is 0.3469 with $\alpha_4 = 3359/15625$ and $\alpha_5 = 72/625$.)


text:
Q: Why does Python's None value not seem to be triggering my conditionals? I have a Python script running inside QGIS. It looks like this:
class Ranker(object):
    @staticmethod
    def haversine(lon1, lat1, lon2, lat2):
        """
        Calculate the great circle distance between two points
        on the earth (specified in decimal degrees)
        """
        # convert decimal degrees to radians
        lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
        # haversine formula
        dlon = lon2 - lon1
        dlat = lat2 - lat1
        a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
        c = 2 * math.asin(math.sqrt(a))
        km = 6367 * c
        return km

    @staticmethod
    def calculateDistance(featureProperty, layerEntrances):
        if featureProperty.geometry() is None:
            print("Null property geometry! Returning -1!")
            return -1
        shortestDistance = 1000
        featuresEntrances = layerEntrances.getFeatures()
        for featureEntrance in featuresEntrances:
            if featureEntrance.geometry() is None:
                print("Null entrance geometry! Skipping!")
                continue
            latEntrance = featureEntrance.geometry().centroid().asPoint().y()
            lonEntrance = featureEntrance.geometry().centroid().asPoint().x()
            latProperty = featureProperty.geometry().centroid().asPoint().y()
            lonProperty = featureProperty.geometry().centroid().asPoint().x()
            currentDistance = Ranker.haversine(lonEntrance, latEntrance, lonProperty, latProperty)
            if currentDistance < shortestDistance:
                shortestDistance = currentDistance
        return shortestDistance

    @staticmethod
    def importAndAnalyze(rowLimit = 3):
        layerProperties = iface.addVectorLayer("/Users/patrick/Downloads/DOR_Parcel/DOR_Parcel.shp", "Philly_City_Parcels", "ogr")
        if not layerProperties:
            print("layerProperties failed to load!")
        layerEntrances = iface.addVectorLayer("/Users/patrick/Downloads/Stations/philly-rail-stations-merged.shp", "Rail_Stations", "ogr")
        if not layerEntrances:
            print("layerEntrances failed to load!")
        features = layerProperties.getFeatures()
        counter = 0
        featuresSelected = []
        Path('/Users/patrick/Desktop/philly-property-rankings.csv').touch()
        with open('/Users/patrick/Desktop/philly-property-rankings.csv', 'a') as csvFile:
            csvWriter = csv.writer(csvFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
            csvWriter.writerow(['Address STD', 'Lat','Lon', 'Distance'])
            for feature in features:
                if counter < rowLimit:
                    csvWriter.writerow([feature['ADDR_STD'], feature.geometry().centroid().asPoint().y(),feature.geometry().centroid().asPoint().x(), Ranker.calculateDistance(feature, layerEntrances)])
                    if counter % 100 == 0:
                        csvFile.flush()
                else:
                    break
                counter += 1
            csvFile.flush()

Ranker.importAndAnalyze(10000000)

The problem is that after the script handles about 57,000 rows of data, it spits out this error:
Traceback (most recent call last):
  File "/Applications/QGIS.app/Contents/MacOS/../Resources/python/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 72, in <module>
  File "<string>", line 64, in importAndAnalyze
ValueError: Null geometry cannot be converted to a point.

I do not understand how this error is being reached. Shouldn't my two conditionals that reference the None value be enough to skip any null geography values?
Full disclosure: I'm not normally a Python guy. Please be kind if I'm missing something obvious.


text:
Q: Как менять значение переменной true/false с помощью чекбокса? const template = data => `
    <input type="checkbox" ${data.status ? 'checked' : ''} onclick="setStatus(${data.status = !data.status})">
`

Как менять data.status при каждом клике на чекбокс?
На данный момент он передает только значение на момент загрузки и не меняет его поочередно при клике и приходится перезагружать страницу, чтобы загрузить другое значение и поменять его.


text:
Q: Topshelf install command not returns I am using Topshelf v3.1 to install my console app as a windows service. I install my console via command line like: myconsole install
Everything seems good except that the command seems never complete, I mean usually once a command is executed, the command line console will be back the state that you can type another command again. Somehow topshelf command stops at the last point so I have to Control + C to kill the command.
My code is below:
class Program
    {
        static void Main(string[] args)
        {
            //HostFactory.Run(x =>
            //{
            //    x.Service<DummyService>(s =>
            //    {
            //        s.ConstructUsing(name => new DummyService());
            //        s.WhenStarted(tc => { });
            //        s.WhenStopped(tc => { });
            //    });

            //    x.RunAsLocalSystem();
            //    x.SetDescription("DummyService1");
            //    x.SetDisplayName("DummyService2");
            //    x.SetServiceName("DummyService3");
            //    x.StartAutomatically();
            //});
            var service = new DummyService();
            service.Run();
        }
}

Somehow, if I uncomment out the block that I commented out above and comment out the last 2 lines in the Main method. Then I run the command again, it magically works.
PS: DummyService.Run method just wraps the commented code block. Essentially, they are the same.
Any ideas?
Cheers,
Ld

A: Topshelf is for running services. This is the expected behaviour. The service needs to run continuously (until a stop command is sent) as Windows Services normally act. At the command line you need to CTRL+C to signal the end of the service.
If you want to run just a command, Topshelf is the wrong way to do it. Topshelf allows you to run the service normally as a command line as an easy way to debug services.


text:
Q: Webservice: html as an animated tree? I am looking for a web service that displays the html structure of a webpage like a graph.
I have seen an app years ago that looked beautiful. The input was a URL and the output was a flash tree with branches acting like springs and nodes had different colors for different tagnames.
I am not sure if this is an SO question. If not, can you please point me to the right stackexchange page?
Thanks!

A: Not sure if I understood correctly, but here is what I found

A: Not sure what you ment with "graph",
but as I'm tring to lern to DOMNodes,
I started playing around with a foldable presentation of html.
this is what i got so far:

*

*source: http://htmlviewer.puggan.se/htmlviewer/htmlviewer.201308131630.phps

*live: http://htmlviewer.puggan.se/htmlviewer/htmlviewer.201308131630.php
<?php

    require_once('/mnt/data/www/libs/remote.php');

    if(isset($_GET['debug']))
    {
        $debug_page = file_get_contents("exemple.html");
    }

    $form_page = <<<HTML_BLOCK

        <title>HTML Viewer</title>

        <form action='?' method='post'>

                Enter a URL
                <input type='text' name='url' id='url_input' />

            <input type='submit' value='view HTML' />
        </form>

HTML_BLOCK;

    if(isset($_REQUEST['url']) AND $_REQUEST['url'] OR isset($debug_page) AND $debug_page)
    {
        if(isset($debug_page) AND $debug_page)
        {
            $url = 'file:///debugpage.html';
            $page = &$debug_page;
        }
        else
        {
            $url = $_REQUEST['url'];
            $url_parts = parse_url($url);

            if($url_parts['scheme'] != 'http' AND $url_parts['scheme'] != 'https')
            {
                echo str_replace("", "
Bad url-scheme
");
                die();
            }

            $hash = isset($url_parts['fragment']) ? $url_parts['fragment'] : FALSE;

            $page = $remote_site->get_page($url);
        }

        if(!$page)
        {
            echo str_replace("", "
Page Empty
");
            die();
        }

        $doc = new DOMDocument();
        @$doc->loadHTML($page);

        if(!$doc)
        {
            echo str_replace("", "
Failed to read html
");
            die();
        }

        echo <<<HTML_BLOCK

        <title>HTML Viewer</title>

{$url}

HTML_BLOCK;
        if($hash)
        {
            $node = $doc->getElementById($hash);
            if($node)
            {
                print_node($node);
            }
            else
            {
                print_node($doc);
            }
        }
        else
        {
            print_node($doc);
        }
        echo <<<HTML_BLOCK

HTML_BLOCK;
    }
    else
    {
        echo $form_page;
    }

    function print_node($node)
    {
        if(!$node instanceof DOMNode)
        {
            trigger_error("Bad node: " . (get_class($node) ?: gettype($node)));
            return FALSE;
        }

        $classes = array('node');

        if($node instanceof DOMDocument)
        {
            echo "
";
            if($node->hasChildNodes())
            {
                echo "\n";
                foreach($node->childNodes as $child_node)
                {
                    print_node($child_node);
                }
            }
        }
        else if($node instanceof DOMComment)
        {
            return FALSE;
        }
        else if($node instanceof DOMDocumentType)
        {
            echo "
";
            echo htmlentities($node->internalSubset);
        }
        else if($node instanceof DOMText)
        {
            if(trim($node->wholeText))
            {
                echo "...";
                echo "
";
                //echo nl2br(htmlentities(trim($node->wholeText)));
                echo "
";
                echo htmlentities($node->wholeText);
                //echo get_class($node);
                //var_dump($node);
                echo "
";
                echo "
\n";
            }
            else
            {
                return FALSE;
            }
        }
        else if($node instanceof DOMCharacterData)
        {
            echo "
";
            echo "
";
            echo get_class($node);
            //var_dump($node);
            echo "
";
            echo "
\n";
        }
        else if($node instanceof DOMElement)
        {
            //content
            if($node->hasChildNodes())
            {
                echo "
tagName} close'>";

                echo "";
                echo "";
                echo "";
                echo "";

                echo "";
                echo "<";
                echo "" . $node->tagName . "";
                print_attributes($node);
                echo ">";
                echo "\n";

                echo "\n";

                echo "...";
                echo "
";
                foreach($node->childNodes as $child_node)
                {
                    print_node($child_node);
                }
                echo "
\n";

                echo "";
                echo "</";
                echo "" . $node->tagName . "";
                echo ">";
                echo "\n";
                echo "
\n";
            }
            else
            {
                echo "
";
                echo "";
                echo "<";
                echo "" . $node->tagName . "";
                print_attributes($node);
                echo "/>";
                echo "\n";
                echo "
\n";
            }
        }
        else
        {
            echo "
";

            echo "
";
            echo get_class($node);
            //var_dump($node);
            echo "
";
            echo "
\n";
        }
    }

    function print_attributes($node)
    {
        if(!$node instanceof DOMElement)
        {
            return FALSE;
        }

        if($node->hasAttributes())
        {
            echo " ";
            foreach($node->attributes as $node_attribute)
            {
                echo "";
                echo "";
                echo htmlentities($node_attribute->name);
                echo "";
                echo "=\"";
                echo "";
                echo htmlentities($node_attribute->value);
                echo "";
                echo "\"";
                echo " ";
            }
            echo "";
        }
        else
        {
            echo ' ';
        }
    }
?>


text:
Q: change css class on mouse over Hi im trying to make my navigation bar do the css focus effect on mouseover so it will not change until another menu item has the mouseover. Im trying to do it using Jquery.
Here is my code(I did import the jquery script btw and my css class):

Contact Us

About Us

Services

Home

Also Here is my Css Classes:

A: The best practice is to solve it with pure CSS (without any jQuery at all). here's a quick example:

A: If you don't care about IE6 - just use :hover like James suggeted. Otherwise simplify your code:
    $(document).ready(function () {
        $('#topNav a').hover(function () {
            $(this).addClass('topNavActive');
        }, function () {
            $(this).removeClass('topNavActive');
        });
    });

if you want to immitate :focus (but with mouseover):
    $(document).ready(function () {
        $('#topNav a').hover(function () {
            $(this).siblings().removeClass('topNavActive');
            $(this).addClass('topNavActive');
        }
    });

is it what you need?

A: try something like this.
    $('.topnav_class').over(function(){
        // delete all the classes of hover
        $(.topnav_class).removeClass('hover');
        // add the hover class just to this node
        $(this).addClass('hover);
    }, function(){
        $(this).addClass('hover');
    });

You have to play with $(this) more so you can do your jQuery a little more DRY (Do not repeat yourself)

A: .topNavNormal{
    background-color: #B0E0E6;
}

a .topNavNormal{
    line-height: 54px;
    color: #42647F;
}

if you aren't using these in different places i'd merge them and then you can just
a .topNavActive{
    line-height: 54px;
    color: #00EEEE;
    background-color: #5F9EA0;
}

and a simple javascript like:
$('topNavNormal').mouseover(function(){
    $('topNavNormal').removeClass('topNavActive');
    $(this).addClass('topNavNormal');
});

A: This Works for me
$(".panel").hover(function () {
    $(this).addClass('panel-info');
    $(this).removeClass('panel-warning');
}, function () {
    $(this).removeClass('panel-info');
    $(this).addClass('panel-warning');
});

A: This works for me. If you want to do something excited with bootstrap. Try this:
 $(".small").hover(function () {
        $(this).addClass('lead');
        $(this).removeClass('small');
    }, function () {
        $(this).removeClass('lead');
        $(this).addClass('small');
    });


text:
Q: a function that chages the structure of a python list I plan to write a python function that can change the structure of a list.
The input is:
list=[['A B C','D E F'],['1 2 3 ', '4 5 6 ']]

The output is:
list=[['A','B','C','D','E','F'],['1','2','3','4','5','6']]

I know I need the split() and append(). The confusing part is the loops.
Thanks so much!!

A: Use the join method to join the contain elements in the nested lists. Then split at the spaces.
my_list = [['A B C', 'D E F'], ['1 2 3 ', '4 5 6']]
my_list = [' '.join(i).split() for i in my_list]

A: Sometimes it's best not to over think it. Lets start with just one piece of your problem, ['A B C','D E F'] . You want to split each string, and put parts into a result list. Let's start by writing that function. You've correctly stated that this can be done using split/append, but lists also happen to have an extend method which will save you a few lines of code.
def as_char(seq):
    result = []
    for item in seq:
        result.extend(item.split())
    return result

Now you want to apply that function to every list in your input. For that you can use map for a list comprehension.
sample_input = [['A B C','D E F'],['1 2 3 ', '4 5 6 ']]
output = map(as_char, sample_input)
# or
output = [as_char(item) for item in sample_input]

A: Join your subelements making sure to leave a space when joining then split on whitespace to split into individual elements and remove any trailing whitespace.
print([ " ".join(sub).split() for sub in l])
[['A', 'B', 'C', 'D', 'E', 'F'], ['1', '2', '3', '4', '5', '6']]

If you only have two subelements unpack and split using str.format to allow a space between for splitting:
print([ "{} {}".format(a,b).split() for a,b in l ])

[['A', 'B', 'C', 'D', 'E', 'F'], ['1', '2', '3', '4', '5', '6']]

If you are using list as a variable name then don't as you will be shadowing the builtin list which often leads to more questions on SO...

A: How about this:
>>> my_list = [['A B C','D E F'],['1 2 3 ', '4 5 6 ']]
>>> map(lambda x:x.split(), map(" ".join, my_list))
[['A', 'B', 'C', 'D', 'E', 'F'], ['1', '2', '3', '4', '5', '6']]


text: Q: Navbar change on scroll Crashes I want to fade my first navbar on scroll and show my second navbar , but when using fade functions or even show() and hide() , on scroll breakpoint it keeps jumping infinitely , what should I do?


text:
Q: IsoDate and DateTime in MongoDB using C# Let us suppose that I want to query mongo on the dateTime. I have two C# variables representing  the start and the end date.
1) {20.10.2011 00:00:00}
2) {22.10.2011 00:00:00}
Now the BsonDateTime.Create(dateTime) transformed them to a BSON DateTime well too:
1) 2011-10-20T00:00:00  MongoDB.Bson.BsonDateTime
2) 2011-10-22T00:00:00  MongoDB.Bson.BsonDateTime
This is the code creating the dateTimes(_value is a string):
DateTime dateTime;
bool parsed = DateTime.TryParse(_value, out dateTime);
if (!parsed)
    throw new FormatException("Wrong format for a query param");
return BsonDateTime.Create(dateTime);

Then the next code builds the query:
private QueryComplete MakeQuery(string key, BsonValue value)
{
    if (_separatorType == ">=")
        return Query.GTE(key, value);
    if (_separatorType == "<=")
        return Query.LTE(key, value);
    return Query.EQ(key, value);
}

And i do get such a strange value in a query:
"Sessions.End" : { "$gte" : ISODate("2011-10-19T21:00:00Z"), "$lte" : ISODate("2011-10-21T21:00:00Z") },

Well, I google ISODate  but haven't found any reason why it should be shifted. Is it OK?

A: I believe the problem is that DateTime.TryParse is giving you a DateTime with a Kind of Local... whereas the ISO date is always in UTC. I expect that some part of the MongoDB code is converting the local DateTime to one in UTC. It's largely not your fault - basically, DateTime is a very confusing type.
I suspect if you specify DateTimeStyles.AssumeUniversal in your parsing code, it will do what you expect.
(Shameless plug: my own project, Noda Time, makes all of this a lot simpler...)


text:
Q: Labelled Generic containing `$eq` Shapeless 2.3.3 LabelledGeneric returns a curious result when run on the following case class:
scala> case class Foo(`$eq`: Int)
defined class Foo

scala> LabelledGeneric[Foo]
res0: shapeless.LabelledGeneric[Foo]{type Repr = Int with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("=")],Int] :: shapeless.HNil} = shapeless.LabelledGeneric$$anon$1@1ac7dbd3

Note the label returned is literally = instead of $eq.
Is this behaviour a quirk of shapeless or something else? Are there other identifier names that result in weird behaviour?
I require this for MongoDB serialization and this kind of a major headache for me ...

A: As per Alexey's comment in the Q, this is a 'feature' in Shapeless, because of the way scala/java interop works. The latter is explained in Daniel Spiewak's blot post under "operators and overaloading".
The list of operators, per the blog, that this affects are:
op  Compiles To
=   $eq
>   $greater
<   $less
+   $plus
-   $minus
*   $times
/   div
!   $bang
@   $at
#   $hash
%   $percent
^   $up
&   $amp
~   $tilde
?   $qmark
|   $bar
\   $bslash
:   $colon


text:
Q: What is the safest method for increasing the build limit in settlements? I have seen three ways to circumvent the building limit for settlements. Those being the "scrap weapon on ground" exploit, console commands, and a mod. Is there a "best" one? As in, does one hinder performance/stability/etc. the least?

A: As mentioned here:

The size budget is a polygon count designed to keep your frame rate steady by preventing you from building massive and overly complicated settlements. The size limit and current size used are actually attributes against the workbench in the settlement itself and differ between settlements.
This is calculated based on the number of objects in the settlement in combination with the size and complexity of the objects. More complex objects have a higher polygon count and as such use more of the budget. Scrap contributes to this limit so you could "fill" a settlement and then go around destroying all of the broken beds, cups, chairs, etc and have more budget available to build more.

This means that the performance hit is caused by drawing an additional quantity of items - all methods that "increase" the maximum number of objects you can build in your settlement will have a hit on performance because your machine has to draw more objects. The amount of performance hit you experience will be down to the platform you're playing on and how well the game was optimized on that platform or the specification of your hardware (PC), rather than the method you use to increase the value of a couple of variables in game.


text:
Q: table positioning issue on chrome I have implemented this calendar on mozilla firefox satisfactorily and when I try to view it on chrome, table doesn't fill all the parent section. The table height is the same as the parent section but it have moved a little bit to the bottom generating a white space between the section and the table.
Chrome:

Firefox:

In firefox works.
This is the code, you can try it on the demo and see the differences between chrome and firefox:

.right{
float:right !important;
}
.wz-ui-input[type="checkbox"] {
display: none;
}
.wz-ui-input {
background-color: #fcfeff;
border: 1px solid #dcdcdc;
border-radius: 3px;
box-shadow: 0 1px rgba(0, 0, 0, 0.05) inset;
color: #464646;
cursor: text;
font-size: 13px;
height: 28px;
padding: 0 10px;
width: 204px;
}
.wz-ui-input[type="checkbox"] + label i {
background: url("@static/checkbox_white.png") no-repeat scroll -17px 0 / 51px 17px rgba(0, 0, 0, 0);
display: inline-block;
height: 17px;
margin: -1px 4px 0 0;
vertical-align: middle;
width: 17px;
}
/* Shadow */
.hide {display:none;}
.abs {position:absolute; z-index: 3;}
.fullHeight{height:100%;}
.fullWidth{width:100%;}
.top{top:0;}
.dark{background-color:#999; background-color: rgba(123,123,123,0.7); opacity: 0.7;}
.center {text-align: center}
/* Calendar Top Bar */
.wz-ui-header{
width:100%;
height: 39px;
-webkit-border-radius: 3px 3px 0 0;
-moz-border-radius: 3px 3px 0 0;
border-radius: 3px 3px 0 0;
background-color: #f1f1f1;
-webkit-box-shadow: 0 2px 4px rgba(0,1,1,.1), inset 0 1px rgba(255,255,255,.1);
-moz-box-shadow: 0 2px 4px rgba(0,1,1,.1), inset 0 1px rgba(255,255,255,.1);
box-shadow: 0 2px 4px rgba(0,1,1,.1), inset 0 1px rgba(255,255,255,.1);
background-image: -webkit-linear-gradient(bottom, #b83e38, #da605b);
background-image: -moz-linear-gradient(bottom, #b83e38, #da605b);
background-image: -o-linear-gradient(bottom, #b83e38, #da605b);
background-image: -ms-linear-gradient(bottom, #b83e38, #da605b);
background-image: linear-gradient(to top, #b83e38, #da605b);
}
.shadow-border{
height: 38px;
width:100%;
-webkit-border-radius: 3px 3px 0 0;
-moz-border-radius: 3px 3px 0 0;
border-radius: 3px 3px 0 0;
background-color: #fdfeff;
border: solid 1px rgba(0,0,0,.15);
}
.calendar-menu{
display:block;
float:left;
width:85%;
}
.calendar-menu li {
border-bottom: 2px solid transparent;
color: #e9b9b7;
display: inline-block;
font-size: 15px;
height: 28px;
margin: 0 11px;
padding: 8px 1px 0;
}
.calendar-menu li.active-type {
border-bottom: 3px solid #7ebe30;
color: #ffffff;
}
.calendar-menu li:hover {
border-bottom: 3px solid #fff;
}
.calendar-menu-nav{
width:auto;
float:left;
}
.calendar-menu-event-finder {
width:auto;
height: 21px;
padding: 5px 10px;
}
.calendar-menu-event-finder input{
width: 137px;
height: 25px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #fcfeff;
-webkit-box-shadow: inset 0 2px rgba(0,0,0,.05);
-moz-box-shadow: inset 0 2px rgba(0,0,0,.05);
box-shadow: inset 0 2px rgba(0,0,0,.05);
border: solid 1px #a64440;
}
.calendar-buttons{
border-left: 1px solid #9f3e3a;
height: 100%;
width: 135px;
}
.wz-view-minimize, .wz-view-maximize, .wz-view-close, .close-image {
border: 1px solid transparent;
border-radius: 2px;
float: left;
height: 9px;
padding: 6px;
width: 10px;
margin: 9px 10px 10px;
}
.wz-view-minimize i{
background: url("@static/minimize.png") no-repeat scroll center bottom / 10px auto rgba(0, 0, 0, 0);
display: block;
height: 9px;
width: 10px;
}
.wz-view-maximize i{
background: url("@static/enlarge.png") no-repeat scroll center bottom / 10px auto rgba(0, 0, 0, 0);
display: block;
height: 9px;
width: 10px;
}
.wz-view-close i {
background: url("@static/close.png") no-repeat scroll center bottom / 10px auto rgba(0, 0, 0, 0);
display: block;
height: 9px;
width: 10px;
}
.close-image i{
background: url("@static/close.png") no-repeat scroll center bottom / 10px auto rgba(0, 0, 0, 0);
display: block;
height: 9px;
width: 10px;
}
/* Calendar general */
.calendar-head {
background: none repeat scroll 0 0 #fff;
height: 35px;
}
#day-calendar, #week-calendar, #month-calendar{
display: none;
}
.calendar-active{
width: 100%;
height: 85%;
background-color: #fff;
border: solid 1px rgba(0,0,0,.15);
display:block !important;
}
/* Calendar Modals */
#my-calendars-modal{
width: 210px;
height: 122px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #fff;
border: solid 1px rgba(0,0,0,.15);
position: absolute;
display: none;
margin-left: 12px;
margin-top: 31px;
z-index: 2;
}
#my-calendars-modal .my-calendars-list {
margin-left: 11px;
margin-top: 11px;
}
#my-calendars-modal .my-calendars-list articles {
margin-bottom: 11px;
font-size: 13px;
}
#my-calendars-modal .calendar {
display: block;
width: 100% !important;
}
#my-calendars-modal .calendar i{
float: left;
}
#my-calendars-modal .calendar span figure {
border-radius: 4px;
float: left;
height: 8px;
margin-right: 5px;
position: relative;
top: 4px;
width: 8px;
}
#my-calendars-modal .deleteCalendar{
margin-right: 10px;
font-size: 12px;
color:#dc513a;
}
#work span figure{
background-color: #34aadc;
}
#office span figure{
background-color: #5856d6;
}
#home span figure{
background-color: #f79a03;
}
#my-calendars-modal .add-new-calendar{
text-align: center;
border-top: 1px solid #dadada;
width: 100%;
padding: 11px 0;
font-size: 13px;
}
#create-event-modal{
width: 289px;
height: 289px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #f1f1f1;
-webkit-box-shadow: 0 1px 5px rgba(0,0,0,.3);
-moz-box-shadow: 0 1px 5px rgba(0,0,0,.3);
box-shadow: 0 1px 5px rgba(0,0,0,.3);
display: none;
z-index: 4;
position: absolute;
margin-left: 34%;
margin-top: 11.5%;
font-size:13px;
}
#create-calendar-modal{
width: 289px;
height: 198px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #f1f1f1;
-webkit-box-shadow: 0 1px 5px rgba(0,0,0,.3);
-moz-box-shadow: 0 1px 5px rgba(0,0,0,.3);
box-shadow: 0 1px 5px rgba(0,0,0,.3);
display: none;
z-index: 4;
position: absolute;
margin-left: 34%;
margin-top: 17%;
font-size:13px;
}
#create-calendar-modal .calendar-name input{
width: 161px;
height: 26px;
background-color: #fcfeff;
-webkit-box-shadow: inset 0 1px rgba(0,0,0,.05);
-moz-box-shadow: inset 0 1px rgba(0,0,0,.05);
box-shadow: inset 0 1px rgba(0,0,0,.05);
border: solid 1px rgba(0,0,0,.2);
border-radius: 3px;
}
#create-calendar-modal .calendar-name {
margin-left: 6%;
position: relative;
top: 32px;
float: left;
}
#create-calendar-modal .calendar-color {
margin-left: 9%;
position: relative;
top: 39px;
float: left;
}
#create-calendar-modal .calendar-color input{
width: 16px;
height: 12px;
}
#create-calendar-modal .calendar-description {
margin-left: 6%;
position: relative;
top: 49px;
float: left;
}
#create-calendar-modal .calendar-description textarea{
width: 260px;
height: 49px;
background-color: #fcfeff;
-webkit-box-shadow: inset 0 1px rgba(0,0,0,.05);
-moz-box-shadow: inset 0 1px rgba(0,0,0,.05);
box-shadow: inset 0 1px rgba(0,0,0,.05);
border: solid 1px rgba(0,0,0,.2);
margin-top: 6px;
border-radius: 3px;
}
#create-calendar-modal .create-calendar-button{
width: 71px;
height: 23px;
background-color: #75d142;
-webkit-box-shadow: inset 0 1px rgba(255,255,255,.3);
-moz-box-shadow: inset 0 1px rgba(255,255,255,.3);
box-shadow: inset 0 1px rgba(255,255,255,.3);
border: solid 1px #1b961b;
background-image: -webkit-linear-gradient(bottom, #4e9c21, #7ebe30);
background-image: -moz-linear-gradient(bottom, #4e9c21, #7ebe30);
background-image: -o-linear-gradient(bottom, #4e9c21, #7ebe30);
background-image: -ms-linear-gradient(bottom, #4e9c21, #7ebe30);
background-image: linear-gradient(to top, #4e9c21, #7ebe30);
margin-right: 10px;
margin-top: 68px;
color: #fff;
border-radius: 4px;
}
#create-calendar-modal .close-image {
float: right;
left: 250px;
position: absolute;
top: -4px;
cursor: pointer;
}
#create-calendar-modal .close-image i{
cursor: pointer;
}
.my-calendars, .current-month, .create-event {
float: left;
font-size: 14px;
margin-left: 12px;
padding: 11px 0;
width: auto;
}
.my-calendars, .my-calendars span, .create-event, .my-calendars img, .current-month img, .create-event span, .create-event img, .add-new-calendar, .add-new-calendar img, .add-new-calendar span, .deleteCalendar{
cursor:pointer;
}
.current-month{
margin-left:29%;
}
.current-month span{
margin: 0 20px;
}
.create-event{
margin-right: 20px;
}
.calendar-body{
height: 481px;
}
.calendar-body table{
width:100%;
height: 100%;
background: white;
}
td.other-month-cell{
background: #f1f1f1;
}
.calendar-days th{
font-size: 14px;
}
thead{
height: 33px;
background-color: #f1f1f1;
border-bottom: solid 2px #cacaca;
}
tbody{
height: 443px;
}
/* Month calendar */
#month-calendar td, #month-calendar th {
border: 1px solid #dadada;
text-align: left;
width: 14.2857%;
}
#month-calendar td span {
top: 6px;
margin-left: 6px;
position: relative;
}
#month-calendar .calendar-day-bar th {
vertical-align: middle;
font-size: 13px;
padding: 0px;
text-align: center;
}
#month-calendar .day-selected{
background-color: rgba(126,190,48,.1);
border: solid 1px #7ebe30 !important;
}
#month-calendar .event {
color: #4a4a4a;
font-size: 12px;
font-weight: bold;
height: 18px;
margin-left: 2px;
padding-left: 4px;
padding-top: 4px;
position: absolute;
width: 125px;
}
#month-calendar .office{
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #d1c4e9;
}
#month-calendar .event:nth-child(2){
margin-top: 10px;
display: block;
}
#month-calendar .event:nth-child(3){
margin-top: 32px;
display: block;
}
#month-calendar .event:nth-child(3)::after {
font-weight: 100;
content: '\A \A 5 more...';
white-space: pre;
color: #828282;
}
/* Week calendar */
#week-calendar td, #week-calendar th {
border: 1px solid #dadada;
text-align: left;
padding-left: 6px;
padding-top: 6px;
width: 12.5%;
}
#week-calendar .calendar-day-bar th, #week-calendar .calendar-day-bar td {
vertical-align: middle;
font-size: 13px;
padding: 0px;
text-align: center;
}
#week-calendar .hour-cell{
height: 41px;
}
/* Day calendar */
/* Images transformation */
.right-arrow{
transform: rotateY(180deg);
}

.wz-selectable, input, textarea, [contentEditable], [contentEditable] * {
cursor: text;
outline: medium none;
}
.wz-unselectable {
cursor: default;
}
[contentEditable] * {
color: inherit;
font-family: inherit;
}
link {
display: none;
height: 0;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
b {
font-weight: bold;
}
ol, ul {
list-style: outside none none;
}
hr {
margin: 0;
padding: 0;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
textarea {
resize: none;
}
audio {
display: none;
height: 0;
}

       My calendars

        September 2013

        Create new event

            <articles id="work" class="calendar">
                <input type="checkbox" checked="checked" class="wz-ui-input">

Work
                Eliminar
            </articles>
            <articles id="office" class="calendar">
                <input type="checkbox" checked="checked" class="wz-ui-input">

Office
                Eliminar
            </articles>
            <articles id="home" class="calendar">
                <input type="checkbox" checked="checked" class="wz-ui-input">

Home
                Eliminar
            </articles>

            Add new calendar

        <form>
            <artricle class="calendar-name">
                <input type="text" placeholder=" Name of calendar">
            </artricle>
            <artricle class="calendar-color">
                Color
                <input type="color">
            </artricle>
            <artricle class="calendar-description">
                Description

                <textarea></textarea>
            </artricle>
            <button type="submit" class="create-calendar-button right">Create</button>
        </form>

                Sunday
                Monday
                Thusday
                Wednesday
                Thursday
                Friday
                Saturday

                1
                2
                3

                4
                5
                6
                7
                8
                9
                10

                11
                12
                13
                14

                    15

 Me voy a casar

 Reunion con el jefe

                16
                17

                18
                19
                20
                21
                22
                23
                24

                25
                26
                27
                28
                29
                30
                31


text:
Q: Reading and storing txt. file content in an array list I have a .txt file and wish to read it in and store its content as an array list.
Data in .txt file is like this :
1984      1   0.20  25.10   4.40  11.20   0.60   4.80   0.10   0.00   5.90  22.50   5.90  12.70   6.00   3.80   0.60  10.70   4.20   0.00   0.00   0.00   7.90   4.00  23.70   3.20   5.80   3.00   0.60   6.00   1.70   7.50   1.20

All in one line, 1984 for year, 1 for months, other values for respective days of months. I wish to store each line (ideally, each variable) in a different slot so its easily accessible by index.
I have written this code in order to read in the file and store the variables in an array list as I am unsure of the size of the array needed.
import java.io.*;
import java.util.*;

public class reader {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(
                    "2RainfallDataLanc.txt"));
            String line = null;
            ArrayList<String[]> rows = new ArrayList<String[]>();
            while ((line = reader.readLine()) != null) {
                String[] row = line.split("/t");
                rows.add(row);
            }
            System.out.println(rows.toString());
        } catch (IOException e) {
        }
    }
}

I receive an error message. Could someone tell me whats wrong with my code please?

A: Try using
for (String[] row : rows) {
    System.out.println(Arrays.toString(row));
}

To see the output. ToString on an array produces nothing useful
Assuming your data points are separated by whitespaces, you could try to parse them with this line
String[] row = line.split("\\s+");

+ means 1 or more occurences of the symbol in front of it (\s is shorthand for white space, see Regular Expressions in Java)


text:
Q: Angular http request observable error does not catch error? Angular 6 using HttpClient. No interceptors implemented for now.
I have an admin service where I'm doing a http call to MSGraph. In this case I'm getting an error 400 bad request which I'm sending to the notification handler.
I've slided in that console.log to make sure that the error block is firing at all and another cnosole.log to see if the 'data' getting back from the server is an error.
None of the console.logs fire yet the global error handler still displays the 400 bad request response in the console.
I'd like to be able to use this response and display a user-friendly message.
Code:
this.http.get(this.GRAPH_ROOT_URL + this.APP_ID, { headers }).subscribe(data => {
  this.notification.done(data);
  console.log(data);
}), error => {
  this.notification.error(`Error getting users from Microsoft GRAPH API. Reason: ${error}`)
  console.log("this is observable error", error);
}

A: Angular 6 uses RxJS 6, which comes with a number of changes. Assuming that's what you're using, this is what I would use:
Here's what I would use:
this.http.get(this.GRAPH_ROOT_URL + this.APP_ID, { headers })
    .pipe(catchError(err => {
      this.alert.error('There was an error getting data');
      return throwError(err);
    })).subscribe(data => this.notification.done(data));

So you use pipe to call catchError, which does handle the server errors correctly.
To use catchError, you need to import it first, like this:
import { catchError } from 'rxjs/operators';


text:
Q: drawing the player (a simple rectangle) with lwjgl does...nothing So, I wanted to program a simple game using lwjgl, however I encountered a problem even before the pre-pre-pre-alpha phase, right at the beginning.
As long as I don't have a texture for it, I wanted to draw the player just using a simple rectangle. However, my Code does nothing.
here's my openGL initialization Code:
glMatrixMode(GL_PROJECTION);
glOrtho(0, 640, 480, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

and here's the main loop:
while(!Display.isCloseRequested()) {
            //Main loop
            glClear(GL_COLOR_BUFFER_BIT);

            player.update();

            Display.update();
            Display.sync(60);
        }
Display.destroy();
System.exit(0);

The player.update() function checks for Input and calls the draw function, which looks like this:
public void draw() {
        glBegin(GL_QUADS);
            glVertex2f(x * World.TILE_SIZE, y * World.TILE_SIZE);
            glVertex2f(x * World.TILE_SIZE + World.TILE_SIZE, y * World.TILE_SIZE);
            glVertex2f(x * World.TILE_SIZE + World.TILE_SIZE, y * World.TILE_SIZE
                    + World.TILE_SIZE);
            glVertex2f(x * World.TILE_SIZE, y * World.TILE_SIZE + World.TILE_SIZE);
        glEnd();
}

To me, this looks like very simple lwjgl-code that should work without any problems, except it doesn't. When executed, it just gives me a black window, without any rectangles drawn on it. Any suggestions?
thanks in advance
-v0xelDev

A: Fixed.
Found the answer here.
Appearently, I can't draw simple coloured shapes with GL_TEXTURE_2D enabled, my openGL initialization code now looks like this:
    glMatrixMode(GL_PROJECTION);
    glOrtho(0, 640, 480, 0, 1, -1);
    glMatrixMode(GL_MODELVIEW);
    glDisable(GL_TEXTURE_2D);
    //glEnable(GL_BLEND);
    //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);


text:
Q: Errors while adding Admob I am trying to add Admob into my app. All I do is drop the Admob files into my app and I get these errors:

I had no errors before I add Admob...
Here is the full error:
error: unable to open executable '/Users/Library/Developer/Xcode/DerivedData/AppName-/Build/Products/Debug-iphonesimulator/AppName.app/AppName'

A: Link all Libraries from this list (step 3):

*

*AdSupport

*AudioToolbox

*AVFoundation

*CoreGraphics

*CoreTelephony

*MessageUI

*StoreKit

*SystemConfiguration

and add -ObjC to other linker flags for you target (step 4):

Source: this guide


text:
Q: contents of mounted drive not visible in Apache/2.4.18 (ubuntu) Our cluster's apache setup is as such: each user has a directory ~/public_html, and any files (including soft linked files) inside this directory are accessible through http. I have files on another server (serverB) which I mounted to our cluster using the flowing command:
sudo mount -t cifs -o vers=3.0,uid=10069,gid=10069,credentials=secrets //xxx.xxx.edu/path/to/source public_html/serverB

When using ssh, I could assess all mounted files just as if they were present on the cluster. I could also see a folder named "serverB" on http. However, serverB appears as an empty folder on http, with none of its contents visible. I was wondering if it's at all possible to make all contents of mounted serverB available through http as well?


text:
Q: If I have a table with a column that contains Name like FIrstName.LastName How to get only the last name by using SQL Query?

A: If you are using  an oracle rdbms, then you can use substr and instr functions to get the lastname from the column.
For ex.
Select substr(column_name, instr(column_name,".")) from the table_name

Note:-
 Assumed that dot (".") is present only once in the values.
For more reference you can refer instr documentation and substr documentation


text:
Q: Is an Object the smallest pageable unit in the Heap? If I have a 2 GB ram and I have an 2 instances of an Object which is 1.5 GB each, the operating system will help and context switch the pages to and from harddisk.
What if I have 1 instances but is 3 GB. Can the same paging method breakdown this instances into 2 pages? Or will I encounter out-of-memory issue?
I will also like to apply the same question to other data structures beside object, will the paging page it as a whole, or will it break it into smaller units.
Thanks.

A: The operating system has no concept of "Objects", only memory pages. Your object will be made up of many memory pages which the OS can swap in and out of real memory independently of each other. Page size varies with operating systems, but is typically 4K.


text:
Q: default routing in codeigniter I'm exploring codeigniter. On app startup default controller is changed to load my controller.
Controller properly loads the view and that's fine, so I'm guessing routing works as expected, but when I use (manually type on address bar other method on same controller) same url pattern /controller/method I'm getting 404 error, either view exist.
Do  have to change some default routing behavior or something else is problem?
Thanks

A: I dont know if you already removed index.php from your url pattern, assuming that's the case you should type inside browser address field index.php/controller/method. (if you manually type url as you describe)
If you on the other hand do not want to use index.php on every link you can consider to remove that, more info here.

A: Well this may be the because of index.php file as mentioned above or else if you would like get rid of index.php Kindly include .htaccess file in your application.
 config/config.php - modifiy
 $config['base_url'] = 'index.php'
 $config['base_url'] = '' // set it to blank

For .htaccess file refer the below code
 RewriteEngine on
 RewriteCond $1 !^(index\.php|images|robots\.txt)
 RewriteRule ^(.*)$ /index.php/$1 [L]

A: follow this

root_folder/.htaccess
to remove index.php in url

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

set base URL
root_folder/application/config/config.php

| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'http://[::1]/my-project/';

removing index.php in url, even on request post in form
root_folder/application/config/config.php

/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';

set default controller, mine is 'home'
root_folder/application/config/routes.php

| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
|       my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'home';

after that, make sure that the all controller file name is capitalize.
  also a class name.
this is also important mostly when you need to upload in a live
server.
root_folder/application/controllers/Home.php

<?php

/**
 *
 *
 * @author Lloric Garcia <emorickfighter@gmail.com>
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends MY_Controller {

    public function index() {

    }

}

then this will be you url
http://[::1]/my-project/home

that is my set up even in live server
all of this came from

https://www.codeigniter.com/userguide3/index.html


text:
Q: Error while trying to connect cassandra database using spark streaming I'm working in a project which uses Spark streaming, Apache kafka and Cassandra.
I use streaming-kafka integration. In kafka I have a producer which sends data using this configuration:
props.put("metadata.broker.list", KafkaProperties.ZOOKEEPER);
props.put("bootstrap.servers", KafkaProperties.SERVER);
props.put("client.id", "DemoProducer");
where ZOOKEEPER = localhost:2181, and SERVER = localhost:9092.
Once I send data I can receive it with spark, and I can consume it too. My spark configuration is:
SparkConf sparkConf = new SparkConf().setAppName("org.kakfa.spark.ConsumerData").setMaster("local[4]");
sparkConf.set("spark.cassandra.connection.host", "localhost");
JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(2000));

After that I am trying to store this data into cassandra database. But when I try to open session using this:
CassandraConnector connector = CassandraConnector.apply(jssc.sparkContext().getConf());
Session session = connector.openSession();

I get the following error:
Exception in thread "main" com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/127.0.0.1:9042 (com.datastax.driver.core.exceptions.InvalidQueryException: unconfigured table schema_keyspaces))
at com.datastax.driver.core.ControlConnection.reconnectInternal(ControlConnection.java:220)
at com.datastax.driver.core.ControlConnection.connect(ControlConnection.java:78)
at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1231)
at com.datastax.driver.core.Cluster.getMetadata(Cluster.java:334)
at com.datastax.spark.connector.cql.CassandraConnector$.com$datastax$spark$connector$cql$CassandraConnector$$createSession(CassandraConnector.scala:182)
at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$2.apply(CassandraConnector.scala:161)
at com.datastax.spark.connector.cql.CassandraConnector$$anonfun$2.apply(CassandraConnector.scala:161)
at com.datastax.spark.connector.cql.RefCountedCache.createNewValueAndKeys(RefCountedCache.scala:36)
at com.datastax.spark.connector.cql.RefCountedCache.acquire(RefCountedCache.scala:61)
at com.datastax.spark.connector.cql.CassandraConnector.openSession(CassandraConnector.scala:70)
at org.kakfa.spark.ConsumerData.main(ConsumerData.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Regarding to cassandra, I'm using default configuration:
start_native_transport: true
native_transport_port: 9042
- seeds: "127.0.0.1"
cluster_name: 'Test Cluster'
rpc_address: localhost
rpc_port: 9160
start_rpc: true

I can manage to connect to cassandra from the command line using cqlsh localhost, getting the following message:
Connected to Test Cluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra 3.0.5 | CQL spec 3.4.0 | Native protocol v4] Use HELP for help. cqlsh>

I used nodetool status too, which shows me this:
http://pastebin.com/ZQ5YyDyB
For running cassandra I invoke bin/cassandra -f
What I am trying to run is this:
try (Session session = connector.openSession()) {
        System.out.println("dentro del try");
        session.execute("DROP KEYSPACE IF EXISTS test");
        System.out.println("dentro del try - 1");
        session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
        System.out.println("dentro del try - 2");
        session.execute("CREATE TABLE test.users (id TEXT PRIMARY KEY, name TEXT)");
        System.out.println("dentro del try - 3");
    }

My pom.xml file looks like that:
<dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.10</artifactId>
        <version>1.6.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka_2.10</artifactId>
        <version>1.6.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.10</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector-java_2.10</artifactId>
        <version>1.6.0-M1</version>
    </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.10</artifactId>
        <version>1.6.0-M2</version>
    </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.10</artifactId>
        <version>1.1.0-alpha2</version>
    </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector-java_2.10</artifactId>
        <version>1.1.0-alpha2</version>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160212</version>
    </dependency>
</dependencies>

I have no idea why I can't connect to cassandra using spark, is it configuration bad or what i am doing wrong?
Thank you!

A:
com.datastax.driver.core.exceptions.InvalidQueryException:
  unconfigured table schema_keyspaces)

That error indicates an old driver with a new Cassandra version. Looking at the POM file, we find there the spark-cassandra-connector dependency declared twice.
One uses version 1.6.0-m2  (GOOD) and the other 1.1.0-alpha2 (old).
Remove the references to the old dependencies 1.1.0-alpha2 from your config:
<dependency>
    <groupId>com.datastax.spark</groupId>
    <artifactId>spark-cassandra-connector_2.10</artifactId>
    <version>1.1.0-alpha2</version>
</dependency>
<dependency>
    <groupId>com.datastax.spark</groupId>
    <artifactId>spark-cassandra-connector-java_2.10</artifactId>
    <version>1.1.0-alpha2</version>
</dependency>


text:
Q: Problems with using default() in .Rprofile Most of the libraries I use in R are installed via the OS (i.e. using apt install r-cran-* which are installed in /usr/lib/R/*).  Unfortuntaely, when using update.libraries() within a session offers to update these packages'm trying to have R only install libraries in specific locations. As a result, I've tried modifying my .Rprofile in the following manner:
## only update libraries installed in R sessions.
## Don't update libraries installed using apt.
## these libraries reside in /usr/lib/R
## Code based on: https://coolbutuseless.github.io/2018/04/11/changing-the-default-arguments-to-a-function/
library(default)
## See my note on stackexchange how this doesn't work as expected
## default(update.packages) <- list(lib.loc=grep("/usr/lib/R", .libPaths(), invert=TRUE, value=TRUE))
tmpUser = Sys.getenv("USER")
if( tmpUser =="root"){
    tmpLibPath <- "/usr/local/lib/R/site-library"
}else{
    tmpLibPath <- Sys.getenv("R_LIBS_USER")
}

default(update.packages) <- list(lib.loc = tmpLibPath)
default(install.packages) <- list(lib = tmpLibPath)
## Clean up
rm(c("tmpUser", "tmpLibPath")

However, when I start an R session, I get the error,
`Error in default(update.packages) <- list(lib.loc = tmpLibPath) :
object 'update.packages' not found
and my changes don't stick (though they do if I execute the code within an interactive session).  Can anyone help me either (a) understand what I'm doing wrong or (b) suggest another way to achieve this goal?


text:
Q: Probability of games to require modification after an update After an update, out of the games on the market, 10% of them will need to be completely modified, 30% will be need to be modified partly, and 60% will require no modification. A game developer currently has 6 games on the market. What is the probability that: i) At least 3 of his games will need to be modified partly and ii) Two require a complete modification and one wont require any modifications.
For the first part, I said that the probability of at least 3 games to require partial modification is $1-$ probability of none, 1 or two to not require partial modification. I got $1-\left(0.7^6+0.7^5\cdot 0.3+0.7^4\cdot 0.3^2\right) = 0.81$ . Was I correct in my assumption?
For the second part, I just did $0.1^2\cdot 0.6\cdot 0.3^3 = 0.00016$ since I thought that the probability is just the product of each event's probability(as in, probability of no modify^2 times probability of no modify times probability of partial modification^3), but the result I get is very low and I don't know if what I did was correct or not.

A:
I got $1−(0.7^6 + 0.7^5⋅0.3+0.7^4⋅0.3^2)=0.81$
  . Was I correct in my assumption?

No, but you have the right idea.
The probability that exactly one of the six requires partial-modification is $\binom 61\cdot 0.7^5\cdotp 0.3$, because it can be any one of the six, not just the last one.
Likewise the probability that exactly two of the six requires partial-modification is $\binom 62\cdot 0.7^4\cdotp 0.3^2$, because it can be any two of the six, not just the last two.
$$1−(0.7^6 + 6\cdotp 0.7^5\cdotp 0.3+15\cdotp 0.7^4\cdotp 0.3^2)=0.25569$$
Alternatively: $20\cdotp 0.7^3\cdotp0.3^3+15\cdotp 0.7^2\cdotp 0.3^4+6\cdotp 0.7^1\cdotp 0.3^5+0.3^6 = 0.25569$

Apply the same principle to the second problem.


text:
Q: TabControl disposes of controls on inactive tabs I'm using the MVVM pattern for my app. The MainWindow comprises a TabControl with the DataContext mapped to the ViewModel:
<Window.Resources>
  <ResourceDictionary>
    <DataTemplate x:Key="templateMainTabControl">
      <ContentPresenter Content="{Binding Path=DisplayName}" />
    </DataTemplate>

    <local:ViewModel x:Key="VM" />
    <local:WorkspaceSelector x:Key="WorkspaceSelector" />
    <local:TabOneView x:Key="TabOneView" />
    <local:TabTableView x:Key="TabTableView" />

    <DataTemplate x:Key="TabOne">
      <local:TabOneView />
    </DataTemplate>

    <DataTemplate x:Key="TabTable">
      <local:TabTableView />
    </DataTemplate>

  </ResourceDictionary>
</Window.Resources>

<TabControl Grid.Row="0"
            DataContext="{StaticResource VM}"
            ItemsSource="{Binding Workspaces}"
            SelectedItem="{Binding SelectedWorkspace}"
            ItemTemplate="{StaticResource templateMainTabControl}"
            ContentTemplateSelector="{StaticResource WorkspaceSelector}" />

The WorkspaceSelector looks like:
public class WorkspaceSelector : DataTemplateSelector
{
  public override DataTemplate SelectTemplate( object item, DependencyObject container )
  {
    Window win = Application.Current.MainWindow;
    Workspace w = ( Workspace ) item;
    string key = w.DisplayName.Replace( " ", "" );
    if ( key != "TabOne" )
    {
      key = "TabTable";
    }
    return win.FindResource( key ) as DataTemplate;
  }
}

so that TabOne returns the DataTemplate. TabOne and the other two tabs return the DataTemplate TabTable.
If I run the application and click on each of the tabs twice (1, 2, 3, 1, 2, 3) I don't get what I expect, which is
TabOne's view is created
TabTwo's view is created
TabOne's View is created
TabTwo's view is created
that is, if the TemplateSelector returns a different value, the existing tab's controls are thrown away and the new tab's control's are created, and if the TemplateSelector returns the same value, nothing happens.
This is exactly what I don't want! I'd like the TabControl to keep all the controls on the tabs, and I would like to be able to do something about creating different controls in code for the case where I go from TabTwo to TabThree. I can live without the latter. But how do I tell the TabControl not to throw away each tab's controls when it's not selected?

A: This is a function of the TabControl and is the default behavior.
Basically, to save memory, the TabControl unloads the visual tree that is in its content area and replaces it with a newly crufted up one for the new tab.  To prove this to yourself, you can listen to the Unload event on each control you template in and notice that it fires every time you switch tabs.
There are likely 2 reasons you would want to override this behavior:

*

*You believe that there would be a significant performance penalty.

*You are losing the state of the controls because any visual state that is being lost is not backed by a ViewModel.

As for #1, you shouldn't be concerned.  CPU time is generally cheaper than RAM and the default behavior leans on the cheaper side of the resource equation. If you still feel like you REALLY don't want this behavior, you can see an example of overriding it here:
https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Wpf.Example/Controls/NonReloadingTabControl.cs
However, I would consider this a "smell" for potentially a future performance issue you should spend the time figuring out now, rather than delaying figuring it out.
For #2, you have two options:

*

*Make sure every property you want preserved (like IsSelected, etc) is backed by a ViewModel that preserves that state.

*Create a persistent UserControl for each tab that you bind to, rather than to ViewModels (Workspaces in your case).  There is an example of that in the "Writer" sample for WAF: http://waf.codeplex.com/


text:
Q: How to get my xbox 360 joypad to work in 14.04? I have a third party wired xbox 360 joypad that I am trying to us for emulators. How do I get this thing to work?

A: Try downloading and configuring xboxdrv (xbox driver)
sudo apt-get install xboxdrv && sudo xboxdrv


text:
Q: SVN auto property based on repository We have multiple SVN repositories. A developer may be working on multiple repositories at the same time. I am aware of the auto-prop option available with SVN. If we enable this, it is adding the property on files in all the repositories whenever commit happens. Is there any way   I can tell subversion to enable auto-prop only when checkin happens to a particular repository and not all the repos.
I am adding the property 'needs-lock'. There are hundreds of developers working on a particular project. It is difficult to enable the auto-prop option in all the developers machine. For the existing files, I can add the property in SVN. Is there any way I can add the property to the newly added files via hook scripts or something from server side instead of enabling auto-prop in all developer machines.

A: See the answer: https://stackoverflow.com/a/18571763/761095.

*

*Force your users to use SVN 1.8 client,

*Set svn:auto-props to add svn:needs-lock on required repository items (works with Subversion 1.8+ client).

See

*

*SVNBook | Inherited Properties & SVNBook | Automatic Property Setting,

*Subversion 1.8 Release Notes | Inherited Properties.


text:
Q: Deploying reactjs app to aws amplify results in white screen with error "Uncaught SyntaxError: Unexpected token '<'" I am trying to deploy a reactjs app to aws amplify and everything works final on localhost and in incognito browser window, just when I access my app url in a regular browser I get this error

If I clear my browser cookies and access the url its fine but everytime I deploy a new build folder it goes back to this. I tried almost every suggestion I could find on the internet but it still occurs.
Solutions I tried :

*

*Setting up PUBLIC_URL in .env file.

*Deploying through S3 bucket instead of drag and drop.

*Adding <Router basename='/index.html'> to my code.

*Adding homepage pointing to my domain in package.json.

*Adding homepage pointing to '.' in package.json

*Adding homepage pointing to './' in package.json

*Adding the above homepage variations to manifest.json in public folder.

Details about my environment and observations :

*

*I am hosting the app on aws amplify with custom domain via Route 53.

*App works absolutely fine without any issues on incognito browser - so if there was an issue with the code it should break in incognito as well correct?

*The work-around is to clear browser cookies and hit the url again but its undesirable coz this is a production environment and every time I deploy a change I cannot ask my users to clear cookies and try again - changes should be picked up by the browser instantly.

*Following is my compiled index.html

    <meta charset="utf-8" />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;900&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Poppins:wght@400;500;600;700;900&display=swap" rel="stylesheet">
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Vaccination Verification Made Easy" />
    <link rel="apple-touch-icon" href="https://vaxtone.com/logo192.png" />
    <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

    <link rel="manifest" href="https://vaxtone.com/manifest.json" crossorigin="use-credentials">
    <title>VaxTone</title>
    <link href="https://vaxtone.com/static/css/2.f4136754.chunk.css" rel="stylesheet">
    <link href="https://vaxtone.com/static/css/main.dd527d15.chunk.css" rel="stylesheet">

You need to enable JavaScript to run this app.

*I used the create-react-app command to create the reactjs app and use npm run build to generate the build folder for deployment.

*I use a service worker to implement progressive-web-app features - could it be something related to my service worker?
Any help on how to resolve this or what do you think is happening would be a big big help .Thanks.

A: Make sure your package json file either does not have homepage set or the value for homepage matches your AWS Amplify URL. I had the same issue and this resolved it.


text:
Q: How to find the index of the nth time an item appears in a list? Given:
x = ['w', 'e', 's', 's', 's', 'z','z', 's']

Each occurrence of s appears at the following indices:
1st: 2
2nd: 3
3rd: 4
4th: 7
If I do x.index('s') I will get the 1st index.
How do I get the index of the 4th s?

A: For getting the index of the items:
return [index for index, char in enumerate(x) if char == 's']

For getting the character itself:
return [char for index, char in enumerate(x) if char == 's']

Or to get tuples of character/index pairs:
(Thanks to falsetru for pointing out a simpler solution)
pairs = [(index, char) for index, char in enumerate(x) if char == 's']

A: Using list comprehension and enumerate:
>>> x = [ 'w', 'e', 's', 's', 's', 'z','z', 's']
>>> [i for i, n in enumerate(x) if n == 's'][0]
2
>>> [i for i, n in enumerate(x) if n == 's'][1]
3
>>> [i for i, n in enumerate(x) if n == 's'][2]
4
>>> [i for i, n in enumerate(x) if n == 's'][3]
7

A: If you didn't want to store the indices for each occurrence, or wanted to work with arbitrary iterables then something like:
from itertools import islice

def nth_index(iterable, value, n):
    matches = (idx for idx, val in enumerate(iterable) if val == value)
    return next(islice(matches, n-1, n), None)

x = [ 'w', 'e', 's', 's', 's', 'z','z', 's']
idx = nth_index(x, 's', 4)
# 7

Note there's a default value of None there in the next. You may wish to change that to something else, or remove it and catch the StopIteration and raise as another more suitable exception (ValueError for instance, so that it ties up more with list.index behaviour).

A: def find_nth_character(str1, substr, n):
    """find the index of the nth substr in string str1"""
    k = 0
    for index, c in enumerate(str1):
        #print index, c, n  # test
        if c == substr:
            k += 1
            if k == n:
                return index

str1 = "B.765.A87_43.Left.9878.xx8"
substr = '.'
occurance = 4

print "%s #%d at index %d" % (substr, occurance, find_nth_character(str1, substr, occurance))

A: Here is a more Pythonic approach using itertools.count and a generator expression:
In [24]: def get_nth_index(lst, item, n):
    ...:     c = count()
    ...:     return next(i for i, j in enumerate(x) if j=='s' and next(c) == n-1)

Demo:
In [25]: get_nth_index(x, 's', 2)
Out[25]: 3

In [26]: get_nth_index(x, 's', 3)
Out[26]: 4

In [27]: get_nth_index(x, 's', 4)
Out[27]: 7

In [28]: get_nth_index(x, 's', 5)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-28-fc4e5e8c31ef> in <module>()
----> 1 get_nth_index(x, 's', 5)

<ipython-input-24-5394f79b3c30> in get_nth_index(lst, item, n)
      1 def get_nth_index(lst, item, n):
      2     c = count()
----> 3     return next(i for i, j in enumerate(x) if j=='s' and next(c) == n-1)

StopIteration:

In [29]:

As you can see, it will raise an StopIteration exception in case it can't find a match. You can also pass a default argument to next() function to return a default value instead of raising exception.

A: simply we can extend the functionality of the built-in list class. by inheriting it.
In [64]: class List(list):
       :     def __init__(self, *val):
       :         self.extend(list(val))
       :
       :
       :     def findidx(self, val, n=None):
       :         '''return the occurances of an object in a list'''
       :
       :         if n == None:
       :             return [i for i, v in enumerate(self) if v == val]
       :
       :         return [i for i, v in enumerate(self) if v == val][n]

and there are two ways to use this class. see in the following example to understand.
In [65]: c = List(4, 5, 6, 7, 2, 5, 4 ,4) # enter the elements of the list as a argument

In [69]: c.findidx(4, 0) # search 4's 0th(1) occurance
Out[69]: 0

In [72]: c.findidx(4, 1) # find 4's 1st(2) occurance
Out[72]: 6

or
In [66]: c.findidx(4) # find all occurances of 4
Out[66]: [0, 6, 7]

In [67]: c.findidx(4)[0] # first occurance
Out[67]: 0

In [67]: c.findidx(4)[2] # third occurance
Out[67]: 7

In [69]: c[0]# for verification
Out[69]: 4

In [70]: c[7]
Out[70]: 4

`

A: You can use this to find in last position
where a is the array
t=(a.index(0)+a.count(0))-1
You can increase the number to -2 or -3 to find the position of the desired number from last

NOTE: The list must be sorted. You can sort it with sort ()

eg:
a.sort()
for more inbuilt function in list click here


text:
Q: KeyError: when making new column in pandas I am working on a dataset and when I try to create a new column after find the difference I get the KeyError: 'filtered'
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

d = {'col1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'col2': [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]}
df = pd.DataFrame(data=d)
fig, ax = plt.subplots(2, figsize=(8,8))

df['col2'].diff().plot(ax=ax[0])

cutoff = 3
df['filtered'] = df.loc[df['col2'].diff().abs() > cutoff]
df.plot(ax=ax[1])

I used to create new column like this (df['filtered'] = some operation), but it gives KeyError: 'filtered' in this situation. Thank you for the help.

A: You need to replace the second-to-last line with:
df['filtered'] = df.loc[df['col2'].diff().abs() > cutoff, 'col2']

assuming that you want to get a filtered version of 'col2'. As @RafaelC mentioned, the current .loc[] operation you have returns all the columns (2 in this case) for which the row filter applies hence the error.


text:
Q: Bitwise operator "&" I have trouble understanding "&" operator in javascript.
Why does this code
var wins = [7, 56, 448, 73, 146, 292, 273, 84];
var score=77;
for (i = 0; i < wins.length; i += 1) {
    alert((wins[i] & score)===wins[i])

        }

return true on win[3] , basicly why does
73&77==73

I just cant find the right answers.


text:
Q: generic and generic map | total time delay for each files In adder.vhd
  H1: half_Adder generic map ( gate_delay => 6 ns );
  port map ( a => ln1, b => ln2, ... );

half_adder.vhd
  Ex1 : xor generic map ( gate_delay => gate_delay );
  A1  : and generic map ( gate_delay => gate_delay );

and.vhd
  entity and is generic ( gate_delay : Time := 2 ns );

xor.vhd
  entity xor is generic ( gate_delay : Time := 3 ns );

I gave four files.
My question is, how much should one wait to see correct result ? In other words, what is the total time delay for each file?

A: Since the longest path in a half adder is only one gate, the delay of the entire circuit will be equal to the gate delay. In this case, the gate delay is 6 ns. The default values for gate_delay of both gate entities are overridden in the instantiations you write.
Note that your code will not work since and and xor are reserved words in VHDL. You will need to rename to something like and_gate and xor_gate
Another side note: VHDL code like this is only used for gate level simulation with timing annotations, usually after synthesis and place and route. If you want to write an adder in VHDL, you should write a <= b + c;


text:
Q: how can I validate if there are no errors when executing SaveChangesAsync? I am testing a scenario where I am trying to save a duplicate element and it shows me the following error since the element must be unique (the name and fields of my table are in Spanish, for the example of my code, I preferred to put it in English):
`Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert duplicate key row in object 'dbo.Generos' with unique index 'IX_Generos_Nombre'.` **The duplicate key value is (Terror).**`
The statement has been terminated.
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__164_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---`

I want to do that if there is any error to save, I can customize the output message and not show the error message.
I also don't understand why the result variable is taken as an int.
[HttpPost]  // I am sending { Nombre: 'Terror'}
public async Task<ActionResult> Post([FromBody] GenreCreationDTO genreCreationDTO)
{
    var entity = mapper.Map<Genre>(genreCreationDTO);
    context.Add(entity);
    var result = await context.SaveChangesAsync(); ///////////////////// problem in this line
    //result is taken as int, why?
    if (!result)
    {
     //show my custom message
    }
     return Ok();
}

A: For a simple application, you could query the database before the insert to check if the name (or any other fields you want to be unique) already exists, and if there are results that match that criteria, then return some type of response telling so. Something like this
[HttpPost]
public async Task<ActionResult> Post([FromBody] GenreCreationDTO genreCreationDTO)
{
    var entity = mapper.Map<Genre>(genreCreationDTO);
    var matches = await context.Where(e => e.Name == entity.Name).Select(e => 1).ToListAsync();
   if(matches.Count == 0)
   {
       context.Add(entity);
       var result = await context.SaveChangesAsync();
       return Ok();
   }
   else
   {
     // show custom message
   }
}

However, keep in mind the above approach will not work 100% for an application used by many clients at the same time. The problem is that there is no guarantee that the thread a request is running on will be suspended after checking if that name already exists but before the insert is done, and while that thread is suspended, another request comes in with the same name and insert the data into the database. Possibly the best thing to do is to handle the exception you are currently receiving in addition to check before the insert if that data already exists. The exception should be rare, it should only occur in a situation similar to the one described above, so, you can choose to not handle it and let the client receive a 500 error, then when the request is retried they will see why the prior request failed, or handle it and determine if the exception indeed occurred because of duplicate data.
As to why the result of SaveChangesAsync is an int, that represents the number of affected rows. In your case, how many rows were inserted.
EDIT: Modified query to include a projection to do SELECT 1 .... instead of SELECT *


text:
Q: Merging exists and not exists into one query - oracle magic In a WHERE part of query we have
SELECT * FROM SomeTable st
WHERE
NOT EXISTS
  (SELECT 1 FROM Tab t1 WHERE t1.A = st.A OR t1.B = st.A)
OR EXISTS
  (SELECT 1 FROM Tab t2 WHERE (t2.A = st.A OR t2.B = st.A) AND t2.C IS NULL)

Seems like a good candidate for merging...
But I'm staring on that for an hour without any idea.
Would you have some thoughts?
Thanks,

A: SELECT distinct st.*
FROM SomeTable st
     left outer join Tab t
     on st.a in (t.a,t.b)
WHERE t.c is null

Sometimes the simplest answer is to use a join rather than an exists.

A: Try:
NOT EXISTS (SELECT 1 FROM Tab WHERE (Tab.A = @Id OR Tab.B = @ID)
            AND (Tab.C is null OR Tab.C != @Var))

A: I think I've got it
SELECT * FROM SomeTable st
WHERE
0 = (SELECT SUM (NVL(t1.C,0) FROM Tab t1 WHERE t1.A = st.A OR t1.B = st.A)

What do you think?
Of course that will work only for case where 'C' is expected to be NULL.
If we are expecting some value, I think that the check
@SomeValue IN (SELECT t1.C FROM Tab t1 WHERE t1.A = st.A OR t1.B = st.A)

Will do?

A: It looks as though you're trying to return all SomeTable values where there's no corresponding value on Tab where C is not null - in which case, the following should work:
SELECT * FROM SomeTable st
WHERE NOT EXISTS
  (SELECT 1 FROM Tab t1 WHERE (t1.A = st.A OR t1.B = st.A) AND t2.C IS NOT NULL)

However, that's not exactly what your existing query does - in your query, if there are two corresponding records on Tab, where one record has a non-null value for C and the other is null, your query will return a corresponding row, but my query won't.


text:
Q: Can you set default Schema for SQL 2008 Query I have a schema called application.  Is there a way that, rather than using the syntax
SELECT * FROM application.table

I can set the default schema so that I can just use
SELECT * FROM table

It would be the same idea as a using statement I suppose.

A: The default schema for all sql server users is "dbo", You can alter the default schema for a user by using commands ALTER USER
ALTER USER UserName WITH DEFAULT_SCHEMA = application;

A: It will be great to have a use statement for schemas.
You can vote the feature suggestion on Microsoft connect.


text:
Q: Gerrit Rest API not working when query string contains Hour, Minute, Second With curl command and Gerrit Rest api, querying like below does not work well.
(Not OK)
/changes/?q=after:"2018-12-03 09:00:00"
Surely, without HH:MM:SS part, it works well.
(OK)
/changes/?q=after:"2018-12-03"
I found similar question in here: Gerrit time search operators is not working when specify to second
But the answer does not working.
Gerrit version is v2.13.7.
Thanks.

A: Try replace the space for "%20"

A: I found a solution.
Replace the space for "%20" is not enough.
Quotation mark also should be encoded as "%22".
If you add time zone also, you should encode "+" as "%2B" too.
Here is full working query string. Below query fetch changes which are updated after 2018-12-03 09:00:00.000 +0900.
/changes/?q=after:%222018-12-03%2009:00:00.000%20%2B0900%22

Thanks.


text:
Q: Remove values in a cell based on a string part I have a column in Excel that contains a series of comma delimited values.  The number of values in each row is different and the values I'm searching for can be in different positions within the cell.  I would like to remove some of those values based on based on a string part.
Example cell:
2006CE3, 2007CE3, 2012CE1, 2012CE3, 2013CE1, 2013CE3, 2014CE2, 2015CE3, 2016CE2, 2019FA, 2020SP

Specifically, remove all values containing "CE".  In the example above, I would like to remove 2006CE3, 2007CE3, 2012CE1, 2012CE3, 2013CE1, 2013CE3, 2014CE2, 2015CE3, 2016CE2, and leave 2019FA, 2020SP

A: To do this with a formula one will need TEXTJOIN:
=TEXTJOIN(", ",TRUE,IF(ISNUMBER(SEARCH("CE",FILTERXML("<z><y>"&SUBSTITUTE(A1,",","</y><y>")&"</y></z>","//y"))),"",TRIM(FILTERXML("<z><y>"&SUBSTITUTE(A1,",","</y><y>")&"</y></z>","//y"))))

A: Please try this formula solution of which using TEXTJOIN function available for Office 365
In B2, enter formula :
=TEXTJOIN(", ",1,INDEX(FILTERXML(""&SUBSTITUTE(A2,", ","")&"","//b[not(contains(.,'CE'))]"),0))


text:
Q: 100% of remaining space after setting a fixed header I'm trying to layout my small React project.
Here's the link to codesandbox: https://codesandbox.io/s/szkola-reacta-44-kalkulator-wydatkow-rvh5t?file=/src/styles.css
What I want to achieve is login page, which will (after login) show expenses and incomes. I want to content below header to occupy the whole remaining space, but the whole page shouldn't be scrollable. I've tried two approaches:

*

*Firstly I've set width of 100vh to an App component, then I've set .main to 100%, to occupy the rest of remaining space after setting up the header. I've found out that it'll set 100vh as well, so it'll be scrollable and I don't want it to be.

*Secondly I've made a header fixed, but then my whole form isn't centered, because header isn't in the document flow.
I prefere to find solution for the first approach, in the second one I know I can calc it somehow (but I need guidance), however the first one looks more straightforward for me, but I'm missing something.
In general, no matter how, but I want to have a header, which will be always in the same place, a dynamically changing content which will occupy remaining space and the whole app should occupy 100vh to prevent from scrolling.


text:
Q: Calling methods in a Java Fx ActionEvent I'm new to JavaFX and I want to create a view class that will call methods in a Controller when an event is triggered by a button push. My code is below:
package spacetrader.menu;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import spacetrader.Window;

public class MenuView implements Initializable {
    public Window window;
    public MenuCtrl menuCtrl;

    @FXML
    Button start;
    @FXML
    Pane background;
    @FXML
    Button exit;

    public MenuView() {};

    public MenuView(Window aWindow, MenuCtrl aMenuCtrl) {
        window = aWindow;
        menuCtrl = aMenuCtrl;
    }

    void renderMainMenu() {
        try {
            window.loadFXML(new FXMLLoader((getClass().getResource("MainMenu.fxml"))));
        } catch (IOException ex) {
            Logger.getLogger(MenuView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        start.setOnAction((ActionEvent event) -> menuCtrl.newGame());
        exit.setOnAction((ActionEvent event) -> menuCtrl.closeApplication());
    }
}

This compiles, but when I run it and press the button I get a null pointer exception on the lambda expressions. The exception refers to "menuCtrl." How should I be setting up my program to make the button call menuCtrl.newGame()?
Here's what I've tried already:

*

*I've moved the setOnAction commands to between the various methods.

*Replaced the calls to menuCtrl methods with System.out.prinln statements to confirm that this works. It does.

*I've replaced menuCtrl methods with System.out.println(this) to ensure there isn't a scoping problem. It prints "spacetrader.menu.MenuView@74f51979" as expected.

*Converted the Lambda expressions to anonymous inner classes

*Used a block as the lambda's body

A: Your setup is unusual, in that your controller class (which you've called MenuView) is the class that calls (indirectly, via your Window class) the FXMLLoader's load method. The FXMLLoader parses the FXML, sees the fx:controller attribute, and consequently instantiates it using the default (no-argument) constructor. (I am making an assumption here that you don't call setController or setControllerFactory on the FXMLLoader in Window.loadFXML.) Thus you have two controller instances: the one which created the loader (for whom the initialize() method is never called and the @FXML-annotated fields are never injected), and one which was created by the FXMLLoader (which called the no-argument constructor, so the window and menuCtrl fields are not initialized for that instance).
You should either refactor this, so that the FXMLLoader is created and passed to the Window class for loading elsewhere (i.e. without instantiating the controller), or you should explicitly set the controller on the FXMLLoader. You can achieve the latter in two steps:

*

*Remove the fx:controller attribute from MainMenu.fxml

*Set the controller explicitly to the instance already created in your renderMainMenu method:

--
FXMLLoader loader = new FXMLLoader((getClass().getResource("MainMenu.fxml"))) ;
loader.setController(this);
window.loadFXML(loader);

A: You may try using Scene Builder where drag and drop feature is available and you can design a screen in seconds. In code section you just have to declare method name and implement that method in code handler class.
You can get it from here

A: You have two constructors. My guess is that you're loading an FXML somewhere which will instantiate your controller using the no-args constructor. In this case menuCtrl is not initialized.
If you're instantiating menuCtrl in the FXML, then add a @FXML annotation to the field.