text:
Q: Regex strong password the special characters I am currently making some tests with regex. I had an exercise which requested to check for a strong password, which means it should have: at least one number,one lowercase letter, one uppercase letter, no spaces, and at least one
character that is not a letter or number. And it should be between 8-16 characters.
I wrote this code:
     <?php

  $passwords = array("Jtuhn", "12J@k", "jok", "Joan 12@45", "Jghf2@45", "Joan=?j123j");

  foreach($passwords as $pass)
  {
    ///^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$/
    if(strlen($pass) >= 8 && strlen($pass) < 17)
     {
       if(preg_match("/^\w*(?=\w*\d)(?=\w*[A-Z])(?=\w*[^0-9A-Za-z])(?=\w*[a-z])\w*$/", $pass) )
        echo "$pass => MATCH
";
       else
        echo "$pass => FAIL
";
     }
    else
      echo "$pass => FAIL(because of length)
";
  }
 ?>

The last two should match but they fail. I think the problem stands at
(?=\w*[^0-9A-Za-z])

which is supposed to be the pattern match to have at least one character that is not a letter or a number, but I cant figure out why.
I know this strong password is solved in internet but thats not my issue. My issue is why that part of work dont do what is supposed to do.

A: You can try this:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,16}$

It covers all your requirment
Explanation

*

*(?=.*\d) Atleast a digit

*(?=.*[a-z])  Atleast a lower case letter

*(?=.*[A-Z]) Atleast an upper case letter

*(?!.* ) no space

*(?=.*[^a-zA-Z0-9]) at least a character except a-zA-Z0-9

*.{8,16}  between 8 to 16 characters

Sample Code:
<?php
$re = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,16}$/m';
$str = 'Jtuhn
12J@k
jok
Joan 12@45
Jghf2@45
Joan=?j123j
';

preg_match_all($re, $str, $matches);
print_r($matches);

?>

Run it here

A: ^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}\S+$

//The rule is at least
   one upper case, one lower case, one digit[0-9],
   one special character[#?!@$%^&*-] and the minimum length should be 8.

A: You could split your regex into different checks.
It will allow you to write more readable conditions and to display specific error messages. Although, regexp patterns will be easier to write and to understand.
i.e. :
$errors = array();
if (strlen($pass) < 8 || strlen($pass) > 16) {
    $errors[] = "Password should be min 8 characters and max 16 characters";
}
if (!preg_match("/\d/", $pass)) {
    $errors[] = "Password should contain at least one digit";
}
if (!preg_match("/[A-Z]/", $pass)) {
    $errors[] = "Password should contain at least one Capital Letter";
}
if (!preg_match("/[a-z]/", $pass)) {
    $errors[] = "Password should contain at least one small Letter";
}
if (!preg_match("/\W/", $pass)) {
    $errors[] = "Password should contain at least one special character";
}
if (preg_match("/\s/", $pass)) {
    $errors[] = "Password should not contain any white space";
}

if ($errors) {
    foreach ($errors as $error) {
        echo $error . "\n";
    }
    die();
} else {
    echo "$pass => MATCH\n";
}

Hope it helps.

A: Use this simple regex to test a strong password
/(?=^.{8,}$)(?=.{0,}[A-Z])(?=.{0,}[a-z])(?=.{0,}\W)(?=.{0,}\d)/g

Javascript:
var password = "Abcdef@1234"
var passwordRegex = /(?=^.{8,}$)(?=.{0,}[A-Z])(?=.{0,}[a-z])(?=.{0,}\W)(?=.{0,}\d)/g

var isStrongPassword = passwordRegex.test(password)

console.log(isStrongPassword, "")

*

*Minimum length 8 characters

*at least 1 uppercase

*at least 1 lowercase

*at least 1 special character

*at least 1 digit

A: ^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[special characters]).{8,16}$

Add special characters as per requirement.
Above code check following conditions

*

*At least 1 uppercase character

*At least 1 lowercase character

*At least 1 digit

*At least 1 special character

Click here to test

A: Use the Below Code In PHP For a strong Password.
Password must have 8 characters and a mix of letters (uppercase and lowercase), numbers, and symbols :
$pswrdChk = 'Test@123';

if (!preg_match('/^(?=.*[\W])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,50}$/', $pswrdChk))
{
echo "Use at least 8 characters and a mix of letters (uppercase and lowercase), numbers, and symbols.";
}
else
{
  echo "Password is Valid";
}


text:
Q: Send email at specified time I would like to send emails at a specified time.
I found this, but it is too complex for me to setup.
https://unix.stackexchange.com/questions/228105/sending-email-out-at-a-specific-time
Any alternatives especially a GUI method?

A: the simpliest way is to send emails at a specific time using the email client "Thunderbird" and the addon "Send later" https://addons.mozilla.org/en-US/firefox/addon/send-later-3/
Important: Thunderbird should be active at the requested time/date. If not the addon will send the Email the next time you start the client...
Another method (out of the Ubuntu-Universe) is using the Browser "Google Chrome" and the extension: "Right Inbox for Gmail" from the Chrome Web Store. With this method even if the computer is not running the mail will be sent at the specified time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic header content in Angular Material Table? Im trying to add a dynamic header to my angular material table, but I cant figure out how to do it. I want the month to be in the header in this case.
<ng-container matColumnDef="month">
    <th mat-header-cell *matHeaderCellDef> {{element.month}} </th>
    <td mat-cell *matCellDef="let element"> {{element.hours}} </td>
</ng-container>

I also tried *matHeaderCellDef="let element" but its not working. I keep getting the error:
TypeError: Cannot read property 'month' of undefined
Any ideas?

A: You can't define variable like *matHeaderCellDef="let element" because the header text must not be undefined when the table is initialised.
You need to ensure the table is not initialised until you get the month value.
e.g. use *ngIf="data" so that the table is not initialised until table source has values.
Assuming month value is loaded through HTTP and stored in retrievedMonth,
You can populate the header dynamically like so:
<th mat-header-cell *matHeaderCellDef> {{retrievedMonth}} </th>
If the month value is in an array or in the same data source as the table, you need to put some filtering logic to extract the month value.


text:
Q: Comparing performance between custom implemented LINQ methods and the original I was just messing around implementing some of LINQ methods when I find out that some of the custom implementation actually run faster than the original even though the implementation is similar. Dealing with lists instead of arrays, makes the difference of speed even bigger to the side of the custom methods!
public static class CustomLINQ
{
    public static IEnumerable<T> WHERE<T>(this IEnumerable<T> items, Func<T, bool> predicate)
    {
        foreach (var item in items)
            if (predicate(item))
                yield return item;
    }

    public static IEnumerable<TReturn> SELECT<TSource, TReturn>(this IEnumerable<TSource> items, Func<TSource, TReturn> projection)
    {
        foreach (var item in items)
            yield return projection(item);
    }
}

public class Program
{
    static int loops  = 1000000;
    static int nTests = 100;

    static void Measure(string msg, Action code)
    {
        long total = 0;
        for (int i = 0; i < nTests; i++)
        {
            var w = Stopwatch.StartNew();
            for (int j = 0; j < loops; j++)
                code();
            total += w.ElapsedMilliseconds;
        }
        Console.WriteLine("(avg) {0} \t {1}ms", msg, total / nTests);
    }

    private static void Main(string[] args)
    {
        var sample = new List<string> { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight" };
        //var sample = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight" };

        Measure("Linq Where", () =>    { var res = sample.Where(x => true && x.Length % 2 == 0); });
        Measure("Custom Where", () =>  { var res = sample.WHERE(x => true && x.Length % 2 == 0); });
        Measure("Linq Select", () =>   { var res = sample.Select(x => x.Length);                 });
        Measure("Custom Select", () => { var res = sample.SELECT(x => x.Length);                 });

    }
}

Sample Times:
(using a list)
(avg) Linq Where         102ms
(avg) Custom Where       62ms
(avg) Linq Select        122ms
(avg) Custom Select      59ms

(using an array)
(avg) Linq Where         75ms
(avg) Custom Where       60ms
(avg) Linq Select        77ms
(avg) Custom Select      60ms

The custom Any and All and the originals also performed slightly a bit differently although the implementation is almost exactly the same, I'm only interested in Where and Select for now
My questions:

*

*This makes me kind of doubt the way I'm measuring this, am I doing it right? is there something wrong with it?

*Why does this simple implementation seem to perform better than the originals? (almost twice as fast with lists and slightly faster with arrays)

*When dealing with lists, why is the difference in performance between the custom implementation and LINQs bigger than it is when dealing with arrays?

A: You aren't actually iterating the sequences. All you are testing is enumerator creation performance; not the actual loop. Basically, the test is meaningless.
For info, I tweaked this to:
Measure("Linq Where", () => { sample.Where(x => true && x.Length % 2 == 0).Consume(); });
Measure("Custom Where", () => { sample.WHERE(x => true && x.Length % 2 == 0).Consume(); });
Measure("Linq Select", () => { sample.Select(x => x.Length).Consume(); });
Measure("Custom Select", () => { sample.SELECT(x => x.Length).Consume(); });

using:
public static void Consume<T>(this IEnumerable<T> source)
{
    using(var iter = source.GetEnumerator())
    {
        while (iter.MoveNext()) { }
    }
}

(which just burns through an iterator manually), changed loops to 500000, and retried (release mode, console, etc):
(avg) Linq Where         139ms
(avg) Custom Where       174ms
(avg) Linq Select        132ms
(avg) Custom Select      174ms

LINQ wins.

A: As noted by another your test is flawed because none of the code is executed except the enumerator creation (you aren't materializing the sequences). But it's also flawed for a second reason, you're testing many times sure, but on extremely tiny sequences! Try the same tests on a lot more elements!


text:
Q: Can relational algebra/calculus proofs be used to test/verify SQL? Is it feasible or even possible to use relational algebra and/or relational calculus in the form of proofs to test/verify the correctness of SQL statements, functions, and stored procedures?
It seems to me like it should be at least possible, but I don't know if there's a detail I'm missing that makes a 1:1 mapping between the proof and the code incorrect.
Have any of you tried a method like this? Did it work? What were your experiences like?

A: There are some known mapping rules between relational algebra operators and SQL statements. For example, the Sigma operator maps to a SELECT statement, there's a one-to-one mapping for the join operators, Delta maps to selecting a subset of columns, etc.

Is it possible to use relational algebra to verify the correctness of SQL statements?

Yes, it is possible. Of course you'll need to have a clear schema of the database with all the relationships, foreign keys, etc. In some cases it's even easier to manipulate relational algebra statements than SQL statements (there are proven transformation rules for modifying and simplifying statements).
But on the other hand, I don't think that verifying statements using relational algebra is much easier than testing SQL statements, especially when you have a database ready where you can execute the queries and see the results.


text:
Q: How to read excel xml spreadsheet data in Classic ASP I thought it would be a straightforward xml load and loop, but for some reason I can't read anything out of an Excel XML spreadsheet.
The content of the Excel spreadsheet, which appears to be a standardised output, is as follows:
<?mso-application progid="Excel.Sheet"?>
<Workbook
    xmlns="urn:schemas-microsoft-com:office:spreadsheet"
    xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel"
    xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
    xmlns:html="http://www.w3.org/TR/REC-html40"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:user="urn:my-scripts">
    <DocumentProperties
        xmlns="urn:schemas-microsoft-com:office:office">...
    </DocumentProperties>
    <OfficeDocumentSettings
        xmlns="urn:schemas-microsoft-com:office:office">...
    </OfficeDocumentSettings>
    <ExcelWorkbook
        xmlns="urn:schemas-microsoft-com:office:excel">...
    </ExcelWorkbook>
    <Styles>...</Styles>
    <Worksheet ss:Name="Sheet1" ss:Protected="1">
        <Names>
            <NamedRange ss:Name="Print_Titles" ss:RefersTo="=Sheet1!C2,Sheet1!R7"/>
        </Names>
        <Table ss:ExpandedColumnCount="34" ss:ExpandedRowCount="32" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="13.2">
            <Column ss:Hidden="1" ss:Width="175.2"/>
            <Column ss:Width="250.20000000000002"/>
            <Column ss:Width="60" ss:Span="31"/>
            <Row ss:AutoFitHeight="0" ss:Height="150" ss:StyleID="s67">...</Row>
            <Row ss:Height="15">
                <Cell ss:StyleID="s69">
                    <Data ss:Type="String">W89231</Data>
                </Cell>
                <Cell ss:StyleID="s70">
                    <Data ss:Type="String">Tom Brown</Data>
                    <NamedCell ss:Name="Print_Titles"/>
                </Cell>
                <Cell ss:StyleID="s69">
                    <Data ss:Type="String">1E+</Data>
                </Cell>
                <Cell ss:StyleID="s69">
                    <Data ss:Type="String">1m</Data>
                </Cell>

etc etc
Having read that byTagName isn't the best method I tried the following singlenode code first:
strFilename = "1B.xml"
Set oXMLDoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
oXMLDoc.async = False
oXMLDoc.Load (Server.MapPath(strFilename))
Set NodeList = oXMLDoc.documentElement.selectNodes("Workbook/Worksheet")
For Each Node In NodeList
 Response.Write Node.selectSingleNode("row/cell/data/text()")
Next

But absolutely nothing happens.
So I went back to the tried and trusted byTagName and tried the following:
strFilename = "1B.xml"
Set oXMLDoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
oXMLDoc.async = False
oXMLDoc.Load (Server.MapPath(strFilename))
Set oRows = oXMLDoc.documentElement.getElementsByTagName("Row")
Response.Write oRows.length

The oRows.length feedback is zero
I just can't seem to get into the DOM even though its a standard Excel XML spreadsheet format.
I'd really appreciate it if somebody could please explain how I can read through the rows and extract the necessary data values.
Regards
Tom

A: Managed to find out that it's all about the namespaces.
By adding the below lines:
Set oXMLDoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
 oXMLDoc.setProperty "SelectionLanguage", "XPath"
 oXMLDoc.setProperty "SelectionNamespaces", "xmlns:myns='urn:schemas-microsoft-com:office:spreadsheet' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet' xmlns:html='http://www.w3.org/TR/REC-html40' xmlns:msxsl='urn:schemas-microsoft-com:xslt' xmlns:user='urn:my-scripts'"

I could then reference the tags within the xml as follows:
Set oXMLRows = oXMLDoc.selectNodes("/myns:Workbook/myns:Worksheet/myns:Table/myns:Row")

and the XML parsing could then begin!! :0)
Regards
Tom


text:
Q: git local repository on different directory error: git did not exit cleanly (exit code 1) I am trying to set up origin/master git repository on shared folder. But I keep getting error:

git did not exit cleanly (exit code 1)

When I try to "push" from my repo to the origin (share folder).
I am using bash and TortoiseGit and gitbash.
Thanks

A: You should push to a bare repository.
i.e. The directory ends with .git and initialized with git init --bare.
mkdir abc.git
cd abc.git
git init --bare

Otherwise, you receive error message receive.denyCurrentBranch (non-bare repository).
Pushing to non-bare repository is not recommended.


text:
Q: Display bordered tiles in ListBox with large number of items in WPF I'm trying to build a GUI similar to the one on the first screenshot:

Basically it's a view of tiles, displayed in a bordered grid that dynamically changes number of columns as the window is resized. The items are selectable. Those may look like pictures, but they are just Unicode characters.
I've made a List of custom objects, and bound the list to a ListBox control successfully. Naturally, this gave me a vertically stacked list of characters.
So I googled some, and found out I could set a custom ItemsPanelTemplate for the list box:
<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
       <WrapPanel Margin="0"/>
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>

The result was the following:

In order to set the border and size of the tiles, I've also added an ItemTemplate:
<ListBox Margin="0,0,0,0" Padding="0,0,0,0" Grid.Row="0" Grid.Column="0" x:Name="tw"
            SelectionChanged="tw_SelectionChanged"
            ScrollViewer.HorizontalScrollBarVisibility="Disabled"
            ScrollViewer.VerticalScrollBarVisibility="Visible">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Margin="0,0,0,0"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Label
                        Padding="0,0,0,0"
            Margin="0,0,0,0"
                        Width="50"
                        Height="50"
                        FontSize="20"
                        Background="White"
                        HorizontalAlignment="Left"
                        HorizontalContentAlignment="Center"
                        VerticalContentAlignment="Center"
                        BorderThickness="1"
                        BorderBrush="Black"
                    Content="{Binding Path=LiteralString}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

The result was the following:

 This is as far as I got.
The first problem is, as you can see, there are spaces between the tiles that I can't get rid of. You'll notice in the markup I've tried manually setting Margin and Padding to 0 wherever possible. The spaces are still there.
The second problem is, you can't really see which item is selected. The 3rd character from the bottom and 2nd from the right is selected, but the blue color is covered by the label. You can only just see it in the space to the left of the character. I have no idea how to fix this.
Another potential problem is performance. The view will eventually have filters, but when all the filters are off, there are some 6500 items to display. When I had just a basic ListBox, the application was taking up some 28MB of RAM while it was running. When I added the ItemsPanelTemplate with the WrapPanel, memory usage jumped to about 136MB. When I added an ItemTemplate with Labels, memory usage jumped to 183MB, and what's worse, the window now takes much longer to load.
I've tried replacing Labels with TextBlocks, since I've read they're much more lightweight. The thing got faster, and memory usage dropped back to around 130MB, but TextBlocks are no good. I can't center text in them, or give them borders. And as you can see in the screenshot, the selected item just gets messed up:

Granted, I have a slow computer, and 183MB is not life-ending, but still, it's a bit inefficient. I intend to put a lot more functionality in this application, and if this one thing takes up so much RAM, the resulting application will likely be an unusable resource vampire. Also, I believe the application I'm mimicking is also written in .NET, (although I'm not sure if it's WPF) and that one only uses 17.5MB of RAM while displaying the view.
Is there another way to do this, one that's both more efficient and more easily customizable?
Thank you.
EDIT:
I have found a slightly better way. I removed the ItemTemplate altogether, and instead I'm using ItemContainerStyle:
 <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Style.Setters>
                        <Setter Property="BorderBrush" Value="Black"/>
                        <Setter Property="BorderThickness" Value="1"/>
                        <Setter Property="Width" Value="50"/>
                        <Setter Property="Height" Value="50"/>
                        <Setter Property="FontSize" Value="20"/>
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="VerticalContentAlignment" Value="Center" />
                    </Style.Setters>
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True" >
                            <Setter Property="FontWeight" Value="Bold" />
                            <Setter Property="Background" Value="SteelBlue" />
                        </Trigger>
                    </Style.Triggers>

                </Style>
            </ListBox.ItemContainerStyle>

This produces much better results. There are no visible spaces between the tiles, and I can customize the look of both selected and deselected tiles.

The only thing I don't know how to do is have a border line with the thickness of 1 pixel. I get two lines with thickness of 1 touching, resulting in a thickness of 2. I've tried setting margins and padding to 0 and -1. No luck. Curiously, setting BorderBrush to Black and BorderThickness to 0.5 doesn't produce a combined black line with thickness of 1, but a grey line with thickness of 2.
Memory usage dropped somewhat to about 150MB compared to when I was using labels, but load times are still atrocious, so I'm still looking for a better solution.
EDIT 2:
I played with the margins for a while, and I finally nailed it. I got the correct border thickness by setting the margin of the ListBoxItem to -0.5, squishing the tiles ever so slightly together. I would like to keep the question open, so that hopefully somebody will present a more efficient solution. The UI is responsive once it's running, but the load time is terrible. During the use of my application the ListBox will be repeatedly re-filled, as filters are adjusted and queries are made. I would like that to happen quickly. Also, memory usage is unnecessarily high in my opinion.

A: As i do not have enough rep to post a comment, will try to answer, or at least point to correct direction.
1) The reason you get Thickness of 2 is that adjacent borders join their respective thicknesses. And -0.5 Margin you use makes them intersect making resultant thickness of 1. Instead you can try to set border thickness of Right and Bottom side, like:
<Setter Property="BorderThickness" Value="0,0,1,1"/>

Which means LeftSide=0, Top=0, RightSide=1, Bottom=1 thick. So leftmost items won't have left border, and topmost items won't have top border. And as a result adjacent borders will not marge, doubling their thickness.
2) And for excessive memory usage and overall slow performance. When you use WrapPanel for ItemsPanel you are discarding UI Virtualization. Because usually non UI computation doesn't take much time first consideration is UI performance. Try to load your data and make computations without UI, I think difference will be obvious.
  I suggest you use some sort of VirtualizingWrapPanel for ListBox ItemsPanel. Personally I use this one with corrections suggested by more experienced coders:
Original implementation
First correction
Second correction


text:
Q: Bootstrap Glyphicons not showing locally I'm trying to load a Bootstrap buttons that has a Glyphicon, but the icon won't show. The button picks every other CSS attached to it except the icons. Is my approach wrong in any way?
What I want >>>:

What I get instead:

<link rel="stylesheet" href="../../bootstrap-3.3.5-dist/css/bootstrap.min.css">

<link rel="stylesheet" href="../../bootstrap-3.3.5-dist/css/bootstrap-theme.min.css">

        <button type="button" class="btn btn-default" aria-label="Left Align"></button>
        <button type="button" class="btn btn-default" aria-label="Center Align"></button>
        <button type="button" class="btn btn-default" aria-label="Right Align"></button>
        <button type="button" class="btn btn-default" aria-label="Justify"></button>

A: The folder structure you have is misconfigured as Boostrap expects the font files to exist in a folder one up and then down again in a folder called fonts, for example: ../fonts/xxxx. So if you have the Bootstrap files in the root, that will not work. Move your Bootstrap files into their own directory so your structure looks something like this:
root
  ----bootstrap
    ----bootstrap.css
    ----bootstrap.js
  --fonts
    --glyphicons.*

A: try requiring the jquery library before bootstrap, that what I did and it worked fine !


text:
Q: IIS7 and Enforce lowercase URLs I tried to use option in iis7 Enforce lowercase URLs, but when i enabled it all images that had *.JPG extension (uppercase) stopped server. in prev version of iis it was ok when using upper and lower cases, it returned same source
may i fix it? or should i create rule for each extension like (jpeg, jpg, gif...)

A: I was just reading an article on writing rules, from Scott Gu
Tips/Trick: Fix Common SEO Problems Using the URL Rewrite Extension
He talks about the issue of excluding static files (.jpeg, .jpg, .gif, etc.) from the lowercase rewrite, and shows how you can add conditions to exclude files.  Another article is where I found the condition for excluding more than just Scott's example
Mike's Umbraco blog - URL Rewriting and SEO
He adds the condition:
<add input="{URL}" pattern="^.*\.(axd|css|js|jpg|jpeg|png|gif)$" negate="true" ignoreCase="true" />

I hope this helps you in future rewrites.


text:
Q: Why does GeoServer WCS 1.1.1 Returns NullPointerException for GetCoverage? I'm making a request for my WCS service in the 1.1.1 version of the protocol.
I should note that the same area is working correctly with 1.0.0 and also with 2.0.1.
The geoserver version I'm using is 2.21.0
The request is below:
http://GEOSERVER_IP:8080/geoserver/wcs?service=WCS&version=1.1.1&request=GetCoverage&Identifier=cite:4326oparea&format=geotiff&crs=EPSG:4326&width=256&height=256&BoundingBox=-117.421875,32.54681317351515,-117.0703125,32.84267363195431

That makes the server respond with a Null error:
<ows:ExceptionReport xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.1.0" xsi:schemaLocation="http://www.opengis.net/ows/1.1 http://54.247.181.28:8080/geoserver/schemas/ows/1.1.0/owsAll.xsd">
<ows:Exception exceptionCode="NoApplicableCode">
<ows:ExceptionText>java.lang.NullPointerException</ows:ExceptionText>
</ows:Exception>
</ows:ExceptionReport>

Am I doing something wrong in the request, or is that a bug on Geoserver's side? I scoured their documentation and couldn't find much to go on.

A: A request that works with the GeoServer demo layer nurc:Img_Sample
http://localhost:8080/geoserver/wcs?service=WCS&version=1.1.1&request=GetCoverage&Identifier=nurc:Img_Sample&format=image/tiff&crs=EPSG:4326&BoundingBox=20.7052,-130.85168,54.1141,-62.0054,urn:ogc:def:crs:EPSG::4326
Notice the axis order in BoundingBox that must be latitude-longitude for urn:ogc:def:crs:EPSG::4326.
An .eml file with a .xml part and .tif part is returned.


text:
Q: Set a word in a text file and replace or delete its value using Batchfile (User Input) I got an error when i run my code.
Its like i got a textfile in C:\Users\Administrator\Desktop\ComOrg
and in, it has a sentence in there and i need to change the value of that word
Like:
Run:
The word inside the textfile here
Enter an input [R]-Replace [D]-Delete :
if  i click R
Enter the word that you want to replace :
lets say i type "Word"
and if i type the word
Enter the word: the word the you will replace
Output = Change the value of the word in a sentence
Here's my code:
@echo off
setlocal enabledelayedexpansion

SET /P _inputname= Please enter "1" to view the text :
    if "%_inputname%"=="1" type "C:\Users\Administrator\Desktop\ComOrg\Sentence.txt "
echo off

echo off
SET /P _name= Please enter an Input [A]-ERASE [B]-DELETE :

    IF "%_inputname%"=="A" SET /P _inputname= Pick a word the you want to replace :
        IF  "%_name%"=="love" SET /P _inputname= Type the word :
            echo I %_name% batch script
                @echo I %_name% batch script > C:\Users\Administrator\Desktop\ComOrg\Sentence.txt

endlocal

A: for replacing parts of the string, use the set command (see set /? for info):
set "string=The mouse eats the cat"
echo %string%
echo %string:mouse=dog%

To replace with variables, you need delayed expansion:
setlocal enabledelayedexpansion
set "string=The mouse eats the cat"
set old=cat
set new=cheese
echo !string:%old%=%new%!


text:
Q: Detecting when the mouse has 'stopped moving' in JavaFX using FXML I want to be able to detect when a the mouse is moving and when it is not moving over an AnchorPane using JavaFX.
I currently have a 'Mouse Moved Event' on my pane that outputs some text when the mouse is moved, but would like to also include some output when the mouse isn't moving.

I am stumped on how I can achieve the second half of the problem while still keeping it relatively simple.
Below outputs "moving" whenever the mouse is moved but when the mouse stops, nothing happens. I can see this is because checkMovement is only called when it moves.
Is there such a thing as an inverse function or similar - something that will do the opposite?
I do believe I can achieve what I want using specific event handlers and/or timers, but this overly complicated for something that seems quite simple. Am I missing something totally obvious here??
I am only quite new to using FX, so feel free to point out anything I should be doing a different way.
EDIT:
I did forget to specify that I am using FXML to define the controls.
Do I need to put this process within the controller(AppController.java) or for 'ease-of-use' sake just leave it in Main.java? How would I even go about this/is it possible?
Obviously, the mouseMovementMethod needs to be modified.
AppController.Java
public class AppController implements Initializable{
    boolean moved = false;

    @FXML
    private AnchorPane anchorPane;

    @FXML
    private ImageView killpic;

    @FXML
    private ImageView processpic;

    @FXML
    private Text exit;

   @FXML
   private Button processAnimalButton;

   /*
    * ...Other Variables
    */

    @FXML
    void mouseMovedMethod(Event event){
        //Mouse Movement Event
    }

    @FXML
    void closeMenu(Event event) {
        Stage stage = (Stage) exit.getScene().getWindow();
        stage.close();
    }

    @FXML
    void selectProcess(Event event) {
        Image killimg = new Image("/images/knife_blood.png");
        Image proimg = new Image("/images/p_selected.png");
        killpic.setImage(killimg);
        processpic.setImage(proimg);
    }

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        Image killimg = new Image("/images/knife_blood_selected.png");
        Image proimg = new Image("/images/p.png");
        killpic.setImage(killimg);
        processpic.setImage(proimg);
    }

}

Main.java:
//*Required imports*//

public class Main extends Application {
    Stage thestage;

    @Override
    public void start(Stage primaryStage) {
        try {
            AnchorPane root = (AnchorPane)FXMLLoader.load(getClass().getResource("popup.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            thestage = primaryStage;
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

A: The reason this is not as simple as you think it should be is that the concept of "mouse not moving" is not as clearly defined as you think it is. The underlying operating system detects input events, such as movement of the mouse, in some deeply buried inner loop. That loop takes a finite time to run, and so the mouse is always apparently stationary for the time it takes the loop to run. The OS is going to report those movements to the JavaFX toolkit with some reduced frequency, and the JavaFX toolkit potentially limits the reporting time of those still further.
Consequently, to define "mouse not moving", you really have to resort to "no mouse movement has been detected in the last x", where x is some measure of time (either real time, e.g. nanoseconds, or number of frame renderings). So you really have to actually implement the logic for that somehow, and decide on how much time counts as "not moving".
@MadProgrammer suggests one implementation in the comments (which I think is the simpler one), and @Roland suggests another.
Here's an implementation of @MadProgrammer's suggestion:
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class TrackMouseStopped extends Application {

    private final long MIN_STATIONARY_TIME = 100_000_000 ; // nanoseconds

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();

        BooleanProperty mouseMoving = new SimpleBooleanProperty();
        mouseMoving.addListener((obs, wasMoving, isNowMoving) -> {
           if (! isNowMoving) {
               System.out.println("Mouse stopped!");
           }
        });

        PauseTransition pause = new PauseTransition(Duration.millis(MIN_STATIONARY_TIME / 1_000_000));
        pause.setOnFinished(e -> mouseMoving.set(false));

        // Note: if you want to consider the mouse having moved for
        // other events (e.g. dragging), you can do
        // pane.addEventHandler(MouseEvent.ANY, e -> { ... }); here
        pane.setOnMouseMoved(e -> {
            mouseMoving.set(true);
            pause.playFromStart();
        });

        Scene scene = new Scene(pane, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

and here's an implementation of @Roland's suggestion:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class TrackMouseStopped extends Application {

    private final long MIN_STATIONARY_TIME = 100_000_000 ; // nanoseconds

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();
        ObjectProperty<Point2D> mouseLocation = new SimpleObjectProperty<>(new Point2D(0, 0));
        pane.setOnMouseMoved(e -> mouseLocation.set(new Point2D(e.getX(), e.getY())));

        BooleanProperty mouseMoving = new SimpleBooleanProperty();
        mouseMoving.addListener((obs, wasMoving, isNowMoving) -> {
           if (! isNowMoving) {
               System.out.println("Mouse stopped!");
           }
        });

        AnimationTimer timer = new AnimationTimer() {
            private double lastMouseX ;
            private double lastMouseY ;
            long lastMouseMovement ;
            @Override
            public void handle(long timestamp) {
                double x = mouseLocation.get().getX();
                double y = mouseLocation.get().getY();
                if (Double.doubleToLongBits(lastMouseX) != Double.doubleToLongBits(x)
                    || Double.doubleToLongBits(lastMouseY) != Double.doubleToLongBits(y)) {
                    lastMouseMovement = timestamp ;
                }

                mouseMoving.set(timestamp - lastMouseMovement < MIN_STATIONARY_TIME);

                lastMouseX = x;
                lastMouseY = y;
            }
        };
        timer.start();

        Scene scene = new Scene(pane, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

A: Create an Event listener of MouseEvent.ANY. In that event listener you set your own properties mouseX and mouseY to the mouse location values of the event. In addition to that create an AnimationTimer which runs permanently and checks if the mouse coordinates didn't change within an interval of "delta" ms. If they didn't, invoke your handling code.
Example:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

public class Main extends Application {

    Scene scene;
    MouseStatus mouseStatus = new MouseStatus();

    Label infoLabel;

    @Override
    public void start(Stage primaryStage) {

        Group root = new Group();

        infoLabel = new Label();
        root.getChildren().add( infoLabel);

        scene = new Scene(root, 640, 480);

        primaryStage.setScene(scene);
        primaryStage.show();

        addInputListeners();

    }

    private void addInputListeners() {

        scene.addEventFilter(MouseEvent.ANY, e -> {

            infoLabel.setText("Moving");

            mouseStatus.setX(e.getX());
            mouseStatus.setY(e.getY());
            mouseStatus.setPrimaryButtonDown(e.isPrimaryButtonDown());
            mouseStatus.setSecondaryButtonDown(e.isSecondaryButtonDown());

        });

        AnimationTimer loop = new AnimationTimer() {

            long deltaNs = 30_000_000;

            double currX;
            double currY;
            long currNs;

            double prevX;
            double prevY;
            long prevNs;

            @Override
            public void handle(long now) {

                currX = mouseStatus.x;
                currY = mouseStatus.y;
                currNs = now;

                if( currNs - prevNs > deltaNs) {

                    if( prevX == currX && prevY == currY) {
                        infoLabel.setText("Stopped");
                    }

                    prevX = currX;
                    prevY = currY;
                    prevNs = currNs;
                }

            }
        };
        loop.start();

    }

    public class MouseStatus {

        double x;
        double y;
        boolean primaryButtonDown;
        boolean secondaryButtonDown;

        public double getX() {
            return x;
        }
        public void setX(double x) {
            this.x = x;
        }
        public double getY() {
            return y;
        }
        public void setY(double y) {
            this.y = y;
        }
        public boolean isPrimaryButtonDown() {
            return primaryButtonDown;
        }
        public void setPrimaryButtonDown(boolean primaryButtonDown) {
            this.primaryButtonDown = primaryButtonDown;
        }
        public boolean isSecondaryButtonDown() {
            return secondaryButtonDown;
        }
        public void setSecondaryButtonDown(boolean secondaryButtonDown) {
            this.secondaryButtonDown = secondaryButtonDown;
        }

    }

    public static void main(String[] args) {
        launch(args);
    }

}


text:
Q: What is the purpose of userError and isUserError functions? I'm exploring the exception mechanism in Haskell. I have figured out how catch and handler functions work.
main = toTry `catch` handler

handler :: IOError -> IO ()
handler e
    | isDoesNotExistError e = putStrLn "The file doesn't exist!"
    | otherwise = ioError e

The type of userError is String -> IOError. As I understand, that means we can pass userError as e in the aforementioned handler. Hoogle says about userError "Construct an IOError value with a string describing the error." But how to actually construct userError and what is the purpose of it? userError takes only a String, how can it possibly do anything?
For example, the aforementioned isDoesNotExistError e has its like own internal logic (as I understand), which deals with "does not exist" case. But we construct our own userError :: String -> IOError using only a String, so after all, is userError kind of a synonym for our String?
I would be grateful if you showed a simple example of using userError and isUserError.

A: userError is basically a smart constructor for a value of type IOError (which itself is an alias for IOException), which uses a single data constructor also named IOError. Two of the fields are ice_type :: IOErrorType and ioe_description :: String; the rest of the fields aren't relevant to UserError, so userError is really just a wrapper around the data constructor IOError:
userError       :: String  -> IOError
userError str   =  IOError Nothing UserError "" str Nothing Nothing

When you want to raise your own IOError, you use userError to create it; the resulting IOError value is what gets passed to the handler.
isUserError e simply tests if ioe_type e is UserError.


text:
Q: Oracle SQL sequential group number assignment I have a result set that for simplicity I will refer to as table "tab" of three columns: Category, Subcategory and Date, ordered by category and then date. This dataset is a grid and I wish to perform other processing on top of that grid. My problem is uniquely identifying (or sequentially labelling) groups within the dataset. The SQL below is what I am after (either GID1 or GID2 would do), based on the existence of the first 3 columns.
I have attempted group_id, grouping_id, rank, dense_rank and either missed a trick with one of these or am attempting something very awkward. It is not important what order the GID is, but is important that the group-number assignment is based on the data as ordered (category then date).
 CREATE TABLE Tab
        ("Category" varchar2(1), "SubCategory" varchar2(7), "Date" int, "GID1" int, "GID2" int);

    INSERT ALL
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'bannana', 20120101, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'grape', 20120102, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'pear', 20120103, 1, 1)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'pear', 20120104, 1, 1)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'bannana', 20120105, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'pear', 20120106, 2, 2)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'pear', 20120107, 2, 2)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'apple', 20120108, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('A', 'pear', 20120109, 3, 3)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'apple', 20120101, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'bannana', 20120102, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'apple', 20120103, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'bannana', 20120104, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'pear', 20120105, 1, 4)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'pear', 20120106, 1, 4)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'pear', 20120107, 1, 4)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'pear', 20120108, 1, 4)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('B', 'pear', 20120109, 1, 4)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'grape', 20120101, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'grape', 20120102, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'apple', 20120103, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'bannana', 20120104, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'grape', 20120105, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'pear', 20120106, 1, 5)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'apple', 20120107, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'apple', 20120108, NULL, NULL)
        INTO Tab ("Category", "SubCategory", "Date", "GID1", "GID2")
             VALUES ('C', 'apple', 20120109, NULL, NULL)
    SELECT * FROM dual
    ;

A: ok if its just pears then:
SQL> select "Category", "SubCategory", "Date",
  2         case
  3           when "SubCategory" = 'pear'
  4           then
  5             count(rn) over (partition by "Category" order by "Date") else null
  6         end GID1 ,
  7         case
  8           when "SubCategory" = 'pear'
  9           then
 10             count(rn) over ( order by "Category", "Date") else null
 11         end GID2
 12    from (select "Category", "SubCategory", "Date", lag("SubCategory") over (partition by "Category" order by "Date"),
 13                                    case
 14                                      when lag("SubCategory") over (partition by "Category" order by "Date") != "SubCategory"
 15                                      and "SubCategory" = 'pear'
 16                                       then 1
 17                                      when row_number() over (partition by "Category" order by "Date") = 1 and "SubCategory" = 'pear' then 1
 18                                      else null
 19                                    end rn
 20                               from tab)
 21   order by 1, 3;

Category   SubCate       Date       GID1       GID2
---------- ------- ---------- ---------- ----------
A          bannana   20120101
A          grape     20120102
A          pear      20120103          1          1
A          pear      20120104          1          1
A          bannana   20120105
A          pear      20120106          2          2
A          pear      20120107          2          2
A          apple     20120108
A          pear      20120109          3          3
B          apple     20120101
B          bannana   20120102
B          apple     20120103
B          bannana   20120104
B          pear      20120105          1          4
B          pear      20120106          1          4
B          pear      20120107          1          4
B          pear      20120108          1          4
B          pear      20120109          1          4
C          grape     20120101
C          grape     20120102
C          apple     20120103
C          bannana   20120104
C          grape     20120105
C          pear      20120106          1          5
C          apple     20120107
C          apple     20120108
C          apple     20120109

to break this down.
we look at the prior row ordered by "Date" (for each "Category") and see if it was a different "SubCategory" and also that the current cateogry = pear. if so we tag the row with a "1" (irrelevant what we use, just NON NULL).
lag("SubCategory") over (partition by "Category" order by "Date") != "SubCategory"
 and "SubCategory" = 'pear'

also for the first row we assign the same. this give us:
Category   SubCate       Date LAG("SU         RN
---------- ------- ---------- ------- ----------
A          bannana   20120101
A          grape     20120102 bannana
A          pear      20120103 grape            1
A          pear      20120104 pear
A          bannana   20120105 pear
A          pear      20120106 bannana          1
A          pear      20120107 pear
A          apple     20120108 pear
A          pear      20120109 apple            1
B          apple     20120101
B          bannana   20120102 apple
B          apple     20120103 bannana
B          bannana   20120104 apple
B          pear      20120105 bannana          1
B          pear      20120106 pear
B          pear      20120107 pear
B          pear      20120108 pear
B          pear      20120109 pear
C          grape     20120101
C          grape     20120102 grape
C          apple     20120103 grape
C          bannana   20120104 apple
C          grape     20120105 bannana
C          pear      20120106 grape            1
C          apple     20120107 pear
C          apple     20120108 apple
C          apple     20120109 apple

now, simply we count() the not null "RN" values ordering again on Date (per category for GID1, and not for GID2[gid2 we order by it too!). which is these lines:
count(rn) over (partition by "Category" order by "Date") (GID1)
and
count(rn) over ( order by "Category", "Date") (GID2)

A: Never thought it could be done with count. Brilliant.
Starting from version 11r2 this could be done by making use of recursive hierarchical query.
with r as (
  select "Category"
    , "SubCategory"
    , "Date"
    , row_number() over (partition by "SubCategory" order by "Category", "Date") rn
  from tab
)
, fwd ( "Category", "SubCategory", "Date", rn, GID1, GID2) as (
  select "Category"
    , "SubCategory"
    , "Date"
    , rn
    , 1
    , 1
  from r
  where rn = 1
  union all
  select nxt."Category"
    , nxt."SubCategory"
    , nxt."Date"
    , nxt.rn
    , decode( nxt."Category"
      , prev."Category", decode( nxt."Date"
        , prev."Date" + 1, prev.gid1
        , prev.gid1 + 1
      )
      , 1
    ) as gid1
    , decode( nxt."Date"
      , prev."Date" + 1, prev.gid2
      , prev.gid2 + 1
    ) as gid2
  from fwd prev
    , r nxt
  where prev.rn + 1= nxt.rn
    and prev."SubCategory" = nxt."SubCategory"
)
select "Category"
  , "SubCategory"
  , "Date"
  , decode( "SubCategory", 'pear', GID1, null ) as gid1
  , decode( "SubCategory", 'pear', GID2, null ) as gid2
from fwd
order by "Category", "Date";

It produces the same result
Category SubCategory       Date       GID1       GID2
-------- ----------- ---------- ---------- ----------
A        bannana       20120101
A        grape         20120102
A        pear          20120103          1          1
A        pear          20120104          1          1
A        bannana       20120105
A        pear          20120106          2          2
A        pear          20120107          2          2
A        apple         20120108
A        pear          20120109          3          3
B        apple         20120101
B        bannana       20120102
B        apple         20120103
B        bannana       20120104
B        pear          20120105          1          4
B        pear          20120106          1          4
B        pear          20120107          1          4
B        pear          20120108          1          4
B        pear          20120109          1          4
C        grape         20120101
C        grape         20120102
C        apple         20120103
C        bannana       20120104
C        grape         20120105
C        pear          20120106          1          5
C        apple         20120107
C        apple         20120108
C        apple         20120109

and can be a little more self explanatory.
Also it produces right GID1 and GID2 numbers for all other SubCategories not only 'pear' if you remove decode from the final select.
It's up to cost comparison to choose between this variant and the one provided by @DazzaL


text:
Q: Why do my vue-router links sporadically lead to the wrong page (or don't work at all)? I have a strange bug in a Vue.js single-page application using Vue Router, where my links sometimes do not lead to the correct page, although the variable determining the target page is correct.
This is better seen than described, so I have deployed the app in its current state. Go to http://daggy1.watchduck.net/nodes/2 and click on a link in the parents/children section, and do the same again on the page where it leads you. You will see that sometimes the page where you go is not the right one, and sometimes the link simply does not work. The links in the full list on top always work fine.
Devtools are enabled, and both the click (a click b) and the page change (a ----> b) are logged to the console.

In the screenshot it can be seen, that clicking link 9 on page 11 led to page 2 instead of 9.
I have uploaded the code on GitHub: https://github.com/watchduck/daggy
The links for the full list are in
Nodes.vue
<router-link v-for="node in nodes"
             :to="{name: 'node', params: {id: node.id, name: node.name}}"
             tag="li"
             active-class="active">
    {{node.id}}: {{node.name}}
</router-link>

while those in question are in
NodeRelatives.vue.
<router-link v-for="relative in relatives"
             :to="{name: 'node', params: {id: relative.id, name: relative.name}}"
             tag="li"
             @click.native="clickDebug(relative.id)">
    {{relative.id}}: {{relative.name}}
</router-link>

Both Nodes.vue and NodeRelatives.vue are used in
Node.vue.
What happens is logged to the console in two ways:

*

*clickDebug in NodeRelatives.vue logs the current page and the clicked link (a click b).

*The watcher in Node.vue logs the last and the new page (a ----> b).

Naturally I would like to know how to make my links behave correctly.
But I would also be glad about hints how to find a bug like this. How to debug Vue.js apps is an often asked question — and the answer is too often something like "use the Chrome extension". If someone can solve this using the Chrome extension, I would love to see that. I am sure a little debugging screencast would be very helpful to a lot of people.

Edit 1: As Slotheroo pointed out, the problem has to do with the tag="li" property and the nested anchor tag in router-link.
I removed them, and added a separate frontend with the new code:
Old: http://daggy1.watchduck.net/nodes/2
New: http://daggy1a.watchduck.net/nodes/2
It is in a separate branch called simple-router-links on GitHub:
NodeRelatives.vue
(Just avoiding the problem is of course not the solution I am looking for.)
Initially we thought that the event listener for the li is causing the problem, but it turned out that that is just the clickDebug listener - added when the problem already existed.

Edit 2: The behaviour is not as sporadic as it seemed:

*

*After reloading the page, all the links work.

*Start with http://daggy1.watchduck.net/nodes/9, click parent 2, click parent 1. Link 1 does not work. (Same for starting with any child of 2, i.e. 3, 4, 5, 9.)

*Start with http://daggy1.watchduck.net/nodes/10, click parent 1, click child 2. Link 2 leads to 13.

*Start with http://daggy1.watchduck.net/nodes/1, click child 2, click parent 1, 2, 1, 2, 1... never fails. (Same for starting with 10.)

Edit 3: When the Axios call to the backend is replaced with static data, it works: http://daggy1b.watchduck.net/nodes/2
The code is in a separate branch called static-data on GitHub, which was later reduced to a minimal version
(1c):
https://github.com/watchduck/daggy/tree/static-data/front/src
When a timeout is put in getNodeRelatives(), the problem is back again. Surprisingly even when the delay is set to 0:
getNodeRelatives() {
    let f = () => {
        this.relativesInBothDirections = this.$store.state.nodeRelatives[this.id]
    }
    setTimeout(f, 0)
}

Edit 4: When the event listener is removed from the broken link, it will work. The screenshot below shows how the event listener from the broken link to page 1 is removed. Clicking it again will lead to page 1 - but as a hard reload of the page, and not within the app.

Edit 5: I opened an issue: https://github.com/vuejs/vue-router/issues/2305
For this I minimized the version with static data: http://daggy1c.watchduck.net/nodes/2

A: This is a weird one for sure. I don't have it fully sorted out, but I'll share what I've learned.
For troubleshooting try this:

*

*Open the Vue developer tools

*Click on a router-link component, this will set the router-link component to be accessible as $vm0 in the console.

*Go to the console and type $vm0.to.params.id and hit enter. This should show the expected value for the target id of the link. e.g. 1

*Change the target id by typing something like $vm0.to.params.id = 7 (assuming the value was previously not 7)

*Click on the link in the window, it should now go to /nodes/7 instead of wherever it was previously set to go.

The weird thing about this is that it works for the 13 nodes links up top, but it does NOT work for the node relatives (parents/children). Changing the id for the to param does not affect where click on the link takes us.
Troubleshooting part 2:

*

*Right click on one of the nodes links in the normal browser window and inspect it. This should open up the elements tab in the dev tools.

*Click on the event listeners sub-tab. We can see that there is one listener for the click event on the  tag

*Now right click and inspect one of the relatives links.

*When reviewing the event listeners for the click event here, we can see that there are two -- one for the  tag and one for the
 tag

This makes me think that perhaps those listeners somehow trigger different events, and perhaps it is the listener on the
 tag that is directing to the wrong location.
One other piece of observational evidence I have is that when a route goes to the wrong link, it was usually the correct link for the previous page. I'll explain what I mean.
1st view: I'm looking at the page for Node 5. It has a parent of Node 2, and children Node 7, and Node 8. Note here that Node 7 is the first child listed.
We click on Node 2
2nd view: We're now on the page for Node 2. It has a parent of Node 1 and children of Nodes 9, 4, 5, and 3. Note that Node 9 is the first child listed. If we click on Node 9, it takes us to Node 7, which would have been the correct first child on the previous page! This suggests that somehow the links weren't updated properly, even though the data on the page looks like it's refreshed.
Things I would suggest to continue troubleshooting:

*

*Remove the tag="li" part of the router-links for relative nodes and see how they render then

*Try to make the way you iterate through node relatives as similar as you can to how you iterate through the nodes

*

*Try iterating on the router-link instead of on the tr

*Try passing static data to the node relatives component. I wonder if there is some sort of latency with the axios call that is resulting in some sort of mismatch between the router-link information and the data.


text:
Q: Recursion can't append list Here I use a simplified code to demonstrate what I've encountered:
def recTry(inList):
    print(inList)
    if len(inList) < 10:
        recTry(inList.append(1))

I hope with recursion it'll grow like [1], [1, 1], [1, 1, 1] ...
But actually run that will yield this:
>>> recTry([1])
[1]
None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in recTry
  File "<stdin>", line 3, in recTry
TypeError: object of type 'NoneType' has no len()

inList become None since the second recursion.
So How can I code to make the inList appended with each recursion?

A: you try to call function with result of inList.append(1) but it is None
try to:
if len(inList) < 10:
    inList.append(1)
    recTry(inList)

A: inList.append(1) returns None so you pass None  while recursion
what you can do is:
def recTry(inList):
    print(inList)
    if len(inList) < 10:
        inList.append(1)
        recTry(inList)
    else:
        return inList

A: It is a convention in Python that methods that mutate sequences return None.  Thus the value your passing in first returns nothing which is your problem.

A: On the 4th line of your function,
recTry(inList.append(1))

inList.append(1) returns None after appending 1 to the existing list. This None is what you are passing to recTry method. You can try this instead to make the inList appended with each recursion:
inList.append(1)
    recTry(inList)


text:
Q: Find series expansion of an integral The question asks to find a series expansion of $\int_{-\infty}^{x}e^{\frac{-s^2}{2}}ds$, given:
$$\int_{-\infty}^{x} \frac{1}{s^n}e^{\frac{-s^2}{2}}ds=\frac{-e^{\frac{-x^2}{2}}}{x^{n+1}}-(n+1)\int_{-\infty}^{x} \frac{1}{s^{n+2}}e^{\frac{-s^2}{2}}ds$$
I've come with with this series:
$$I(x)=\sum_{j=0}^{\infty}(-1)^j \frac{1}{x^{2j+1}}e^{\frac{-x^2}{2}} \prod_{k=0}^{j} (2k+1)$$
but the ratio test shows that this series is divergent, which I think shouldn't be the case as the integral itself converges for all $x$.
edit: not a Taylor expansion! I'm required to come up with a series representation with the given recursive relation.
Any help would be greatly appreciated!


text:
Q: Find Files Recursively With Different ACLs How would I go about finding all files recursively that have ACLs different from what I'm searching for?  For example I would like to find all files in a directory that have ACLs that are not identical to the following example:
# owner: bob
# group: bobs-group
user::rwx
user:fred:rwx
group::rw-
mask::rwx
other::r--

Using a separate search I'd like to be able to do the same for directories, but with slightly different permissions.

A: You may use find and a diff.

*

*Save the desired reference permissions in a file, e.g. perref

$cat perref
# owner: bob
# group: bobs-group
user::rwx
user:fred:rwx
group::rw-
mask::rwx
other::r--

*Do some find-magic by simply comparing the output of getfacl with the reference and negating matches. As this needs to cut the first line of getfacl output (i.e. the filename), one needs process substitution here, this must go via a shell script and proper quoting.

find -type f \
! -exec bash -c 'diff -q <(getfacl "$1" | sed 1d ) perref >/dev/null' bash '{}' \; \
-print

Or -print0 in the end, depending on the further plans. This works as diff has a 0 as exit status if files are identical.
Remove the ! for finding files with matching ACLs.
Use -type d for doing the search on directories.


text:
Q: protofile.proto: A file with this name is already in the pool Having the following structure:
- project1
  - project1.py
  - protofile_pb2.py
  - protofile_pb2_grpc.py
- project2
  - project2.py
  - protofile_pb2.py
  - protofile_pb2_grpc.py

project1.py:
import protofile_pb2.py
...

project2.py:
import protofile_pb2
import project1
...

When running project2.py, I get this error:
TypeError: Couldn't build proto file into descriptor pool!
Invalid proto descriptor for file "protofile.proto":
protofile.proto: A file with this name is already in the pool.

A: You are using different versions of your generated protofile.proto. Make sure to regenerate the protobuf files and it should work fine.

A: According to this comment, it worked for me:
pip uninstall protobuf
pip install --no-binary protobuf protobuf

A: I faced similar issue while deploying google cloud functions in Python. My cloud function was using different versions of .proto files in my module (which was again a private module which I wanted to install using requirements.txt). The solution is to use pure python implementation instead of using binary implementation of protobuf. To solve this in cloud functions or in cloud build you can set cloud functions env variables to use python implementation of protocol buffers.
In your gcloud cloud function deploy command use following option:
<start of command> --set-env-vars=PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION='python' <your rest of the command>

or if you are in any other env/os simply do this
export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION='python'

This solved my issue.


text:
Q: Using the onclick method to grab $this row and populate a web form I am trying to select data from a table row and use that very data in a web form. I've been able to pass the record id as a data-attribute of the row. I am stuck on the part where I have to use the $.on() function and also what do I put in the PHP Webform that will be associated with this Javascript code?
Thanks
Here is the Javascript
$(document).on('click', 'tr', function() {

        //Get the ID from the row clicked
        var id = $(this).data('recordId');

        //short-hand
        $('#section2').load('data_entry_form.php?id='+id);

});

Here is the PHP for the Web Form (see the first few lines where I try to "catch" the record id that was selected by the user.

<form>
<?php
   $_GET['id'];

   echo $id; //should echo the id being sent across.
?>
<input type="date"></input>

<input list="auditors" placeholder="Auditor" />
<datalist id="auditors">
    <option value="Foo" />
</datalist>

<input list="city" placeholder="City" />
<datalist id="city">
    <option value="Bar" />
</datalist>

<input type="submit" name="submitbutton" id="submitbutton" value="Submit" />
</form>

Here is the PHP that generated the original table that I selected the rows from. Here I have passed a data-attribute which is the "fee_source_id" (identical to the first column in the table).
<?php
require_once 'config.php';

$dbh = new PDO($dsn, $dbuser, $dbpass);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$result = $dbh->query("
    SELECT a_aif.aif_id,
      a_aif.fee_source_id,
      a_aif.company_name_per_sedar,
      a_aif.document_filing_date,
      IF (a_aif_remaining.aif_id IS NULL, 0, 1) `match`
    FROM  a_aif
      LEFT JOIN a_aif_remaining
        ON a_aif_remaining.aif_id = a_aif.aif_id
    WHERE aif_id = {$id}
    ORDER BY aif_id DESC");

$result->setFetchMode(PDO::FETCH_ASSOC);

if ( !empty($result) ) : endif;

?>

    Document ID
    Pubco Name
    Filing Date
    PDF

<?php foreach($result as $index => $row) : ?>
<tr data-recordId="<?=$row[fee_source_id];?>"
    class="<?=$row["match"] ? "match" : "";?>">
    <?php echo $row[fee_source_id]; ?>
    <?php echo $row[company_name_per_sedar]; ?>
    <?php echo $row[document_filing_date]; ?>

<? endforeach;?>

A: Where is '$row['aif_id']' set at?  In the code above, you have '$id' and $row['aif_id'] but where is that $row['aif_id'] being set?  Is $row supposed to represent the data loaded with $id?
$('document').ready(function(){
    $('table').find('tr').on({
     click: (function(e){
        var id = $(this).data('recordId');
        $('#section2').load('data_entry_form.php?id='+id);

     })

    });

});

<?php
   $id = $_GET['id'];

   echo $id; //should echo the id being sent across.
?>


text:
Q: How to send push notification with firebase to ionic app with custom ID? I am using FCM to send push notifications to Ionic capacitor app and it works perfectly when I am sending notification to all users(I am using this example).
Is it possible to provide a list of users(with custom IDs) to firebase to send notifications? I guess than App should send custom ID or property to Firebase and then receive push notification if that ID is in the list.


text:
Q: What will happen to a black hole if the Higgs field at the singularity is turned off? At high enough temperature the Higgs field VEV becomes zero (around $10^{15}~\rm K$ or so). Suppose the singularity reaches such a temperature, will all the mass vanish? What will happen then?
Note that a black hole appears cold to external observers but internally the temperature should be much higher. (At least that's what I read)

A: No. The Higgs mechanism gives mass to the gauge bosons and fermions in the standard model. Mass can also come from other sources. The mass of a proton, for instance, is much greater than the sum of the masses of its constituents.
And keeping in mind that mass in relativity is essentially just total energy as measured in a particular reference frame, as long as energy is conserved, nothing can cause the mass of a black hole to vanish without anything being radiated away.


text:
Q: Why does Live Test in Google Search Console return content that is not viewable in the browser? According to Google Search Console Live Test on https://www.energycouncil.com.au/ returns text that does not exist on the viewable website.

Why is completely different source returned when using the Google Search Console with a Live Test?

A: I worked it out.
Code had been injected into a source code file that redirects the site if it is a website indexer. Ingeniously, this code did not do anything for over a year so I didn't see the issue as no files appeared to be recently modified.
To find the issue, download the live site and search it for "redirect"


text:
Q: Facebook JSON not being displayed on TableView I am trying to display Facebook JSON from a correctly authenticated account onto a TableView, however no information is displayed despite Json being logged. Here is how I am attempting to display the information onto the TableView:
- (void)fetchFacebookPosts {
    [FBRequestConnection startWithGraphPath:@"me/feed" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        if (!error) {
            NSLog(@"%@",result);
            facebookResponse = [result mutableCopy];
            [self.facebookPosts addObjectsFromArray:result[@"data"]];
            [self.tableView reloadData];
        } else {
            NSLog(@"Failure: %@", error);
        }
    }];
}

#pragma mark - Table view data source

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FacebookCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"FacebookCell"];
    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Background.png"]];

    if (cell == nil) {
        cell = [[FacebookCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FacebookCell"];
    }

    NSDictionary *entry = facebookPosts[indexPath.row];

    // Set Image

    // Set User Name
    NSString *user =  entry[@"story"];
    [cell.textLabel setText:user];

    return cell;
}

In this code facebookResponse is a NSMutableDictionary
and facebookPosts is a NSMutableArray.


text:
Q: Flutter Messaging App - Disabling Icon Button I have a messaging application where you can select from a list of users to talk with. There is an icon button on the App Bar where you can confirm the group of users you want to message. Right now, the user can spam the icon button multiple times. I want to disable the icon button after it has been pressed once. I have a bool iconEnabled variable, but I am unsure where to place it in onPressed.
return Scaffold(
      appBar: AppBar(
        title: Text("Users"),
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.check),
            onPressed: widget.isNew
                ? () async {
                    if (newUsers.length == 0) {
                      return;
                    }
                    widget.thread.users.addAll(newUsers);
                    widget.thread.userIds.addAll(widget.thread.users.map((user) => user.id).toList());
                    widget.thread.users = widget.thread.users;
                    // Call New Thread
                    var threadId = await Client.addThread(widget.thread);
                    widget.thread.id = threadId;
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        settings: RouteSettings(name: "MessagePage"),
                        builder: (context) => MessagePage(
                          thread: widget.thread,
                        ),
                      ),
                    );
                  }
                : () {
                    if (newUsers.length == 0) {
                      return;
                    }
                    widget.thread.users.addAll(newUsers);
                    widget.thread.userIds.addAll(widget.thread.users.map((user) => user.id).toList());
                    widget.thread.users = widget.thread.users;
                    // Call users patch
                    Client.addUsers(widget.thread);
                    Navigator.pop(context);
                  },
          ),
        ],
      ),

A: Wrap the IconButton with the AbsorbPointer widget like this:
AbsorbPointer(
          absorbing: buttonDisabled,
          child: IconButton(
          icon: Icon(Icons.check),
          onPressed: () { disableButton();}
        ),
      ),

For this example I declared a global variable:
 bool buttonDisabled = false;

When the button is pressed:
 void disableButton() {
    setState(() {
     buttonDisabled = true;
    });
  }

A: If you already have the logic done for when to enable/disable the button, then you're 99% of the way there.
If onPressed is passed null, the button will be disabled. So you can just make a little change in the creation of the IconButton:
onPressed: !iconEnabled ? null : (widget.isNew // ... and put the closing parentheses after the onPressed callbacks


text:
Q: Unbound Expression works as not expected in lightning Faced an issue where unbound expressions are not working as expected. Below is the scenario.
Parent component:
<aura:component implements="force:appHostable" controller="test1" >
<aura:attribute name="campingItem" type="Camping_Item__c" default="{ 'sobjectType': 'Camping_Item__c'}" />    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>    <aura:attribute name="campingItemList" type="Camping_Item__c[]"/>

    <c:CampingItemList campingItems="{#v.campingItemList}" campingItem = "{#v.campingItem}"/>

</aura:component>

Parent Controller:
({
    doInit : function(component, event, helper) {
        var action = component.get('c.getcampingItems');

        // Configure response handler
        action.setCallback(this, function(response) {
            var state = response.getState();

            if(state === "SUCCESS") {
                console.log('Working: ' + state);
                component.set('v.campingItemList', response.getReturnValue());
                console.log('list: ' + component.get('v.campingItemList'));
            } else {
                console.log('Problem getting account, response state: ' + state);
            }
        }
        $A.enqueueAction(action);

        component.set('v.campingItem.Name', 'check1');
    }
});

Child Component:
<aura:component implements="force:appHostable" controller="test1">
  <aura:attribute name="campingItems" type="Camping_Item__c[]"/>

<aura:attribute name="campingItem" type="Camping_Item__c" default="{ 'sobjectType': 'Camping_Item__c'}" />

<ui:message aura:Id="msg" title="Error" class="slds-hide" severity="confirm" closable="true">        Successfully deleted ID    </ui:message>

ABC = {!v.campingItem.Name}

</aura:component>

Here, we are getting that value of the attribute campingItem in the child which we are setting it in the doInit of the parent i.e. check1 which is not supposed to be as per the developer guide as it is the unbound expression. But with list campingItemList its working as expected mean not getting the value.

A: Please check the below documentation link which very clearly says if you are going to use init events to load data for attributes which will get passed to other components then you have to use bound expressions. Unbound will not work for these cases
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/expr_data_binding.htm

Don't use a component's init event and client-side controller to
  initialize an attribute that is used in an unbound expression. The
  attribute will not be initialized. Use a bound expression instead. For
  more information on a component's init event, see Invoking Actions on
  Component Initialization.
Alternatively, you can wrap the component in another component. When
  you instantiate the wrapped component in the wrapper component,
  initialize the attribute value instead of initializing the attribute
  in the wrapped component's client-side controller.

A: When we use Unbound expression, it works as a one-way binding. So if we are passing any value as an attribute to child component, then both of the components have the same value(at initialization time), but then if we update the value in any of the components, it doesn't update to another one.


text:
Q: How can I create a distinct list of javascript objects, when I need a compound key to make it distinct? Yes, there are several posts about creating distinct lists in several languages, but I'm not seeing anything about using a compound or composite key.
I have an array of objects (contacts) with duplicates, that I need to make an array of distinct values from, with the key being the composite of the email, name, and phone fields. The objects look like this:
{
    name: "Name",
    email: "email@example.com",
    phone: "5551212",
    organization: "BigCompany",
    title: "CEO"
}

I can create a distinct list using map.has(), based on email only:
const distinct = [];
const map = new Map();
for (const item of contacts) {
    if(!map.has(item.email)){
        map.set(item.email, true); // set any value, but add an entry to the Map
        distinct.push(item);
    }
}

...but I need distinct array elements for each contact with the same email, but a different phone, or same phone, but different email, etc. Reading through the documentation on map.has(), I'm not seeing anything about the key parameter being a complex data structure (multiple fields, in this case). Is there some better tool, or am I just missing that section of the documentation?

A: You can create a JSON string to use as a key, like this:
const distinct = [];
const map = new Map();
for (const item of contacts) {
    const {name, email, phone} = item;
    const key = JSON.stringify({name, email, phone});
    if(!map.has(key){
        map.set(key, true);
        distinct.push(item);
    }
}

Since JSON.stringify (spec | MDN) is required to follow ES2015's property order (which many operations aren't), you know that if you create the objects in the same way every time and all of the enumerable properties are "own" properties, the resulting JSON string will be the same for objects with the same name, email, and phone property values (and different if they're different). (That "create the objects in the same way every time" is important, the objects {a: 1, b: 2} and {b: 2, a: 1} result in different JSON strings.)

Side note: If you're just using map.has and map.set(key, true), a Set would probably make more sense:
const distinct = [];
const set = new Set();
for (const item of contacts) {
    const {name, email, phone} = item;
    const key = JSON.stringify({name, email, phone});
    if(!set.has(key){
        set.add(key);
        distinct.push(item);
    }
}

A: You can use Map to store your distinct contacts by creating your own compound key:
const contacts = [
  {
    name: "Name",
    email: "email@example.com",
    phone: "5551212",
    organization: "BigCompany",
    title: "CEO"
  },
  // ...
]

// Store distinct contacts.
const map = new Map()

contacts.forEach((c) => {
  /**
   * Any contact with the same name, email, and phone will
   * be considered a duplicate.
   */
  const key = `${c.name}::${c.email}::${c.phone}`
  map.set(key, c)
})

Now your map is a container of items { key => contact }.
To get a list of distinct contacts, use:
const list = Array.from(map.values())

// Use spread syntax to accoplish the same thing.
const list2 = [...map.values()]

Note: using the delimiter :: can be considered unsafe if name, email, or phone number might contain that substring. Whichever delimiter you use, you should make sure you disallow it from input on those fields if possible, and/or make it such that the likelihood of it occurring in the input is highly improbable:
const delim = '__:DELIM:__'
const key = `${c.name}${delim}${c.email}${delim}${c.phone}`

Even still, there is no 100% guarantee that the delimiter won't occur in a field such as name unless you perform input validation on that field.
EDIT: On examination of T.J. Crowder's JSON key, using that method to generate your key would provide a good guarantee of no substring issues:
const key = JSON.stringify({name, email, phone});
map.set(key, c)


text:
Q: filled / open circle by group I have trouble making a filled / open circle plot by group.
My data looks like:
Body_weight  Gender
50            M
60            M
55            M
45            F
43            F
42            F

I want to plot the male weights in filled circle and the female weights in open.
I tried:
ggplot(data, aes(x=Gender, y=Body_weight))+
 geom_point(aes(fill=Gender))

But, this only gives filled circles for both gender.
I have no idea why this does not work.
geom_point(aes(shape=Gender)) works and gives a circle / triangle plot.

A: The aesthetic "fill" does not determine if the point is filled with colour or not, but fills it with a different colour for each gender. The way to do what you want is using "shape" and mapping the shapes to open and closed circle instead of the default circle/triangle you get. To do this you need to use scale_shape_manual.
ggplot(data, aes(x=Gender, y=Body_weight)) +
    geom_point(aes(shape=Gender)) +
    scale_shape_manual(values = c(16, 21))

Have a look at http://sape.inf.usi.ch/quick-reference/ggplot2/shape for other shapes available


text:
Q: aChartEngine cryptic IllegalArgumentException Folks - I am getting a cryptic IllegalArgumentException when using aChartEngine to draw a timeseries plot.  Here is the code snippet that attempts to render the chart:
private GraphicalView chartView;
private XYMultipleSeriesDataset dataset;
private XYMultipleSeriesRenderer renderers;

dataset = new XYMultipleSeriesDataset();
TimeSeries series = new TimeSeries(varLongName);
for(int i=0;i<values.size();i++)
    series.add(quarterDates.get(i), values.get(i));
dataset.addSeries(series);

renderers = new XYMultipleSeriesRenderer();
double YMin=0f;
double YMax=0f;

XYSeriesRenderer render = new XYSeriesRenderer();
render.setColor(Color.RED);
render.setPointStyle(PointStyle.CIRCLE);
render.setFillPoints(true);
render.setLineWidth(2f);
YMin=dataset.getSeriesAt(0).getMinY();
YMax=dataset.getSeriesAt(0).getMaxY();
renderers.addSeriesRenderer(render);
renderers.setXTitle("Date");
renderers.setYTitle(varShortName);
renderers.setAxesColor(Color.GREEN);
renderers.setChartTitle(currentBankName+" "+varShortName+".");
renderers.setAxisTitleTextSize(16f);
renderers.setYLabelsAlign(Align.RIGHT);
renderers.setYLabelsPadding(5f);
renderers.setLabelsTextSize(12f);
renderers.setLegendTextSize(12f);

Log.d(TAG,"YMin is initially set to: "+YMin);
YMin -=5f;
Log.d(TAG,"YMin is now set to: "+YMin);
Log.d(TAG,"YMax is initially set to: "+YMax);
YMax +=5f;
Log.d(TAG,"YMax is now set to: "+YMax);
renderers.setYAxisMin(YMin);
Log.d(TAG, "Set YAxis Min on renderer");
renderers.setYAxisMax(YMax);
Log.d(TAG, "Set YAxis Max on renderer");

chartView = ChartFactory.getTimeChartView(this, dataset, renderers, "dd-MMM-yyyy");
Log.d(TAG, "Created chartView");
plotArea.addView(chartView, new LayoutParams(LayoutParams.MATCH_PARENT, 250));

I added a lot of debug messages to localize the problem but am still having trouble.  From the looks of it, it appears that something is -Inf or something like that but I may be completely on the wrong track. I am also including the activity's layout file.
Layout File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/background"
tools:context=".MyPerformance" >

<TextView
    android:id="@+id/HelloUser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:layout_marginTop="5dp"
    android:textColor="@color/strong_black"
    android:textSize="16sp"
    android:textStyle="bold"
    android:layout_marginLeft="5dp" />

<TextView
    android:id="@+id/ReportForBank"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/HelloUser"
    android:layout_alignLeft="@id/HelloUser"
    android:text="@string/reportForBank"
    android:layout_marginTop="10dp"
    android:textColor="@color/strong_black"
    android:textSize="12sp"
    android:textStyle="bold" />

<Spinner
    android:id="@+id/PerfVarSpinner"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_below="@id/ReportForBank"
    android:layout_alignLeft="@id/ReportForBank"
    android:prompt="@string/var_prompt" />

<ImageView
    android:id="@+id/HelpOnVarIcon"
    android:layout_width="36dp"
    android:layout_height="36dp"
    android:layout_toRightOf="@id/PerfVarSpinner"
    android:layout_alignTop="@id/PerfVarSpinner"
    android:src="@drawable/help"
    android:contentDescription="@string/help"
    android:clickable="true"
    android:onClick="showDescription" />

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_below="@id/PerfVarSpinner"
    android:layout_alignLeft="@id/ReportForBank"
    android:background="@color/black_overlay"
    android:id="@+id/PlotArea" />

<TextView
    android:id="@+id/Recommendations"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/PlotArea"
    android:layout_alignLeft="@id/PlotArea"
    android:text="@string/recommendation"
    android:layout_marginTop="10dp"
    android:textColor="@color/strong_black"
    android:textSize="12sp"
    android:textStyle="bold" />

Any help would be much appreciated.  And here is the logcat output:
08-08 18:25:57.909: D/com.ssjanus.bankstats.MyPerformance(2404): YMin is initially set to: 318580.0
08-08 18:25:57.909: D/com.ssjanus.bankstats.MyPerformance(2404): YMin is now set to: 318575.0
08-08 18:25:57.909: D/com.ssjanus.bankstats.MyPerformance(2404): YMax is initially set to: 318580.0
08-08 18:25:57.919: D/com.ssjanus.bankstats.MyPerformance(2404): YMax is now set to: 318585.0
08-08 18:25:57.919: D/com.ssjanus.bankstats.MyPerformance(2404): Set YAxis Min on renderer
08-08 18:25:57.919: D/com.ssjanus.bankstats.MyPerformance(2404): Set YAxis Max on renderer
08-08 18:25:57.939: D/com.ssjanus.bankstats.MyPerformance(2404): Created chartView
08-08 18:25:58.079: D/AndroidRuntime(2404): Shutting down VM
08-08 18:25:58.079: W/dalvikvm(2404): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
08-08 18:25:58.129: E/AndroidRuntime(2404): FATAL EXCEPTION: main
08-08 18:25:58.129: E/AndroidRuntime(2404): java.lang.IllegalArgumentException: -5.585327982E13 > -1.1170655964E14
08-08 18:25:58.129: E/AndroidRuntime(2404):     at java.util.TreeMap$BoundedMap.<init>(TreeMap.java:1110)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at java.util.TreeMap.subMap(TreeMap.java:704)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at org.achartengine.model.XYSeries.getRange(XYSeries.java:305)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at org.achartengine.chart.XYChart.draw(XYChart.java:254)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at org.achartengine.GraphicalView.onDraw(GraphicalView.java:168)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.View.draw(View.java:10978)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.drawChild(ViewGroup.java:2887)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2489)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.View.draw(View.java:10981)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.widget.FrameLayout.draw(FrameLayout.java:450)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.drawChild(ViewGroup.java:2887)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2489)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.View.draw(View.java:10981)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.drawChild(ViewGroup.java:2887)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2489)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.View.draw(View.java:10981)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.widget.FrameLayout.draw(FrameLayout.java:450)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.drawChild(ViewGroup.java:2887)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2489)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.drawChild(ViewGroup.java:2885)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2489)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.View.draw(View.java:10981)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.widget.FrameLayout.draw(FrameLayout.java:450)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2126)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewRootImpl.draw(ViewRootImpl.java:2026)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1634)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.os.Looper.loop(Looper.java:137)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at android.app.ActivityThread.main(ActivityThread.java:4424)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at java.lang.reflect.Method.invokeNative(Native Method)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at java.lang.reflect.Method.invoke(Method.java:511)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-08 18:25:58.129: E/AndroidRuntime(2404):     at dalvik.system.NativeStart.main(Native Method)
08-08 18:25:58.739: I/dalvikvm(2404): threadid=3: reacting to signal 3
08-08 18:25:58.760: I/dalvikvm(2404): Wrote stack traces to '/data/anr/traces.txt'

Update: Okay I think I raised a storm in a tea cup! Sorry about that. It turns out that the dates were badly formatted which caused this exception.

A: It turns out that the dates were badly formatted which caused this exception.  I was converting dates from a sql date format (yyyy-MM-dd) into java.util.Date using SimpleDateFormat which was ok, except I was grabbing the "year" part of the date wrong, e.g., setting the year to 200 instead of 2007.  This raised the exception.


text:
Q: Oracle Apex Popup lov conditionally value required I am using Oracle Apex 5.1.
I have a select list item (P28_SELECT_LIST with values A1, A2, A3) and two pop up LOVs (P28_LOV_1, P28_LOV_2).
Based on the P28_SELECT_LIST value(for A2 and A3) the two LOVs should be made value required.( I Cannot use validations as it is showing two separate error occurred message for two LOV items.
I need the validations to work exactly as it works when value required it ticked to yes under validations. Is there a way to do it? Maybe by using javascript. I have tried setting attributes like aria-invalid to true etc. But didn't help.
Any suggestions on how to do it? Thanks in advance.


text:
Q: Can a scope that looks up on a polymorphic be turned into an association between the two models? Suppose an Invoice belongs_to Invoiceable, a polymorphic, being the possible invoiceable_types Subscription, SubscriptioCart and Purchase.
The Invoice table has the columns invoiceable_type and invoiceable_id. So for example, if I want to retrieve all Invoices related to a SubscriptionCart through the polymorphic, I can do Invoice.where(invoiceable_type: "SubscriptionCart").
Now how can I transform such scope into a direct association between Invoice and a SubscriptionCart through the polymorphic?
I've tried adding belongs_to :subscription_cart to the Invoice model, resulting in @invoice.subscription_cart returning nil .
This makes sense as the table invoices doesn't have a column subscription_cart_id (nor should it, as that's why we use the polymorphic).
But how do I specify what to look for in Invoiceable then?
I've tried class_name: :SubscriptionCart and foreign_key: subscription_cart_id but it still returns nil.
Stripped down models:
Invoice model:
class Invoice < ApplicationRecord
  belongs_to :invoiceable, polymorphic: true

  scope :subscription_cart, -> {
    where(invoiceable_type: "SubscriptionCart")
  }

end

SubscriptionCart model:
class SubscriptionCart < ApplicationRecord
    include ::Invoiceable::Subscription

    belongs_to :subscription
    has_many   :invoices, as: :invoiceable
end

Subscription model:
class Subscription < ApplicationRecord
    include ::Invoiceable::Subscription

    belongs_to  :user
    has_many    :subscription_carts, dependent: :restrict_with_exception
    has_many    :invoices, as: :invoiceable, dependent: :restrict_with_exception
end

Invoiceable concern:
module Invoiceable::Subscription
    extend ActiveSupport::Concern

    include Invoiceable

    included do
    def attributes_for_invoice_items
      {}.tap do |attributes|
        attributes["flat_fee"] = plan_invoice_item
        attributes["delivery_price"] = delivery_price_item_invoice_item if plan.deliverable?
        attributes["setup_fee"] = setup_invoice_item if setup_fee_billing_pending?
        attributes["per_unit"] = per_unit_invoice_item if base_plan.per_unit?
      end
    end
  end
end


text:
Q: Запуск тестов в разных браузерах одновременно Как запустить один и тот же тест в нескольких браузерах одновременно?
Пытался использовать Selenium grid, но не хватило знаний и навыков гугления.
Запускаю на своей машине Windows 8.1
Использую JUnit Webdriver 2.0 maven

A: Параллельный запуск тестов является одним из мощных средств для ускорения тестирования. Хорошо автоматизированные тесты должны быть независимыми, изолированными и воспроизводимыми, эти качества делают их идеальными для одновременного выполнения. Однако на практике не все тестовые классы разработаны с возможностью параллельного запуска. Такие аспекты, как общие изменяемые переменные, общий доступ к файлу и базе данных, или использование встроенного веб-сервера, могут сделать параллельный запуск тестов очень сложным или вообще невозможным. Тем не менее, одновременный запуск тестов, определенно, очень полезная вещь.
Начиная с версии 4.7 в JUnit была добавлена возможность параллельного запуска, для этого нужно настроить Maven следующим образом:
<plugins>
    [...]
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12.3</version>
        <configuration>
          <parallel>methods</parallel>
        </configuration>
      </plugin>
    [...]
</plugins>

Атрибут parallel может принимать значения «classes», «methods» или «both». При этом нельзя однозначно утверждать о количестве запущенных одновременно тестов, это напрямую зависит от параметров компьютера и настроек плагина по-умолчанию.
Во время запуска теста найдите следующую строку в консоли, она позволяет узнать параметры с которыми выполняется параллельный запуск:
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Concurrency config is parallel='methods', perCoreThreadCount=true, threadCount=2,
useUnlimitedThreads=false

Атрибут threadCount позволяет указать, сколько потоков должно быть выделено для запуска тестов (сколько тестов должно запускаться параллельно). Обратите внимание, что его использование с параметром perCoreThreadCount, установленным в true, может исказить реальное количество запускаемых одновременно тестов. В то же время perCoreThreadCount позволяет добиться большей гибкости при запуске тестов на разных машинах. Например, при запуске тестов со следующей конфигурацией на машине с 2-х ядерным процессором, одновременно будут выполняться 4 тестовых класса, а не 2:
<plugins>
    [...]
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12.3</version>
        <configuration>
          <parallel>classes</parallel>
          <perCoreThreadCount>true</perCoreThreadCount>
          <threadCount>2</threadCount>
        </configuration>
      </plugin>
    [...]
</plugins>

Существует еще такой атрибут как useUnlimitedThreads. При его использовании будет создаваться столько потоков, сколько классов или методов в Вашем проекте, и все тесты будут пытаться запуститься одновременно. useUnlimitedThreads отлично работает для юнит-тестов, но для функционального web тестирования его лучше не использовать.
Настройки конфигурации полностью зависят от характера Ваших тестов, поэтому стоит поэкспериментировать с различными конфигурациями и посмотреть, какой из вариантов настройки больше всего подходит для Вас.
Информация взята с
Блога вебразработчика
В будущем советую все таки использовать Google. И не бояться эксперементировать со своим проектом. Надеюсь предоставленная информация Вам поможет, удачи в дальнейших трудах)