Q: PHP if specific business day of week and time echo The following code works to echo "Open" or "Closed" if time is between 8:15am and 5:30pm. I am trying to make it day specific. How can I incorporate format character 'D' as example, Mon hours 8:15am - 5:30pm .. echo "Open", Sat hours 8:15am - 1:00pm "Open". I want to be able to control echo of Open/Closed by each day and time.
current working code for hours only
<?php
date_default_timezone_set('America/New_York');
$hour = (int) date('Hi');
$open = "yah hoo, we are open";
$closed = "by golly, im closed";

if ($hour >= 0815 && $hour <=1735) {
// between 8:15am and 5:35pm
echo "$open";
} else {
echo "$closed";
}
?>

example of what I am trying to do:
$hour = (int) date('D Hi');
if ($hours >= 0815 && $hour <=1735 && $hour === 'Mon')
{ echo "$open"; }
else { echo "$closed"; }
if ($hours >= 0815 && $hour <=1300 && $hour === 'Sat')
{ echo "$open"; }
else { echo "$closed"; }

another example per The One and Only's answer which looks close to what I am looking for, but this also does not work
<?php
$openDaysArray = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat','Sun');

$thisDate = date('D Hi');

$explode = explode(" ", $thisDate);
$day = $explode[0];
$time = $explode[1];

if (in_array($day, $openDaysArray))
if ($time < 815 || $time > 1730 && $day === 'Mon');
if ($time < 815 || $time > 1730 && $day === 'Tue');
if ($time < 815 || $time > 1730 && $day === 'Wed');
if ($time < 815 || $time > 1730 && $day === 'Thu');
if ($time < 815 || $time > 1730 && $day === 'Fri');
if ($time < 815 || $time > 1730 && $day === 'Sat');
if ($time < 815 || $time > 1730 && $day === 'Sun');
{echo 'Open';}
else {echo 'Closed';}
?>

A: I'd handle it this way. Set up an array of all your open times.  If you know you're closed on Saturday and Sunday, there's really no need to proceed with with checking times at that point, so kill the process there first.  Then simply find out what day of the week it is, look up the corresponding opening and closing times in your $hours array, create actual DateTime objects to compare (rather than integers).  Then just return the appropriate message.
function getStatus() {

    $hours = array(
        'Mon' => ['open'=>'08:15', 'close'=>'17:35'],
        'Tue' => ['open'=>'08:15', 'close'=>'17:35'],
        'Wed' => ['open'=>'08:15', 'close'=>'17:35'],
        'Thu' => ['open'=>'08:15', 'close'=>'22:35'],
        'Fri' => ['open'=>'08:15', 'close'=>'17:35']
    );

    $now = new DateTime();
    $day = date("D");

    if ($day == "Sat" || $day == "Sun") {
        return "Sorry we're closed on weekends'.";
    }

    $openingTime = new DateTime();
    $closingTime = new DateTime();

    $oArray = explode(":",$hours[$day]['open']);
    $cArray = explode(":",$hours[$day]['close']);

    $openingTime->setTime($oArray[0],$oArray[1]);
    $closingTime->setTime($cArray[0],$cArray[1]);

    if ($now >= $openingTime && $now < $closingTime) {
        return "Hey We're Open!";
    }

    return "Sorry folks, park's closed. The moose out front should have told ya.";
}

echo getStatus();

A: Use a switch statement:
$thisDate = date('D Hi');

$hoursOfOpArray = array("Mon_Open" => "815", "Mon_Close" => "1730", "Tue_Open" => "815", "Tue_Close" => "1730"); //repeat for all days too fill this array

$explode = explode(" ", $thisDate);
$day = $explode[0];
$time = (int)$explode[1];

switch($day) {
    case "Sun":
        $status = "Closed";
    break;
    case "Mon":
        $status = ($time < $hoursOfOpArray[$day . "_Open"] || $time > $hoursOfOpArray[$day . "_Close"]) ? "Closed" : "Open";
    break;
    //same as Monday case for all other days
}

echo $status;

This should also work:
echo ($day === 'Sun' || ($time < $hoursOfOpArray[$day . "_Open"]) || ($time > $hoursOfOpArray[$day . "_Close"])) ? "Closed" : "Open";

A: This one works, added remarks to explain as much as possible.
<?php

date_default_timezone_set('America/New_York');

// Runs the function
echo time_str();

function time_str() {

    if(IsHoliday())
    {
        return ClosedHoliday();
    }

$dow = date('D'); // Your "now" parameter is implied

    // Time in HHMM
    $hm = (int)date("Gi");

    switch(strtolower($dow)){
            case 'mon': //MONDAY adjust hours - can adjust for lunch if needed
                if ($hm >=    0 && $hm <  830) return Closed();
                if ($hm >= 830 && $hm < 1200) return Open();
                if ($hm >= 1200 && $hm < 1300) return Lunch();
                if ($hm >= 1300 && $hm < 1730) return Open();
                if ($hm >= 1730 && $hm < 2359) return Closed();
                break;
            case 'tue': //TUESDAY adjust hours
                if ($hm >= 830 && $hm < 1730) return Open();
                else return Closed();
                break;
            case 'wed': //WEDNESDAY adjust hours
                if ($hm >= 830 && $hm < 1730) return Open();
                else return Closed();
                break;
            case 'thu': //THURSDAY adjust hours
                if ($hm >= 830 && $hm < 1730) return Open();
                else return Closed();
                break;
            case 'fri': //FRIDAY adjust hours
                if ($hm >= 830 && $hm < 1730) return Open();
                else return Closed();
                break;
            case 'sat': //Saturday adjust hours
                return Closed();
                break;
            case 'sun': //Saturday adjust hours
                return Closed();
                break;

    }
}

// List of holidays
function HolidayList()
{
// Format: 2009/05/11 (year/month/day comma seperated for days)
return array("2016/11/24","2016/12/25");
}

// Function to check if today is a holiday
function IsHoliday()
{
// Retrieves the list of holidays
$holidayList = HolidayList();
// Checks if the date is in the holidaylist  - remove Y/ if Holidays are same day each year
if(in_array(date("Y/m/d"),$holidayList))
{
    return true;
}else
{
    return false;
}
}

// Returns the data when open
function Open()
{
    return 'Yes we are Open';
}

// Return the data when closed
function Closed()
{
    return 'Sorry We are Closed';
}

// Returns the data when closed due to holiday
function ClosedHoliday()
{
    return 'Closed for the Holiday';
}

// Returns if closed for lunch
// if not using hours like Monday - remove all this
// and make 'mon' case hours look like 'tue' case hours
function Lunch()
{
    return 'Closed for Lunch';
}

?>

A: $o = ['Mon' => [815, 1735], /*and all other days*/'Sat' => [815, 1300]];
echo (date('Hi')>=$o[date('D')][0] && date('Hi')<=$o[date('D')][1]) ? "open": "closed";

Done! And dont ask.


Q: Get the last line from each of a large number of files, transform them, and write all results to a single new file I have several hundreds of .csv files that are not logically named (contains numbers, characters, and special characters), all stored in a directory. Each file has large but unequal number of rows and columns. I do not need any information other than the last line of each file.
What would be an efficient way to use Mathematica to get the last line from each file, and summarize them to a new .csv file with the file name as the tag ?
@WReach suggested this, but I am not sure how to proceed, especially given the irregular titles.

A: A simple way to read the last line of a file uses ReadList to get all lines from the file and then returns the last element of the list:
lastLine[file_] := ReadList[file, String] // Last

This code ignores the possibility of an empty file.  If we care about such an eventuality, we can deal with it using a bit more logic:
lastLine[file_] := ReadList[file, String] /. {{} -> $Failed, ls_ :> Last @ ls}

This method reads the whole file to get the last line.  An alternate method will be shown below which avoids that, but for now let's look at the rest of the problem.
Here is a function that produces a summary that lists each CSV file in a directory along with the file's last line:
summarizeFiles[directory_] :=
  Module[{files}
  , files = FileNames["*.csv", directory]
  ; {FileNameTake[#, -1], lastLine @ #} & /@ files
  ]

It uses FileNames to get the CSV pathnames.  The filename portion of the path is extracted using FileNameTake and then our helper function lastLine is used to get the last line.
We can export the summary as a CSV like this:
$dataDirectory = FileNameJoin @ {NotebookDirectory[], "data"};
$outputFile = FileNameJoin @ {NotebookDirectory[], "result.csv"};

Export[$outputFile, summarizeFiles @ $dataDirectory]

This example assumes that the input data and output file reside in the notebook directory -- change this assumption to suit your taste.
The final result looks like this:
FilePrint @ $outputFile
(*
TI_2000_0.07_508.csv,"x[1] -> 8,x[2] -> 8,x[3] -> 7,x[4] -> 7,x[5] -> 0,x[6] -> 8,x[7] -> 0,x[8] -> 8,x[9] -> 7,x[10] -> 5"
TI_2000_0.13_846.csv,"x[1] -> 8,x[2] -> 7,x[3] -> 7,x[4] -> 7,x[5] -> 7,x[6] -> 7,x[7] -> 0,x[8] -> 7,x[9] -> 6,x[10] -> 5"
...
TI_2300_0.12_104.csv,"x[1] -> 8,x[2] -> 8,x[3] -> 8,x[4] -> 7,x[5] -> 8,x[6] -> 8,x[7] -> 4,x[8] -> 8,x[9] -> 4,x[10] -> 4"
TI_2300_0.1_966.csv,"x[1] -> 8,x[2] -> 8,x[3] -> 8,x[4] -> 8,x[5] -> 4,x[6] -> 4,x[7] -> 8,x[8] -> 8,x[9] -> 4,x[10] -> 4"
*)

Avoid Reading The Whole File
Now we return to the issue of reading the entire file to obtain the last line.  The first question is whether this overhead is really a problem.  For the sample files, I would suggest that it is not.  However, we can optimize if the actual data files are much larger in size, number, or both.  The trick is to start reading from somewhere near the end of the file when trying to find the last line.  The problem is, from which byte should we start reading given that we do not know the length of the last line?
If we can make some simplifying assumptions, then this is not a difficult problem.  The first assumption is that there is a known maximum line length (including the newline delimiter sequence).  We can start reading that far from the end of the file.  We can ignore any extra lines or line fragments picked up in the subsequent read.
The second assumption is that the file encoding is such that there are no variable-length multibyte character sequences in the file.  This is important because otherwise when we start reading from some arbitrary point in the file we might be unlucky enough to start in the middle of a multibyte sequence and read some very strange results.  This assumption appears to hold true for the sample data set.
Under these assumptions, the code to skip most of the file and read the last line looks like this:
ClearAll[lastLine]

lastLine[file_, maxLineBytes_:1024] :=
  Module[{s, line}
  , s = OpenRead[file]
  ; SetStreamPosition[s, Max[0, FileByteCount@file - maxLineBytes]]
  ; line = ReadList[s, String] /. {{} -> $Failed, ls_ :> Last @ ls}
  ; Close[s]
  ; line
  ]

SetStreamPosition is used to set the read position.  FileByteCount and maxLineBytes are used to calculate the starting read point.  Adjust maxLineBytes as desired.
If the simplifying assumptions are violated, then the methodology can still be used but the determination of the read starting point becomes more complex.  It would involve a trial-and-error process that reads from various candidate start points until the last line is found without any multi-byte errors.  It is left as an exercise to the reader to implement that additional logic :)
Edit
@librik points out that SetStreamPosition accepts negative positions indicating an offset from the end of the file.  Thus, the use of FileByteCount is unnecessary if the SetStreamPosition is changed to:
Quiet[SetStreamPosition[s, -maxLineBytes], SetStreamPosition::stmrng]

Quiet is necessary to guard against the case when the file length is less than maxLineBytes.


Q: File permission issues in android PFA the png, in this please note the permissions for the images inside app_themes directory. I am creating and adding files to this directory(app_themes) and during the process I do not specify any permissions at all.

Now I can see, for some png's the permission is rwxrwxrwx and for some others, it is just rw.
Though I do not specify any permission at all, why this difference in permission occurs?
I have no issues while I access a file with rwxrwxrwx from a different application, but cannot access those files which has only rw permission from a second application.
Please let me know how to resolve this by having the same permission - rwxrwxrwx for all the files.
This behaviour of android seems slightly strange!
Any help is much appreciated.
In first place, why android sets different permissions for different files, though the files are created using the same code?


Q: ORA-01017 error when conecting to Oracle Database Standard Edition 2.12.2.0.1.0 for Microsoft Windows x64 (64-bit) I've installed and created non-CDB database (single tenant) database. Created a user account using the SYS user, granted it the CONNECT and CREATE SESSION roles. When I attempt to login using the newly created account I get the "ORA-010170: invalid username/password; login denied" error.
I'm I missing something with respect to the Oracle 12c Standard database?? Since I've created a "normal" database I should be able to login with a non SYS account.
Thanks!!

A: Check the netca config. There needs to be an entry in tnsnames.ora.


Q: JDBC connection error for SQL Server Database I have a SQL server names as MS8AT09\AT09. I am able to login to the server through Microsoft SQL server Management studio. While trying to login to same server through JDBC I am facing the error as

"The TCP/IP connection to host XXXXXX, Port 1433 has failed.  Verify
  the connection properties.  Make sure that an instance of SQL Server
  is running on the host and accepting TCP/IP connections at the port.
  Make sure that TCP connections to the port are not blocked by a
  firewall".

Please help.

A: It is unlikely that a named instance is running on port 1433, unless you explicitly set it as such. I also suspect that SSMS is using shared memory (if local) or named pipes (if remote), unlike JDBC which is using TCP/IP (and I don't know how to set JDBC to use a different protocol).
From this documentation, it seems your connection string should be:
jdbc:sqlserver://MS8AT09;instanceName=AT09;...

With no port designation. You could also try using the IP address instead of the name, in case name resolution is hampered for some reason.
Please check what port the instance is running on (look at SQL Server Configuration Manager)...

...and confirm your connection string does not hard-code a port that is different (JDBC might ). Do not hard-code the dynamic port, because it may not be the port used next time SQL Server starts. From Microsoft's documentation:

We recommend that the port number always be specified, as this is more secure than using sqlbrowser.

So, you may want to set your named instance to run on a specific port number, instead of using a dynamic port (the default), and then hard-coding that port number in the JDBC connection string. You can use the one that the instance was using dynamically, since you know it isn't in use by anything else. Also see KB #823938. So your connection string would become (assuming you used port 56737):
jdbc:sqlserver://192.168.0.65;instanceName=AT09;port=56737;...


Q: what is placemark in flutter geocoding I m very beginner for flutter google maps. I just want to know what is placemark in flutter geocoding and I just need to understand the below code. Thank you so much for any help.
  _getAddress() async {
try {
  List<Placemark> p = await placemarkFromCoordinates(
      _currentPosition.latitude, _currentPosition.longitude);
  Placemark place = p[0];

  setState(() {
    _currentAddress =
        "${place.name}, ${place.locality}, ${place.postalCode}, ${place.country}";
    startAddressController.text = _currentAddress;
    _startAddress = _currentAddress;
  });
} catch (e) {
  print(e);
}

}

A: Placemark is a class that contains information like place's name, locality, postalCode, country and other properties. See Properties in the documentation.
placemarkFromCoordinates is a method that returns a list of Placemark instances found for the supplied coordinates.
Placemark place = p[0]  just gets the first Placemark from the list you got from placemarkFromCoordinates method.
The code inside the setState method just updates the _currentAddress to the place info you got from the Placemark place and then passes its value to the startAddressController.text and _startAddress.

A: Placemark() class helps you to get certain information like city name, country name, local code based on google map api.
Before you use Placemark() in your app, you need to get decoded string info from google map api
https://maps.googleapis.com/maps/api/geocode/json?latlng='.$request->lat.','.$request->lng.'&key='."your api key here"

From your server side code should return json response and then
_placeMark = Placemark(name: _address)

Now _placeMark would help you get access to city, country, local code etc.
For more go there
https://www.dbestech.com/tutorials/flutter-google-map-geocoding-and-geolocator


Q: docker build how to run intermediate containers with centos:systemd I am trying to build a docker image that is based on centos:systemd. In my Dockerfile I am running a command that depends on systemd running, this fails with the following error:
Failed to get D-Bus connection: Operation not permitted
error: %pre(mod-php-7.1-apache2-zend-server-7.1.7-16.x86_64) scriptlet failed, exit status 1
Error in PREIN scriptlet in rpm package mod-php-7.1-apache2-zend-server-7.1.7-16.x86_64

how can I get the intermediate containers to run with --privileged and mapping -v /sys/fs/cgroup:/sys/fs/cgroup:ro ?
If I comment out the installer and just run the container and manually execute the installer it works fine.
Here is the Dockerfile
FROM centos/systemd
COPY ./ZendServer-9.1.0-RepositoryInstaller-linux.tar.gz /opt
RUN tar -xvf /opt/ZendServer-9.1.0-RepositoryInstaller-linux.tar.gz -C /opt/
RUN /opt/ZendServer-RepositoryInstaller-linux/install_zs.sh 7.1 java --automatic

A: If your installer needs systemd running, I think you will need to launch a container with the base centos/systemd image, manually run the commands, and then save the result using docker commit. The base image ENTRYPOINT and CMD are not run while child images are getting built, but they do run if you launch a container and make your changes. After manually executing the installer, run docker commit {my_intermediate_container} {my_image}:{my_version}, replacing the bits in curly braces with the container name/hash, your desired image name, and image version.
You might also be able to change your Dockerfile to launch init before running your installer. I am not sure if that will work here in the context of building an image, but that would look like:
FROM centos/systemd
COPY ./ZendServer-9.1.0-RepositoryInstaller-linux.tar.gz /opt
RUN tar -xvf /opt/ZendServer-9.1.0-RepositoryInstaller-linux.tar.gz -C /opt/ \
    && /usr/sbin/init \
    && /opt/ZendServer-RepositoryInstaller-linux/install_zs.sh 7.1 java --automatic

A: A LAMP stack inside a docker container does not need systemd - I have made to work with the docker-systemctl-replacement script. It is able to start and stop a service according to what's written in the *.service file. You could try it with what the ZendServer is normally doing outside a docker container.


Q: What happens if I simply change a mount point from /usr/local to /usr? I have this disk set up like so:
/dev/sda3 mounted to: /usr/local

if I just change this (in fstab, right?) to:
/dev/sda3 mounted to: /usr

What happens? Do I lose anything or does it all just default to the new mount point?

A: If you just changed the mount point in your fstab, without copying files over, then the contents that were in /usr/local/ will appear in /usr/. The original contents of /usr/ would be hidden from the OS.
Because /usr/ contains many of your system settings, libraries, binaries, and other important files, I am sure that your system would not work properly after remapping the drive's mount point.
In effect, the OS would not be able to find anything it would be looking for in /usr/ or its subdirectories (including /usr/local). The /usr/ directory is full of libraries which include symbolic links, and some of it's files have very specific ownership and permissions requirements.
I would not suggest changing the mount points, copying, or moving these files unless you have to.


Q: Select Similar Titles From a Table With a Single Query I would like to query a single table and select any entries which have similar titles. A similar title is a title with exactly the same string (case insensitive) but with "(fresh)" appended. The result should return the id and title of any matches.
For example if this was my table:
ID    TITLE
1     Bacon
2     Eggs
3     Eggs (fresh)
4     ketchup
5     Ketchup (Fresh)

Then I'd like to extract:
array(
    array(
        id => 2
        title => Eggs
    ),
    array(
        id => 3
        title => Eggs (fresh)
    )
),
array(
    array(
        id => 4
        title => ketchup
    ),
    array(
        id => 5
        title => Ketchup (Fresh)
    )
)

Currently I'm using two separate queries. First I select all titles and then I do a loop to find which entries have those titles with "(fresh)" appended. I'm sure there must be a more efficient way to extract these matching titles in a single query but I can't put my finger on it.

A: Try this:
select src.id ID_wo_fresh, tgt.id ID_w_fresh, src.title
from tbl src
inner join tbl tgt on src.title= replace(replace(tgt.title,' (fresh)',''),' (Fresh)','')
and src.id <> tgt.id

This will return the ID of product without 'fresh' or 'Fresh' in the name, the ID with 'fresh' or 'Fresh' in the name and the name itself. Note that this will exclude rows which don't find a match i.e. only have the name with or without suffix, but not both. To show for all rows, use left join instead.


Q: Is there a way to autosave in Dungeons of Dredmor? Dredmor is a fun game, but it occasionally crashes on my computer.  Therefore, I end up saving often to avoid losing progress.  Going into the menu to save means that first I have to close all of my sub screens (ie, I have to close my inventory, dismiss my Lutefisk cube, close my character window, etc).  This is kind of irritating.  I'd prefer some sort of auto-save feature, or, failing that, a quicksave button.
Is there some way to do this in Dredmor?  I haven't found anything in any of the menus about this.  I've seen that the game supports mods, but I don't know where to look for Dredmor mods, and if one of this type exists.

A: The game automatically saves whenever you switch floors. My anti-crash approach is, whenever I pass a staircase (either up or down), take it and immediately return. Staircases are common enough that this is a pretty effective way of periodically saving. It also works in permanent-death mode.
Just be careful - steps to unvisited areas can lead you to a room full of monsters, and even stairs to a visited location may be dangerous, since monsters slowly spawn in visited areas. So although it's usually easy to get back, don't do this if you're really low on health.


Q: Using Directive C++ Implementation In C, if I use #include "someFile.h", the preprocessor does a textual import, meaning that the contents of someFile.h are "copy and pasted" onto the #include line. In C++, there is the using directive. Does this work in a similar way to the #include, ie: a textual import of the namespace?
using namespace std; // are the contents of std physically inserted on this line?

If this is not the case, then how is the using directive implemented`.

A: The using namespace X will simply tell the compiler "when looking to find a name, look in X as well as the current namespace". It does not "import" anything. There are a lot of different ways you could actually implement this in a compiler, but the effect is "all the symbols in X appear as if they are available in the current namespace".
Or put another way, it would appear as if the compiler adds X:: in front of symbols when searching for symbols (as well as searching for the name itself without namespace).
[It gets rather complicated, and I generally avoid it, if you have a symbol X::a and local value a, or you use using namespace Y as well, and there is a further symbol Y::a. I'm sure the C++ standard DOES say which is used, but it's VERY easy to confuse yourself and others by using such constructs.]
In general, I use explicit namespace qualifiers on "everything", so I rarely use using namespace ... at all in my own code.

A: No, it does not. It means that you can, from this line on, use classes and functions from std namespace without std:: prefix. It's not an alternative to #include. Sadly, #include is still here in C++.
Example:
#include <iostream>

int main() {
  std::cout << "Hello "; // No `std::` would give compile error!
  using namespace std;
  cout << "world!\n"; // Now it's okay to use just `cout`.
  return 0;
}

A: Nothing is "imported" into the file by a using directive.  All it does is to provide shorter ways to write symbols that already exist in a namespace.  For example, the following will generally not compile if it is the first two lines of a file:
#include <string>
static const string s("123");

The <string> header defines std::string, but string is not the same thing.  You haven't defined string as a type, so this is an error.
The next code snippet (at the top of a different file) will compile, because when you write using namespace std, you are telling the compiler that string is an acceptable way to write std::string:
#include <string>
using namespace std;
static const string s("123");

But the following will not generally compile when it appears at the top of a file:
using namespace std;
static const string s("123");

and neither will this:
using namespace std;
static const std::string s("123");

That's because using namespace doesn't actually define any new symbols; it required some other code (such as the code found in the <string> header) to define those symbols.
By the way, many people will wisely tell you not to write using namespace std in any code.  You can program very well in C++ without ever writing using namespace for any namespace.  But that is the topic of another question that is answered at Why is "using namespace std" considered bad practice?

A: No, #include still works exactly the same in C++.
To understand using, you first need to understand namespaces. These are a way of avoiding the symbol conflicts which happen in large C projects, where it becomes hard to guarantee, for example, that two third-party libraries don't define functions with the same name. In principle everyone can choose a unique prefix, but I've encountered genuine problems with non-static C linker symbols in real projects (I'm looking at you, Oracle).
So, namespace allows you to group things, including whole libraries, including the standard library. It both avoids linker conflicts, and avoids ambiguity about which version of a function you're getting.
For example, let's create a geometry library:
// geo.hpp
struct vector;
struct matrix;

int transform(matrix const &m, vector &v); // v -> m . v

and use some STL headers too:
// vector
template <typename T, typename Alloc = std::allocator<T>> vector;

// algorithm
template <typename Input, typename Output, typename Unary>
void transform(Input, Input, Output, Unary);

But now, if we use all three headers in the same program, we have two types called vector, two functions called transform (ok, one function and a function template), and it's hard to be sure the compiler gets the right one each time. Further, it's hard to tell the compiler which we want if it can't guess.
So, we fix all our headers to put their symbols in namespaces:
// geo.hpp
namespace geo {
    struct vector;
    struct matrix;

    int transform(matrix const &m, vector &v); // v -> m . v
}

and use some STL headers too:
// vector
namespace std {
    template <typename T, typename Alloc = std::allocator<T>> vector;
}

// algorithm
namespace std {
    template <typename Input, typename Output, typename Unary>
    void transform(Input, Input, Output, Unary);
}

and our program can distinguish them easily:
#include "geo.hpp"
#include <algorithm>
#include <vector>

geo::vector origin = {0,0,0};

typedef std::vector<geo::vector> path;

void transform_path(geo::matrix const &m, path &p) {
    std::transform(p.begin(), p.end(), p.begin(),
                   [&m](geo::vector &v) -> void { geo::transform(m,v); }
                   );
}

Now that you understand namespaces, you can also see that names can get pretty long. So, to save typing out the fully-qualified name everywhere, the using directive allows you to inject individual names, or a whole namespace, into the current scope.
For example, we could replace the lambda expression in transform_path like so:
#include <functional>
void transform_path(geo::matrix const &m, path &p) {
    using std::transform;              // one function
    using namespace std::placeholders; // an entire (nested) namespace

    transform(p.begin(), p.end(), p.begin(),
              std::bind(geo::transform, m, _1));
    //                                 this ^ came from the
    //                                 placeholders namespace
    // ^ note we don't have to qualify std::transform any more
}

and that only affects those symbols inside the scope of that function. If another function chooses to inject the geo::transform instead, we don't get the conflict back.


Q: What does +Mat mean? Lookint at the definition of the Flow class on https://doc.akka.io/api/akka/current/akka/stream/scaladsl/Flow.html, it has the
following signature:
 final class Flow[-In, +Out, +Mat]

The question is, why is the type of the third parameter is +Mat? I thought, +Mat makes only sense on Sink, because
Sink consumes the stream.
Even the Source has the +Mat:
final class Source[+Out, +Mat]

A: Each stage materializes in some value, this is what gives you the ability to obtain a mechanism to push elements into the stream via a SourceQueueWithComplete when you use a Source.queue.
Even a Flow could materialize in some value but this isn't common, in this cases you'll see that the materialized value is NotUsed.


Q: Docker compose network doesn't bind ip address I'm trying to run a selenium grid from a docker compose file. In this docker compose I set an Ip address, because I want to run test on a jenkins from another docker image. Only when I try to run my tests with the setup ip address it gives following error
 org.openqa.selenium.remote.UnreachableBrowserException at RemoteWebDriver.java:573
        Caused by: java.net.UnknownHostException at InetAddress.java:800

This is my docker compose file
version: "3"
services:
  hub:
    image: selenium/hub
    networks:
      testing_net:
        ipv4_address: 172.28.1.1
    ports:
      - "4444:4444"

    environment:
      GRID_MAX_SESSION: 16
      GRID_BROWSER_TIMEOUT: 3000
      GRID_TIMEOUT: 3000

  chrome:
    image: selenium/node-chrome
    container_name: web-automation_chrome
    depends_on:
      - hub
    environment:
      HUB_PORT_4444_TCP_ADDR: hub
      HUB_PORT_4444_TCP_PORT: 4444
      NODE_MAX_SESSION: 4
      NODE_MAX_INSTANCES: 4
    volumes:
      - /dev/shm:/dev/shm
    ports:
      - "9001:5900"
    links:
      - hub
    networks:
      testing_net:
        ipv4_address: 172.28.1.2

  firefox:
    image: selenium/node-firefox
    container_name: web-automation_firefox
    depends_on:
      - hub
    environment:
      HUB_PORT_4444_TCP_ADDR: hub
      HUB_PORT_4444_TCP_PORT: 4444
      NODE_MAX_SESSION: 2
      NODE_MAX_INSTANCES: 2
    volumes:
      - /dev/shm:/dev/shm
    ports:
      - "9002:5900"
    links:
      - hub
    networks:
      testing_net:
        ipv4_address: 172.28.1.3
networks:
  testing_net:
    ipam:
        driver: default
        config:
            - subnet: 172.28.0.0/16

When I go to 172.28.1.1:4444 I don't reach the selenium hub


Q: Math: Division Problems Generator I am making a program that takes asks if you want to do Addition, Subtraction, Multiplication, and Division. It then asks how many questions. I have everything working but Division. I want to make sure that there will be no remainder when doing the division problem. I don't know how to make this work.
      else if (player==4) {

      System.out.print("How many questions would you like?-->"); player =
      in.nextInt(); numQuestions= player;

      do{

      //question
          do {
              do{
          num1 = (int) (Math.random() * 100);
          num2 = (int) (Math.random() *10);

              }while (num2 > num1);
          } while (num1 % num2 == 0);

              compAnswer = num1 / num2;

                  System.out.println(num1+" / " + num2 + "=");
                  System.out.print("What's your answer? -->");
                  player = in.nextInt();
                    if (player == compAnswer) {
                        System.out.println(" That's right, the answer is "
                                + compAnswer);
                        System.out.println("");
                        score++;
                    } else {
                        System.out.println("That's wrong! The answer was "
                                + compAnswer);
                        System.out.println("");

                    }
            //x++;

      }while( x < numQuestions + 1 );

      System.out.println("");
      System.out.println("Thanks for playing! Your score was " + score +
      "."); }

A: You are specifically picking numbers where there are a reminder. You can just loop while there is a reminder instead:
} while (num1 % num2 != 0);

However, you won't need to loop at all. If you pick the second operand and the answer, you can calculate the first operand:
num2 = (int) (Math.random() *10);
compAnswer = (int) (Math.random() * 10);

num1 = num2 * compAnswer;


Q: Reporting plugin for Opensource chef Is there any Plugin to add reporting feature to an opensource chef as it is for Enterprise chef?
I tried installing using below command

      /opt/chef/embedded/bin/gem install knife-reporting

knife-reporting gem got install but no related commands are found when i run knife

A: Knife-Reporting plugin is used to analyze the reports sent by clients to the server.
[knife runs help ] run this command to find the new functionalists given by knife reporting.
Question Seems to be a similar question.
chef doc has the code for handling the report and sending it to the server. It has to be shipped with chef handler cookbook and enabled before chef run.
For getting json files which contains all info about node run as report.
Get chef_handler from community.
Add recipe[chef_handler::json_file] in your run list. This will get the report as a json file and store in your /var/chef/reports (can be changed in chef_handler cookbook) in client machine.


Q: Unable to edit any columns in my C# DataGridView - would anyone know why? I'm trying to enabled editing for a number of columns in my DataGridView. Now, before anyone suggestions I should read the MSDN article: How to: Specify the Edit Mode for the Windows Forms DataGridView Control, I already have.
In summary (and I quote):

*

*The underlying data source supports editing.

*The DataGridView control is enabled.

*The EditMode property value is not EditProgrammatically.

*The ReadOnly properties of the cell, row, column, and control are all set to false.

All of that is simple and common sense. I've confirmed that the Enabled = true. I've confirmed that the EditMode is EditOnKeystrokeOrF2 I've confirmed that all the columns (except one) are ReadOnly = false.
What I find interesting is the first line:-

The underlying data source supports editing.

Now, what I'm doing is the following, to bind the data to the DGV :-
// Grab all the Foos.
var foos = (from x in MyRepository.Find()
            select new
                      {
                          x.Foo1,
                          x.Foo2,
                          ...
                          x.FooN
                       }).ToList();

// Now lets bind this result to the GridView.
dataGridView2.DataSource = foos;

Which I thought was the right way to do things..
What i was planing on doing was, when the cell is changed and the user then leaves the cell, that's where I was planning on grabbing the data that was just changed (figure this out manually) and then manually update the DB.
Is this the right way to do things?

A: In this case, the underlying data source does not support editing since the properties of anonymous types are read only.  Per the C# language spec:

The members of an anonymous type are a sequence of read-only properties inferred from the anonymous object initializer used to create an instance of the type.

Instead, you might want to define a display class with editable properties for the values you want to display and create instances of that class.

A: I had this problem with an unbound DGV.  I fixed it by setting the ReadOnly property of each ROW. Both the DGV and the Columns were not ReadOnly, but the Rows were somehow being set R/O perhaps when I set them using a collection.
So:
foreach (var r in Lst)
{
   ...
   dgv.Rows[dgv.Rows.Count - 1].ReadOnly = false;
}


Q: How to clear the session using a button and javascript Session is client side staff, but is it possible through clear it using javascript code?
I would like too have the idea like this and ,can it convert  to jquery format? Thank you.
js
    $(function(){
  $("#closeTab").click(function() {
    window.parent.$('#tt').tabs('close','Create List');
        $.post("clear.php",function(data){
      });
  });
});

php
    <?
if (isset($_SESSION['lname']))
unset($_SESSION['lname']);
if (isset($_POST['creminder']))
unset($_SESSION['creminder']);
?>

Is this one ok ?

A: make an ajax call to the server and let your server page kills/ends the session
HTML
 Kill Session

Script
$(function(){

  $("#aKill").click(function(){
        $.post("serverpage.php",function(data){
        // if you want you can show some message to user here
     });
});

and in your serverpage.php, Execute the PHP script to terminate the session.

A: Create a separate file to clear the session only. clearsession.php
session_start();
session_destroy();

Now, make a simple request
$("#aKill").click(function(){
    $.get("clearsession.php");
}

A: The below covers the basics more or less.
The Function:
function destroySession(){
  var theForm = $("#yourForm");
  //we don't need any ajax frame.
  theForm.each(function(){ this.reset() });
  $.ajax({
    url: 'destroysession.php',
    type: 'post',
    data: 'sure=1', //send a value to make sure we want to destroy it.
    success: function(data);
      alert(data);
    }
  });
}

The PHP (destroysession.php):
<?php
  //whatever logic is necessary

  if(!empty($_POST['sure'])){
     $sure = $_POST['sure'];
     if($sure == 1){
       //logic to destroy session
       echo 'Session Destroyed!';
     }else if($sure != 1){
       //logic to perform if we're being injected.
       echo 'That value is incorrect. What are you doing over there?';
     }
  }else{
     //logic to perform if we're being injected.
     echo 'That value is incorrect. What are you doing over there?';
  }
?>

The HTML:
<input type='button' value='reset' onclick='destroySession()'>


Q: Inheriting class definition from parent class I am building Grape Entities inside my Rails models as described here:
https://github.com/ruby-grape/grape-entity#entity-organization
Currently I am creating default values automatically, based on the column hash of the model itself.
So I have a static get_entity method that exposes all the model's columns:
class ApplicationRecord < ActiveRecord::Base

  def self.get_entity(target)
    self.columns_hash.each do |name, column|
      target.expose name, documentation: { desc: "Col #{name} of #{self.to_s}" }
    end
  end

end

And then I have here an example Book model using it inside the declared Entity subclass (the comment also shows how I can override the documentation of one of the model's column):
class Book < ActiveRecord::Base

  class Entity < Grape::Entity
    Book::get_entity(self)
    # expose :some_column, documentation: {desc: "this is an override"}
  end

end

The downside with this approach is that I always need to copy and paste the class Entity declaration in each model I want the Entity for.
Can anybody help me out generating the class Entity for all child of ApplicationRecord automagically? Then if I need overrides I will need to have the Entity declaration in the class, otherwise if the default declaration is enough and can leave it as it is.
NOTE:
I cannot add class Entity definition straight inside ApplicationRecord because, Entity class should call get_entity and get_entity depends on column_hash of Books.
SOLUTION:
ended up doing this thanks to brainbag:
def self.inherited(subclass)
  super
  # definition of Entity
  entity = Class.new(Grape::Entity)
  entity.class_eval do
    subclass.get_entity(entity)
  end
  subclass.const_set "Entity", entity

  # definition of EntityList
  entity_list = Class.new(Grape::Entity)
  entity_list.class_eval do
    expose :items, with: subclass::Entity
    expose :meta, with: V1::Entities::Meta
  end
  subclass.const_set "EntityList", entity_list
end

def self.get_entity(entity)
  model = self
  model.columns_hash.each do |name, column|
    entity.expose name, documentation: { type: "#{V1::Base::get_grape_type(column.type)}", desc: "The column #{name} of the #{model.to_s.underscore.humanize.downcase}" }
  end
end

Thanks!

A: I haven't used Grape so there may be some extra magic here that you need that I don't know about, but this is easy to do in Ruby/Rails. Based on your question "generating the class Entity for all child of ApplicationRecord automagically" you can do this:
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  class Entity < Grape::Entity
    # whatever shared stuff you want
  end
end

Book will then have access to the parent Entity:
> Book::Entity
=> ApplicationRecord::Entity

If you want to add extra code only to the Book::Entity, you can subclass it in Book, like this:
class Book < ApplicationRecord
  class Entity < Entity # subclasses the parent Entity, don't forget this
    # whatever Book-specific stuff you want
  end
end

Then Book::Entity will be its own class.
> Book::Entity
=> Book::Entity

To combine this with your need for get_entity to be called on an inherited class, you can use the #inherited method to automatically call get_entity any time ApplicationRecord is subclassed:
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  def self.get_entity(target)
    target.columns_hash.each do |name, column|
      target.expose name, documentation: { desc: "Col #{name} of #{self.to_s}" }
    end
  end

  def self.inherited(subclass)
    super
    get_entity(subclass)
  end

  class Entity < Grape::Entity
    # whatever shared stuff you want
  end
end


Q: Nested resource parameters with Rails and Backbone.js I've got this issue where I am seeing the incoming parameters nested incorrectly. Here's some of the setup:
In routes.config I've defined:
resources :events do
  resources :guests
end

As a result I end up with the right controller/action paths. The ones I'll call out here are specified as such:
POST   /events/:event_id/guests(.:format)                guests#create

no surprises here. Now in the Guest model I have an association with a Contact model such that A Guest belongs to a Contact and a Contact has many Guests. This works correctly. Nothing tricky here either.
The backbone.js model for this is defined as such:
define('GuestModel', [
  'underscore',
  'backbone'
], function(_, Backbone) {

  var Guest = Backbone.Model.extend({
    idAttribute: "id",
    url: function() {
      return '/events/' + this.get('event_id') + '/guests';
    }
  });

  return Guest;
});

A quick caveat to this: I am providing the backend API support for the frontend and the guy who is implementing the front end (as my immediate client) doesn't use the rails asset pipeline at all. I have no control over this and as a result this is the bit of code I can't really affect w/o first convincing him it's the way to go.
The problem is that in the GuestsController#create method I'm expecting to see params that look like this:
{
    :event_id => 1,
    :guest => {
      :contact => {
        ...all the contact parameters...
      },
      ...other guest params...
     },
     ...other railsy parameters...
    }
Instead I'm getting:
{
    :event_id => 1,
    :contact => {
      ...all the contact parameters...
    },
    ...other guest params...,
    ...other railsy parameters...
   }
Because there's no :guest object in the params at the top level, none of this is picked up by the standard Rails create behavior and I find myself having to basically pull out the contact and other guest params and put them manually into a hash object. Or I can pull out the event id and other Railsy params and use the params as a whole.  But I can't believe this hasn't ever been seen or addressed by someone before me so I'm hoping someone can either tell me what the standard approach to this is, or what I'm doing wrong at a more fundamental level.
Thanks in advance, and let me know if I've left out some information or code you need to see...
jd


Q: How to pass variable parameter into XPath expression? I want to pass a parameter into an XPath expression.
(//a/b/c[x=?],myParamForXAttribute)

Can I do this with XPath 1.0 ? (I tried string-join but it is not there in XPath 1.0)
Then how can I do this ?
My XML looks like

  <c>
   <x>val1</x>
   <y>abc</y>
  </c>
  <c>
   <x>val2</x>
   <y>abcd</y>
  </c>

I want to get <y> element value where x element value is val1
I tried //a/b/c[x='val1']/y but it did not work.

A: Given that you're using the Axiom XPath library, which in turn uses Jaxen, you'll need to follow the following three steps to do this in a thoroughly robust manner:

*

*Create a SimpleVariableContext, and call context.setVariableValue("val", "value1") to assign a value to that variable.

*On your BaseXPath object, call .setVariableContext() to pass in the context you assigned.

*Inside your expression, use /a/b/c[x=$val]/y to refer to that value.

Consider the following:
package com.example;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.common.AxiomText;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axiom.om.xpath.DocumentNavigator;
import org.jaxen.*;

import javax.xml.stream.XMLStreamException;

public class Main {

    public static void main(String[] args) throws XMLStreamException, JaxenException {
        String xmlPayload="<parent><c><x>val1</x><y>abc</y></c>" +
                                        "<c><x>val2</x><y>abcd</y></c>" +
                          "</parent>";
        OMElement xmlOMOBject = AXIOMUtil.stringToOM(xmlPayload);

        SimpleVariableContext svc = new SimpleVariableContext();
        svc.setVariableValue("val", "val2");

        String xpartString = "//c[x=$val]/y/text()";
        BaseXPath contextpath = new BaseXPath(xpartString, new DocumentNavigator());
        contextpath.setVariableContext(svc);
        AxiomText selectedNode = (AxiomText) contextpath.selectSingleNode(xmlOMOBject);
        System.out.println(selectedNode.getText());
    }
}

...which emits as output:
abcd

A: It depends on the language in which you're using XPath.
In XSLT:
 "//a/b/c[x=$myParamForXAttribute]"

Note that, unlike the approach above, the three below are open to XPath injection attacks and should never be used with uncontrolled or untrusted inputs; to avoid this, use a mechanism provided by your language or library to pass in variables out-of-band.  [Credit: Charles Duffy]
In C#:
String.Format("//a/b/c[x={0}]", myParamForXAttribute);

In Java:
String.format("//a/b/c[x=%s]", myParamForXAttribute);

In Python:
 "//a/b/c[x={}]".format(myParamForXAttribute)


Q: php Error: Resourse id #4 for($i = 0;$i<10;$i++)
        {
            $query1 ="SELECT `id` FROM radcheck ORDER BY `id` DESC LIMIT 1;";
            $lololo= mysql_query($query1) or die(mysql_error());
            //echo $lololo;
            $query = "INSERT INTO radcheck (username,attribute,op,value) VALUES ('teleuser".$lololo."','Cleartext-Password',':=','$arr1[$i]')";
            mysql_query($query) or die(mysql_error());
        }

I am trying to retrieve my latest id value to append with my username. And the value retrieve always be 'Resource id #4'.
Is there anyway to solve it ?
Thank you.

A: Mysql doesn't support TOP that is for SQL Server.
Instead of using TOP you can use mysql LIMIT so your query would be:
SELECT `id` FROM radcheck ORDER BY `id` DESC LIMIT 1;

A: You do not have to use single quotes around column names. if you need to escape it use backticks. And TOP is not mysql syntax. You have to use limit
SELECT `id` FROM radcheck ORDER BY `id` DESC limit 1

Do not longer use the depricated mysql_* API. Use mysqli_* or PDO

A: Remove the 's around field names -
"SELECT TOP 1 id FROM radcheck ORDER BY id DESC";

But as Daan told it will not work for mysql, then ORDER & LIMIT will do the trick.
"SELECT id FROM radcheck ORDER BY id DESC LIMIT 1";

A: i hope you never mind trying this pattern
 Select id from radcheck WHERE id=1 ORDER BY 'id' DESC ;


Q: Highcharts center on x and y axis offset First, for reference I'm trying to mimic this chart:

Currently my chart looks like this: http://jsfiddle.net/eA4Df/
What's the option to center the (1, 1) coordinates of the chart but still display all of the bubble data?
Current highcharts options are:
    chart: {
        type: 'bubble',
        zoomType: 'xy'
    },
    legend: {
        enabled: false
    },
    credits: {
        enabled: false
    },
    title: {
        text: 'Highcharts Bubbles'
    },
    xAxis: {
        plotLines: [{
            color: '#000000',
            width: 2,
            value: 1
        }]
    },
    yAxis: {
        plotLines: [{
            color: '#000000',
            width: 2,
            value: 1
        }]
    }

A: You can try to set min and max values for the axis:
xAxis: {
    plotLines: [{
        color: '#000000',
        width: 2,
        value: 1
    }],
    max: 2,
    min: 0
},
yAxis: {
    plotLines: [{
        color: '#000000',
        width: 2,
        value: 1
    }],
     max: 2,
    min: 0
},

Example SQL FIDDLE HERE

A: Instaed of plotLines, you can move your axis by offset parameter or use plugin


Q: CS50 Caesar multiple errors I'm working on Caesar of CS50 and I don't know what's wrong with this code. I keep getting 5 errors and 1 warning (scroll down). I have done my best so far to fix it but I honestly don't know what to do.
The program is essentially a Caesar cipher encoder. When I launch the program it should as me for a key (which is a number) and the message I'm trying to cipher, it should then give me the output which is the cipher.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
bool check_valid_key(string s);

int main(int argc, string argv[])
{
    if (argc != 2 || !check_valid_key(argv[1]))
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    int key = atoi(argv[1]);

    string plaintext = get_string("plaintext: ");

    printf("ciphertext: ");
    for (int i = 0, len = strlen(plaintext); i < len; i++)
    {
        char c = plaintext[i];
        if (isalpha(c))
        {
            char m = 'A';
            if (islower(c))
                m = 'a';
            printf("%c", (c - m + key) % 26 + m);
        }
        else
            printf("%c", c);
    }
    printf("\n");
 }

 bool check_valid_key(string s);
 {
     for (int i = 0, len = strlen(s); i < len; i++)
        if (!isdigit(s[i]))
            return false;
    return true;
 }

A: it would be useful to use a better text editor to catch syntax errors before you even compile. here are the syntax errors your program has.
the len should be assigned first like this
for (int i = 0, len = strlen(plaintext); i < len; i++) {

but that's in efficient since the strlen() is called at each iteration, do this instead.
int len = strlen(plaintext); // it's in efficient to calculate length each iteration.
for (int i = 0; i < len; i++) {

condition for if statements should be surrounded by brackets.
if (islower(c)) // if (cond) <-- brackets are importants

your function definition has a semicolon which is also a syntax error
bool check_valid_key(string s) // ; <-- remove this semicolon
{
}


Q: merging result of one observable to another I have a situation which I haven't been able to solve via RxJava2 operators.
I have a list of "Matches" I retrieve from Room. Here is my Match POJO.
public class Match {
@PrimaryKey
private int id;

@Ignore
Team rivalTeam;

}
Here is my Dao for this table.
@Dao
public interface MatchDao {
    @Query("select * from `match` where homeTeamId= :homeTeamId")
    Single<List<Match>> getMatchesByTeamId(int homeTeamId);

}

My target is to create an observable which will pull out these matches and then merge it with an observable which would be returning the rivalTeam.
Here is my Team Dao
@Dao
public interface TeamDao {

    @Query("select * from teams where id = :teamId")
    Single<Team> getTeamById(int teamId);

}

What I have achieved is this.
private Single<List<Match>> fetchMatches(Team team) {
        return matchDao.
                getMatchesByTeamId(team.getId()).toObservable().
                flatMapIterable(matches -> matches).
                map(match -> teamDao.getTeamById(**match.getRivalId()**).toObservable() // this doesn't work ofcourse since map can't return an observable.);
    }

I know I have to perhaps zip both observables , but how would I go about doing that since the second observable is dependent on the first?.
If zip would have worked on a single source , I would have been able to do a
match.setRivalTeam(team) in the zipper method.
Hints?


Q: Transfer WP from subdomain to main domain I've set up a redesign of a site in the subdomain to work out any kinks and to make sure everythings working ok before setting it up on the root domain. I've looked up transfers but have only found info on transfering from host to host or from local to host.
I've set up a wordpress site that was previously locally hosted, so I know how to transfer a site, I'm just hoping that there is an easier way to do this since this is transferring from subdomain to domain - like hopefully without having to reinstall wordpress...
Any solutions or suggestions welcome.
Thanks in advance.

A: After copying to the main-directory change the values in then wp-config.php and .htaccess files for the new localtion. Then you have to change the values in the database. You need 3 SQL-Statements, which you can execute with phpMyAdmin for example.
First change the options-Table
UPDATE wp_options
SET option_value = replace(option_value, 'http://www.example.com/subdir', 'http://www.example.com')
WHERE option_name = 'home' OR option_name = 'siteurl';

Second change the values for the guid in the posts-table
UPDATE wp_posts
SET guid = replace(guid, 'http://www.example.com/subdir', 'http://www.example.com');

Third change the URL in the posts-Table
UPDATE wp_posts
SET post_content = replace(post_content, 'http://www.example.com/subdir', 'http://www.example.com');

If you have used another prefix then wp_ you have to change it in the 3 SQL-Statements. Pay attention at the example domain-names, too.

A: wordpress.org-support-moving-wordpress helped me, on a virtual machine running ubuntu, use the from existing server., i used the velvet plugin for url updating/re-write and seems to work maybe 1 or 2 broken images or attachments but it done 99% of the work.


Q: How do I dynamically make a field type number in Angular? I am generating an HTML form from JSON using some custom directives. Part of the JSON include restrictions on the values of the fields.
One of the restrictions the JSON puts on fields is a positive decimal type. The code I use in my link function to accomplish this:
//...snip
if (<this field should be number>) {
   elem.attr("type", "number");
}

This successfully changes the field type to number. However, there are two problems:

*

*It does not allow negative numbers

*Every time I type a key stroke (even for valid numbers), it throws a number format exception. For example, if I type "123" I will get the following 3 errors:

*

*Error: [ngModel:numfmt] 1 to be a number

*Error: [ngModel:numfmt] Expected 12 to be a number

*Error: [ngModel:numfmt] Expected 123 to be a number
I know that the model is successfully changed to a number type because when I print it out with a directive it displays without quotes.
So my question is:

*

*How do I allow negative numbers

*How do I stop all of the exceptions from being

A: How to Dynamically Change the Type of an Input Element
The type of an input element can be changed dynamically simply with AngularJS interpolation.
<input type="{{dynamicType}}" ng-model="inputValue">

Or from a directive
angular.module("myApp").directive("typeVar", function() {
     return {
         link: linkFn
     };
     function linkFn(scope,elem,attrs) {
         //elem.attr("type", "number");
         attrs.$observe("typeVar", function(value) {
             elem.attr("type", value);
             //attrs.$set("type", value);
         });
     }
});

HTML
<input type-var="{{dynamicType}}" ng-model="inputValue">

The DEMO on JSFiddle
The type property is an intrinsic part of the input element. For more information, see MDN HTML Element Reference -- input.


Q: Mercurial convert extension not able to pull from remote Git repository I'm trying to do a 'hg convert', to pull from a Git repo into an Hg one.
Now, I don't have Git installed on my Windows 7 machine; is that necessary? I'm using the TortoiseHG commandline, and I have activated the convert extension ('hg help convert' works fine).
Here's an example of the command I'm trying to use:
hg convert -s git -d hg https://github.com/mysticbob/glm.git gittest

That's a public repo on Github, so I should be able to convert from it. And the address is what Github says one should use for getting. What I get is the following message:
initializing destination gittest repository
https://github.com/mysticbob/glm.git does not look like a Git repository

Any ideas?

A: If I believe issue 1246, you need to have git installed for the hg convert extension to work.
Even with Git installed, you might experience some other issues with the import, in which case you could consider other alternatives such as:

*

*converting the git repo to a svn one, and then importing that svn repo into a mercurial one

*or trying the hg-git mercurial plugin, which specifically mentions:

This plugin is implemented entirely in Python - there are no Git binary dependencies, you do not need to have Git installed on your system.

(But I don't know if hg-git works with recent 1.7+ Mercurial versions)


Q: Multiplication cancellation property by Peano axioms I am trying to prove cancellation property of multiplication of natural numbers, $xy=xz$ implies $y=z$, with Peano axioms and arithmetic but not using or defining order on natural numbers. It can be done for addition. But for proving multiplication cancellation property one uses order. Why is that so?

A: You do not need to use order. Do it by induction on $y$. Define $M:=\{y \ |yx=zx\Rightarrow y=z \}$.
For $y=1$ we have $1\cdot x=z\cdot x$. If $z=1$ we are done. Suppose $z\neq 1$. Then $z=s(p)$ for some $p$ and hence
$$1\cdot x=s(p)\cdot x= px+x=(p\cdot x)+1\cdot x$$
and
$$1+(1\cdot x)=1+(p\cdot x)+(1\cdot x).$$
Using cancellation for addition we get
$$1=1+(p\cdot x)=(p\cdot x)+1=s(p\cdot x),$$
that is a contradiction. Therefore $z=1$.
Now, let $y=k\in M$, i.e. for any positive integers $z,x$ if $kx=zx$ then $k=z$. Let $t,s \in \mathbb{N}_+$ be such that $s(k)\cdot s=t\cdot s$. We show that $s(k)=t$. Obviously $t\neq 1$. Hence $t=s(m)$ for some $m$ and therefore we get
$$s(k)s=s(m)s$$
that is equaivalent to
$$ks+s=ms+s$$
from which it follows that $ks=ms$ (cancellation for addition). From the induction hypothesis we have $k=m$, and therefore $s(k)=s(m)=t$.
That means that $n=k+1\in M$ and the proof is completed.


Q: Order of operations in for loops in C In the following floor loop, how would sum += n -- be evaluated? I'm very, very confused...
int sum;
for(sum=0;n>0;sum+=n--);

A: For sum += n-- the following operations are performed

*

*add n to sum

*decrement n
With sum += --n

*

*n is decremented

*the new value of n is added to sum
n-- is called postdecrement, and --n is called predecrement

A: That has to do with post- and predecrement operations. Predecrement operations first decrease the value and then are used in other operations while postdecrement ones first get used in operations (addition in the case) and decrement the value only after this.
All in all, the order will be as follows:

*

*sum is incremented by n

*n is decremented

A: A very simple example I would like to demostrate.
Let us consider two variables a=1 and b=4
the statement a=b will assign the value of b to a,
In the statement a=b++ , first the value of b is assigned to a and then the value of b is incremented.
If the value of awas 1 and value of b was 4, then after using a=b++, the value of a will become 4 and the value of b will become 5.
The statement a=b++can be visualised as
a=b;
then
b=b+1;
Similarly, in your case, you have sum+=n-- which can be broken down as
sum=sum+(n--)
or
sum=sum+n
then
n=n-1
Here again, first the value of sum+n will be assigned to sum, then the value of n will be decremented by 1


Q: WPF FileDrop Event: just allow a specific file extension I have a WPF Control and I want to drop a specific file from my desktop to this control. This is not a heavy part but I would like to check the file extension to allow or disallow the dropping. What is the best way to solve this problem?

A: I think this should work:
<Grid>
    <ListBox AllowDrop="True" DragOver="lbx1_DragOver"
                                                      Drop="lbx1_Drop"></ListBox>
</Grid>

Let's assume you want to allow only C# files:
private void lbx1_DragOver(object sender, DragEventArgs e)
{
   bool dropEnabled = true;
   if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
   {
      string[] filenames =
                       e.Data.GetData(DataFormats.FileDrop, true) as string[];

      foreach (string filename in filenames)
      {
         if(System.IO.Path.GetExtension(filename).ToUpperInvariant() != ".CS")
         {
            dropEnabled = false;
    break;
         }
       }
   }
   else
   {
      dropEnabled = false;
   }

   if (!dropEnabled)
   {
      e.Effects = DragDropEffects.None;
  e.Handled = true;
   }
}

private void lbx1_Drop(object sender, DragEventArgs e)
{
    string[] droppedFilenames =
                        e.Data.GetData(DataFormats.FileDrop, true) as string[];
}


Q: Cant obtain md5 Fingerprint for api key I am trying to develop the map element of my app and I am having trouble obtaining a md5 fingerprint,  I am using Ubuntu and I have located the debug.keystore file, but when I enter the commands I get:
No command 'store' found, did you mean:
 Command '0store' from package 'zeroinstall-injector' (universe)
 Command 'stone' from package 'stone' (universe)
store: command not found
or;
Illegal option:  -key
Try keytool -help
I think the first error maybe incorrect file path but I think the second error is when I got it right.
Anyone Help with this
Thanks In Advance

A: The command is keytool, not store. Per the documentation, the command you need to run is:
keytool -list -alias androiddebugkey -keystore <path_to_debug_keystore>.keystore -storepass android -keypass android

In your specific case, for Ubuntu, this turns into:
keytool -list -alias androiddebugkey -keystore ~/.android/debug.keystore -storepass android -keypass android


Q: Angular 14 (Excel) File Download, Returning 502 (Bad Gateway) I have an app, that uses a standalone service for the back-end (Springboot) and a standalone front end app (Angular 14).
I'm making a request from the front end, to the back end. The back-end generates an excel file (XSSFWorkbook) and sends it back to the front using HttpServletResponse.
The front-end is expecting a blob, and uses an octet-stream to create a downloadable file.
My issue is, this functionality works perfectly on a local machine, but returns a 502 error, when both apps are deployed. Both Apps are deployed to separate cloud environments. No issues with Http requests to other endpoints, except for this file download endpoint.
I have looked at the backend app's logs, but it returns no errors & I've considered the idea that they're might be a timeout issue, but the error is returned within 3 seconds and the average file size is 9 bytes.
Error shown in chrome developer tools console:
main.4854ab3470858733.js:1 ERROR
{error: 'Backend returned code 502, body was:[object Blob]', status: 502}
error
:
"Backend returned code 502, body was:[object Blob]"
status
:
502
[[Prototype]]
:
Object
I need some ideas, on what could be the cause.


Q: Jackson deserialization into field from subnode? I have a class
public class Foo {
    String foo;
    String bar;
}

and JSON
{
  "foo": "foo",
  "bar": {
    "bar": "bar"
  }
}

Can I deserialize it using any json library without writing adapters/serializers to specific class.
Maybe some of gson's adapters has needed behavior?
But I didn't find adapter to field. I'd like to write annotation like @MyJsonExpandAnnotation("bar.bar") but I can't find adapter with access to Field.

A: Basically what you would use without your given annotation example is
public class Foo {
    String foo;
    Bar bar;
}

public class Bar{
    String bar;
}

There is an open suggestion for it tho.


Q: is it possible to write a directive to match "any other query params"? To ensure people don't append random query parameters (e.g. appending &r=234522.123 or similar) to avoid hitting our cache I want to have a way to reject any queries that are not handled explicitly. I can of course create one that contains a whitelist, but that would have to be separately maintained and I hate maintaining two things that needs to stay in synch. (Though, it would aid in failing faster.) Is this possible with Spray routing?

A: I ended up with this:
// This contains a white-list of allowed query parameters. This is useful to
// ensure people don't try to use &r=234234 to bust your caches.
def allowedParameters(params: String*): Directive0 = parameterSeq.flatMap {
  case xs =>
    val illegal = xs.collect {
      case (k, _) if !params.contains(k) => k
    }
    if (illegal.nonEmpty)
      reject(ValidationRejection("Illegal query parameters: " + illegal.mkString("", ", ", "\nAllowed ones are: ") + params.mkString(", ")))
    else
      pass
}

For usage, have a look at the unit tests:
val allowedRoute = {
  allowedParameters("foo", "bar") {
    complete("OK")
  }
}

"Allowed Parameter Directive" should "reject parameters not in its whitelist" in {
  Get("/?foo&bar&quux") ~> allowedRoute ~> check {
    handled should equal(false)
    rejection should be(ValidationRejection("Illegal query parameters: quux\nAllowed ones are: foo, bar"))
  }
}

it should "allow properly sorted parameters through" in {
  Get("/?bar&foo") ~> allowedRoute ~> check {
    handled should equal(true)
    responseAs[String] should equal("OK")
  }
}

A: Actually, you have a good solution, i can only suggest a small refactoring:
def only(params: String*): Directive0 = {
  def check: Map[String, String] => Boolean = _.keySet diff params.toSet isEmpty
  parameterMap.require(check, rejection)
}

You can write it as a one-liner, but it would be just longer

A: With a route like this:
val myRoute = {
  ...
  pathPrefix("test") {
    parameter("good") {
      good =>
        complete("GOOD")
    }
  } ~
 ...
}

Spray will require first parameter to be good and to have value, i.e. ?good=value. No other parameters that have values are allowed.


Q: Spawning new robot in running ROS Gazebo simulation The problem statement is in simulating both 'car' and a quadcopter in ROS Gazebo SITL as mentioned in this question. Two possibilities have been considered for the same which is as depicted in the image.

(Option 1 uses 6 terminals with independent launch files and MAVproxy initiation terminals)
While trying to search for Option 1, the documentation appeared to be sparse (The idea is to launch the simulation with ErleRover and then spawn ErleCopter on-the-go; I haven't found any official documentation mentioning either the possibility or the impossibility of this option). Can somebody be requested to let me know how option 1 can be achieved or why it is impossible by mentioning corresponding official documentation?
Regarding option 2, additional options have been explored; The problem is apparently with two aspects: param vs rosparam and tf2 vs tf_prefix.
Some of the attempts of simulation of multiple turtlebots have used tf_prefix which is deprecated. But, I have been unable to find any example which uses tf2 while simulating multiple (different) robots. But, tf2 works on ROS Hydro (and thus Indigo). Another possible option is the usage of rosparam instead of param (only). But, documentation on that is sparse regarding the usage of same on multi-robot simulation and I have been able to find only one example (for a single robot Husky).
But, one thing is clearer: MAVproxy can support multiple robots through the usage of SYSID and component-ID parameters. (upto 255 robots with 0 being a broadcast ID) Thus, port numbers have to be modified (possibly 14000 and 15000 as each vehicle uses 4 consecutive ports) just like the UCTF simulation. (vehicle_base_port = VEHICLE_BASE_PORT + mav_sys_id*4)
To summarise the question, the main concern is to simulate an independent car moving around and an independent quadcopter flying around in the ROS Gazebo SITL (maybe using Python nodes; C++ is fine too). Can somebody be requested to let me know the answers to the following sub-questions?

*

*Is this kind of simulation possible? (Either by the usage of ROS Indigo, Gazebo 7, MAVproxy 1.5.2 on Ubuntu 14.04 or by modifying UCTF project to spawm a car like ErleRover if there is no other option)
(You are kindly requested to let me know the examples if possible and official links if this is impossible)

*If on-the-go launch is not possible with two launch files, is it possible to launch two different robots with a single launch file?

*This is an optional question: How to modify the listener (subscriber) of the node? (Is it to be done in the Python node?)
This simulation is taking relatively long time with system software crashing for about 3 times (NVIDIA instead of Noveau, broken packages etc) and any help will be whole-heartedly, gratefully and greatly appreciated. Thanks for your time and consideration.
Prasad N R


Q: Reset Bootstrap modal when clicking outside modal window I'm having some problems with reseting my bootstrap modal whenever the user clicks outside the modal window to dismiss instead of pressing the dismiss button. My datetimepicker stops working whenever the modal window doesnt reset properly.
This is what my modal should do whenever it opens:

But this is what happens if I open the window just after dismissing my window by hitting the gray area outside the modal window:

Whenever I dismiss using the Avbryt (dismiss) button it works just fine.
I get no errors and this is the code I use for my modal
$scope.show = function() {
    ModalService.showModal({
            templateUrl: 'newProject.html',
            controller: "NewProjectModalController"
        }).then(function(modal) {
            modal.element.modal();
            modal.close.then(function(result) {
                $('#newProjectModal').modal('hide');
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
            }
        });
    });
}
$scope.dismiss = function () {
    close(false, 500)
}

The modal service can be found on JSfiddle.
I discovered that its not really the backdrop that is triggering the dismiss but the edges of the modal window. If I hit the outside of the modal within the small square, its dismisses, but not if I hit the backdrop outside.

A: Try triggering a click event on the Avbryt button when a user clicks on the modal backdrop. Something like this:
$('.modal-backdrop').click(function(){
  $('.avbryt').trigger('click');
});

That should bypass whatever the underlying problem is.
For reference: http://api.jquery.com/trigger/

A: According to the image in question, you are using angular-modal-service along with bootstrap.js  in your project. So I searched its github repo and found this issue: https://github.com/dwmkerr/angular-modal-service/issues/107
According to the comments there, you should change your code as below:
ModalService.showModal({
        templateUrl: 'newProject.html',
        controller: "NewProjectModalController"
    }).then(function(modal) {
        modal.element.modal();
        modal.close.then(function(result) {
            $('#newProjectModal').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
        }
        // added by me
        modal.element.on('hidden.bs.modal', function () {// bootstrap event
            modal.scope.close(false,500);
        });
    });
});


Q: Exlude a directory in .htaccess with RedirectMatch for Wordpress I change my Wordpress permalink structure from %year%/%months%/ to %postname%
So i create this mod alias rules in .htaccess but i have a problem:
RedirectMatch 301 /\d{4}/\d{2}/([^/]+)(/?)(.*)$ http://domainname.com/$1

The rules also redirect the images under the wp-content directory, so domainname.com/wp-content/uploads/2013/11/name.jpg become domainname.com/name.jpg
I can't use RewriteCond because this RedirecMatch is mod_alias, i try to use !^/(wp-content.*)$ but doesn't work.
How can i solve? It's better to use RedirectMach or RewriteRule (i haven't changed the server)?
Can you post a better regex?
Thank you!

A: Try ^ and $:
RedirectMatch 301 ^/\d{4}/\d{2}/([^/]+)(/?)(.*)$ http://domainname.com/$1

A: You should probably stick with using mod_rewrite instead of mod_alias because it'll interfere with wordpress' mod_rewrite rules. Both mod_rewrite and mod_alias affect the same request URI at different points in the URL-file processing pipeline, so you could end up getting redirected and rewritten at the same time.
RewriteCond %{REQUEST_URI} !\.(jpeg|gif|png)$ [NC]
RewriteRule ^\d{4}/\d{2}/([^/]+?)(/?)(.*)$ http://domainname.com/$1 [L,R=301]


Q: Is every funky topology a topology? Whenever $X$ is a set, define that a funky topology on $X$ is a collection of subsets of $X$ deemed "open" such that:

*

*$X$ is open.

*If $A,B \subseteq X$ is open, then $A \cap B$ is open.

*If $\mathcal{C}$ is an open cover of $X$, then for all $A \subseteq X$, if $$\forall U \in \mathcal{C}(A \cap U \mbox{ is open}),$$ then $A$ is open.

It's clear that every topology is a funky topology.

Question. Does the converse hold?

A: No.  For instance, $\{X\}$ is a funky topology on any set $X$, but is not a topology unless $X$ is empty.
It also does not suffice to assume the empty set is open.  For instance, if $X=\{a,b,c\}$, then $\{\emptyset,\{a\},\{b\},X\}$ is a funky topology but not a topology.


Q: Find a configuration for which this bound is achieved. This is the problem from David Pollard Book" Convergence of Stochastic Process".
Can anyone give me some hint here??
Let $S_0$ be a set of N points in $S$. Suppose there is an integer $V\leq N$ such that $D$ shatters no set of V points in $S_0$. Then $D$ picks out no more that ${n \choose 0}+ {n \choose 1}+ .....+ {n \choose {V-1}}$ subset from $S_0$
The above theorem informs us that the class of quadrants in $R^2$ picks out at most $1+\frac{1}{2}N+ \frac{1}{2}N^2$ subsets from any collection of N points. Find a configuration for which this bound is achieved.
Hstrong textow to find Configuration for which this bound is achived??
Definition from the same book :
Let $D$ be a class of subsets of some space $S$. It is said to have
polynomial discrimination (of degree v) if there exists a polynomial $\rho(.)$
(of degree $v$) such that, from every set of $N$ points in $S$, the class picks out at
most $\rho(N)$ distinct subsets. Formally, if $S_0$ consists of $N$ points, then there
are at most $\rho(N)$ distinct sets of the form $S_0\bigcap d $ with$ d$ in $D$. Call $\rho(.)$ the
discriminating polynomial for $D$.
Thank you


Q: Using Diagrammr package to make a flow DiagrammeR I am trying to make a flow to show my experimental design. I have something that works, but I would like to add another layer at the bottom-which adds a question box to each group, which should be big enough to read. An example of what I have is image 1 hoping for is in image 2. Such that group 1 has a question and answer (with arrows) and group 2 and 3 has a question and 3 answers (with arrows). Of course, the arrows should be black and in the right place-its just hard to do in word!
Does anyone know how I can do this?
Image 1
Image 2
Code:
# install.packages("DiagrammeR")
#library(DiagrammeR)

schematic <- grViz("digraph lexicon {
      # node definitions with substituted label text
node [fontname = Helvetica, shape = rectangle, style=filled,color=lightgrey]
      tab1 [label = '@@1']
      tab2 [label = '@@2']
      tab3 [label = '@@3']
      tab4 [label = '@@4']
      tab5 [label = '@@5']
      node [shape = rectangle, fillcolor=PeachPuff]
      tab6 [label = '@@6']
      node [shape = rectangle, fillcolor=CadetBlue]
      tab7 [label = '@@7']
      node [shape = rectangle, fillcolor=Lavender]
      tab8 [label = '@@8']

node [fontname = Helvetica, shape = rectangle, style=bold]
      m1 [label = 'Did not agree to participate n=18']
      m2 [label = 'Under 18 years n=11']
      m3 [label = 'No smoke in past 3 months n=8']
      m4 [label = 'Did not complete survey n=155']
      # creating horizontal lines
      node [shape=none, width=0, height=0, label='']
      {rank=same; tab1 -> m1}
      {rank=same; tab2 -> m2}
      {rank=same; tab3 -> m3}
      {rank=same; tab4 -> m4}
      # edge definitions with the node IDs
     tab1 -> tab2 -> tab3 -> tab4 -> tab5->{tab6 tab7 tab8};
      }
      [1]: 'Raw Data n=434'
      [2]: 'Agreed to participate n=406'
      [3]: 'Over 18 years n=491'
      [4]: 'smoke in past 3 months=403'
      [5]: 'Final sample n=238'
      [6]: 'Group1 n=82'
      [7]: 'Group2 n=98'
      [8]: 'Group3 n=88'
      ")

jpeg(file = "schematic.jpg")
schematic

A: You can just add some more nodes
schematic <- grViz("digraph lexicon {
          # node definitions with substituted label text
    node [fontname = Helvetica, shape = rectangle, style=filled,color=lightgrey]
          tab1 [label = '@@1']
          tab2 [label = '@@2']
          tab3 [label = '@@3']
          tab4 [label = '@@4']
          tab5 [label = '@@5']
          node [shape = rectangle, fillcolor=PeachPuff]
          tab6 [label = '@@6']
          node [shape = rectangle, fillcolor=CadetBlue]
          tab7 [label = '@@7']
          node [shape = rectangle, fillcolor=Lavender]
          tab8 [label = '@@8']

    node [fontname = Helvetica, shape = rectangle, style=bold]
          m1 [label = 'Did not agree to participate n=18']
          m2 [label = 'Under 18 years n=11']
          m3 [label = 'No smoke in past 3 months n=8']
          m4 [label = 'Did not complete survey n=155']

# ------> NEW NODES
    node [fontname = Helvetica, shape = rectangle, style=bold,  width = 2.5, height = 1, ALIGN = LEFT]
          q1 [label = 'Question 1 \\l\n\n']
          q2 [label = 'Question 2 \\l\n\n']
          q3 [label = 'Question 3 \\l\n\n']
          a11 [label = 'Answer 1 \\l\n\n']
          a21 [label = 'Answer 1 \\l\n\n']
          a22 [label = 'Answer 2 \\l\n\n']
          a23 [label = 'Answer 3 \\l\n\n']
          a31 [label = 'Answer 1 \\l\n\n']
          a32 [label = 'Answer 2 \\l\n\n']
          a33 [label = 'Answer 3 \\l\n\n']

    # creating horizontal lines
          node [shape=none, width=0, height=0, label='']
          {rank=same; tab1 -> m1}
          {rank=same; tab2 -> m2}
          {rank=same; tab3 -> m3}
          {rank=same; tab4 -> m4}
    # edge definitions with the node IDs
         tab1 -> tab2 -> tab3 -> tab4 -> tab5->{tab6 tab7 tab8};
#--------> ATTACH NEW NODES
         tab6 -> q1 -> a11
         tab7 -> q2 -> a21 -> a22 -> a23
         tab8 -> q3 -> a31 -> a32 -> a33
          }
          [1]: 'Raw Data n=434'
          [2]: 'Agreed to participate n=406'
          [3]: 'Over 18 years n=491'
          [4]: 'smoke in past 3 months=403'
          [5]: 'Final sample n=238'
          [6]: 'Group1 n=82'
          [7]: 'Group2 n=98'
          [8]: 'Group3 n=88'
          ")

    jpeg(file = "schematic.jpg")
    schematic


Q: How to turning back the situation when button clicked again in Qt? Basically I created QListWidget and QPushButton and I want to list current item in the widget when I clicked the button.Until here it is fine. What I want is after clicking that button again, I want to see previous situation(old item!) of that item. How can I do that?
    Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    for(int i = 0; i < 9; i++ ){
        ui->listWidget->addItem(QString::number(i) + " old item!");
    }
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_pushButton_clicked()
{
    QListWidgetItem *itm = ui->listWidget->currentItem();
    itm->setText("new item!");
}


Q: How to fetch the link that is outside the href tag? private static final Pattern ptninhref =Pattern.compile(
            "(?:.*\\<[aA][^\\>]*(?i)href(?-i)=\\\"[^\\\"]*)([^\\\"]*)");

    public static List<String> captureValuesinhref(String largeText){
        Matcher mtchinhref = ptninhref.matcher(largeText);
        List<String> inHREF = new ArrayList<>();
        while(mtchinhref.find()){
           inHREF.add(mtchinhref.group());

How to fetch only  "link is given "?
 When i am using (?:.*\<[aA][^\>]*(?i)href(?-i)=\"[^\"]*)([^\"]*)(?:[^\"]*\".*\</[aA]\>.*) this regular expression code, it gives me output like: link is given here.
But required output only: "link is given here"
I have required the link which is outside the href tag.
There are two link :
1 is inside the href tag.
2 is outside the href tag that is shown in the browser.
I have required the 2nd link only.
How to fetch that using java in netbeans?

A: public class RegexExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String href= "Visit W3Schools.com!";
        String regexOr = "(?<=[>])(\\\\?.)*?(?=[<])";
        Pattern pattern = Pattern.compile(regexOr);
        Matcher matcher = pattern.matcher(href);
        if (matcher.find()) {
            String enrichedValue = matcher.group();
            System.out.print(enrichedValue);
        }
    }
}

This will print:

Visit W3Schools.com!

Keep in mind \ becomes \\ in java, it needs to be escaped
Full example:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {
    private static final Pattern ptninhref;
    static{
        ptninhref = Pattern.compile("(?<=[>])(\\\\?.)*?(?=[<])");
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String href= "https://www.paypa1.com/signin/";
        List<String> results = captureValuesinhref(href);
        for(String result:results){
            System.out.print(result);
        }
    }

    public static List<String> captureValuesinhref(String largeText){
        Matcher mtchinhref = ptninhref.matcher(largeText);
        List<String> inHREF = new ArrayList<String>();
        while(mtchinhref.find()){
           inHREF.add(mtchinhref.group());
        }
        return inHREF;
    }
}

prints:

https://www.paypa1.com/signin/


Q: SQL - group by with two colums agregation problem My today's problem is that I have a table that has rows like that:
ID NAME NUMBER IDN
1  dsad 500600 12
1  dsad 600700 13
2  kkkk 111222 56
2  kkkk 333232 57

in one ID example 1 i have 2 identical names 2 different numbers and different IDN.
What i want is to extract single row For each Id where the idn value is the smaller one.
So I want to have sommething like that
1  dsad  500600 12
2  kkkk  111222 56

Is it posible to write a single sql to have that result? I tried to group that by ID and NAME and have the min(IDN) but I'm stuck with the number field :) any ideas?

A: You were almost there, just add the MIN(Number) field.
SELECT  ID
        , NAME
        , MIN(NUMBER)
        , MIN(IDN)
FROM    ATable
GROUP BY
        ID
        , NAME

In response to comment
Following would get you the records with the MIN(IDN), regardless what the number for that specific record is.
SELECT  t.*
FROM    ATable t
        INNER JOIN (
          SELECT  ID, IDN = MIN(IDN)
          FROM    ATable
          GROUP BY ID
        ) tmin ON tmin.ID = t.ID
                  AND tmin.IDN = t.IDN

A: DECLARE @TABLE table (ID int, [NAME] varchar(100),NUMBER int ,IDN int)
insert into @TABLE SELECT 1,'dsad',500600,12
insert into @TABLE SELECT 1,'dsad',600700, 13
insert into @TABLE SELECT 2,'kkkk',111222, 56
insert into @TABLE SELECT 2,'kkkk',333232, 57

select t.ID, t.[Name], t.Number, t.IDN
from (
   select [NAME],min(IDN) as minIDN
   from @TABLE group by [NAME]
) as x inner join @TABLE as t on t.[Name]=x.[Name] and t.IDN = x.minIDN;

A: Version that only uses a left join and no subqueries, with SQlite3 and a shell script since I don't have anything other at hand ATM:
#!/bin/sh

rm -f test.sqlite
sqlite3 test.sqlite << AAA
CREATE TABLE test (id int, name text, number int, idn int);
INSERT INTO test VALUES(1,'dsad',500600,12);
INSERT INTO test VALUES(1,'dsad',600700,13);
INSERT INTO test VALUES(2,'kkkk',111222,56);
INSERT INTO test VALUES(2,'kkkk',333232,57);
INSERT INTO test VALUES(1,'dsad',600700,9);
INSERT INTO test VALUES(2,'kkkk',333232,59);
INSERT INTO test VALUES(2,'cccc',333232,59);
SELECT a.* FROM test a
    LEFT JOIN test b ON
            a.id=b.id AND
            a.name=b.name
            AND a.idn > b.idn
            WHERE b.id IS NULL;
AAA
# Result:
# 1|dsad|600700|9
# 2|cccc|333232|59
# 2|kkkk|111222|56

Can anyone comment on where the performance is better? I think that matters, too!


Q: onSuccessListner after image crop permission I am getting image cropping like this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

//do some activity based on permission granted or declined.
            } else {
                CropImage.activity(mainImageURI)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setAspectRatio(1,1)
                        .setAutoZoomEnabled(false)
                        .start(this);

                ;

            }

        }

My question is I want to do some activity right after the permission is granted or declined. In current scenario, I can first grant the permission and then again click again the imageview I am using, and then the cropping. But I want to have one activity right after the permission is granted and one if permission is denied.

A: You should override onRequestPermissionsResult in your activity in order to get notified whenever permission is granted or not:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == PERMISSIONS_CODE) {
        for (int i = 0; i < permissions.length; i++) {
            String permission = permissions[i];
            int grantResult = grantResults[i];

            if (permission.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                if (grantResult == PackageManager.PERMISSION_GRANTED) {
                    // TODO Open The Crop Activity
                } else {
                    // TODO Tell the user your app can't function properly
                }
            }
        }
    }
}


Q: WPF download multiple files with progress in popup Hy,
I am trying to make a popup indicating the progress of the download of several files. I'm not used to working with await/async and think I'm probably making a big mistake in this case.
The goal is to follow the progress of the file download one by one, I don't want to run all the downloads at the same time. And also have a general look at the progress of all the files to download.
Here is my actual code:
In a first Window I genereate the file list and send it in a PopUp:

Popupdownload inputDialog = new Popupdownload(FileList);
   if (inputDialog.ShowDialog() == true)
   {
     MessageBox.Show(FileList.Count().ToString() + " files are downloaded");
   }

My popup class :
public partial class Popupdownload: Window
    {
        public Popupdownload(List<string> listFiles)
        {
            InitializeComponent();
            DowloadList(listFiles);
        }
        public async void DowloadList(List<string> listFiles)
        {
            int counter = 0;
            foreach (string e in listFiles)
            {
                FileInfo TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e));
                Uri myUri = new Uri("http://********/" + e), UriKind.Absolute);
                await DownloadFile(myUri, TempFile.FullName);
                counter++;
                progressBarTotal.Value = 100*(double)counter / (double)listFiles.Count();
            }
        }

        Stopwatch sw = new Stopwatch();
        public async Task DownloadFile(Uri URL, string location)
        {
            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
                sw.Start();
                try
                {
                    webClient.DownloadFileAsync(URL, location);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("The file " + location + " hasn't been dowload. Contact admin");
                }
            }
        }
        private void ProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            labelSpeed.Content = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
            progressBar.Value = e.ProgressPercentage;
            labelPerc.Content = e.ProgressPercentage.ToString() + "%";
            labelDownloaded.Content = string.Format("{0} MB's / {1} MB's",
                (e.BytesReceived / 1024d / 1024d).ToString("0.00"),
                (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
        }
        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
            sw.Reset();
            if (e.Cancelled == true)
            {
                MessageBox.Show("Download has been canceled.");
            }
            else
            {
              //  MessageBox.Show("Download completed!");
            }
        }
    }

My current code is a digest of several sources, and I am not sure that some parts work well.
My previous synchronius version of it is working, but hasn't the current file download status preview that I'would like.
It seem to me that all dowloads are launch in same time and it doesn't wait until first has stopped. So it is probably my first issue.
Thanks for your help

A: Here is how I resolve my question:
First my program launch a PopUp with the file list in argument.
Popupdownload inputDialog = new Popupdownload(FileList);

The Popupdownload windows :
    public partial class Popupdownload: Window
{
// Global Clock for speed processing
    Stopwatch sw = new Stopwatch();

// PopUp Initialisation
    public Popupdownload(List<string> listFiles)
    {
        InitializeComponent();
        DowloadListASync(listFiles, type);
    }
// List processing with Progress Status Update
    public async void DowloadListASync(List<string> listFiles)
    {
        int counter = 0;
        long totalSize = 0;
        int totalcounter = listFiles.Count();
        progressLabelTotal.Content = 1 + "/" + totalcounter.ToString();
        var sw = Stopwatch.StartNew();
        foreach (string e in listFiles)
        {
            progressBarTotal.Value = 100 * (double)counter / (double)totalcounter;
            FileInfo TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e));
            Uri myUri = new Uri("http://www.XXXX/" + e, UriKind.Absolute);
            if (!TempFile.Directory.Exists)
            {
                TempFile.Directory.Create();
            }
            if (TempFile.Exists) TempFile.Delete();
            await DownloadAFile(myUri, TempFile.FullName);
            counter++;
            TempFile = new FileInfo(System.IO.Path.Combine(App.folderpath, e));
            if (TempFile.Exists)
            {
                totalSize += TempFile.Length;
            }
            else
            {
                totalcounter--;
                counter--;
            }
            var totalSpeed = (totalSize / 1024d / (sw.Elapsed.TotalSeconds));
            if (totalSpeed < 800)
            {
                labelTotalSpeed.Content = string.Format("{0} kb/s", totalSpeed.ToString("0.00"));
            }
            else
            {
                totalSpeed = ((totalSize / 1024d) / 1024d / (sw.Elapsed.TotalSeconds));
                labelTotalSpeed.Content = string.Format("{0} Mb/s", totalSpeed.ToString("0.00"));
            }
            progressBarTotal.Value = 100 * (double)counter / (double)totalcounter;
            labelTotalPerc.Content = ((double)counter / (double)totalcounter).ToString("P");

            progressLabelTotal.Content = (counter != totalcounter) ? (1 + counter).ToString() + "/" + totalcounter.ToString() : "Téléchargment effectué";
        }
        Close;
    }
//async Download file with HttpClient, and keep progress
    public async Task DownloadAFile(Uri URL, string location)
    {
        using (var client = new HttpClientDownloadWithProgress(URL.AbsoluteUri, location))
        {

            var watch = Stopwatch.StartNew();
            FileInfo TempFile = new FileInfo(location);
            client.ProgressChanged += (totalFileSize, totalBytesDownloaded, progressPercentage) => {
                Nomfichier.Content = TempFile.Name;
                labelPerc.Content = progressPercentage.ToString() + "%";
                progressBar.Value = (double)progressPercentage;
                // labelSpeed.Content = string.Format("{0} kb/s", (totalBytesDownloaded / 1024d / (watch.Elapsed.TotalSeconds)).ToString("0.00"));

                var speed = (totalBytesDownloaded / 1024d / (watch.Elapsed.TotalSeconds));
                if (speed < 800)
                {
                    labelSpeed.Content = string.Format("{0} kb/s", speed.ToString("0.00"));
                }
                else
                {
                    speed = ((totalBytesDownloaded / 1024d) / 1024d / (watch.Elapsed.TotalSeconds));
                    labelSpeed.Content = string.Format("{0} Mb/s", speed.ToString("0.00"));
                }
                //   Console.WriteLine($"{progressPercentage}% ({totalBytesDownloaded}/{totalFileSize})");
            };
            await client.StartDownload();
            Nomfichier.Content = "";
        }
    }

and the HttpClientDownload class used like in comment:
    public class HttpClientDownloadWithProgress : IDisposable
    {
        private readonly string _downloadUrl;
        private readonly string _destinationFilePath;

        private HttpClient _httpClient;

        public delegate void ProgressChangedHandler(long? totalFileSize, long totalBytesDownloaded, double? progressPercentage);

        public event ProgressChangedHandler ProgressChanged;

        public HttpClientDownloadWithProgress(string downloadUrl, string destinationFilePath)
        {
            _downloadUrl = downloadUrl;
            _destinationFilePath = destinationFilePath;
        }

        public async Task StartDownload()
        {
            _httpClient = new HttpClient { Timeout = TimeSpan.FromDays(1) };

            using (var response = await _httpClient.GetAsync(_downloadUrl, HttpCompletionOption.ResponseHeadersRead))
                await DownloadFileFromHttpResponseMessage(response);
        }

        private async Task DownloadFileFromHttpResponseMessage(HttpResponseMessage response)
        {
            response.EnsureSuccessStatusCode();

            var totalBytes = response.Content.Headers.ContentLength;

            using (var contentStream = await response.Content.ReadAsStreamAsync())
                await ProcessContentStream(totalBytes, contentStream);
        }

        private async Task ProcessContentStream(long? totalDownloadSize, Stream contentStream)
        {
            var totalBytesRead = 0L;
            var readCount = 0L;
            var buffer = new byte[8192];
            var isMoreToRead = true;

            using (var fileStream = new FileStream(_destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
            {
                do
                {
                    var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        isMoreToRead = false;
                        TriggerProgressChanged(totalDownloadSize, totalBytesRead);
                        continue;
                    }

                    await fileStream.WriteAsync(buffer, 0, bytesRead);

                    totalBytesRead += bytesRead;
                    readCount += 1;

                    if (readCount % 100 == 0)
                        TriggerProgressChanged(totalDownloadSize, totalBytesRead);
                }
                while (isMoreToRead);
            }
        }

        private void TriggerProgressChanged(long? totalDownloadSize, long totalBytesRead)
        {
            if (ProgressChanged == null)
                return;

            double? progressPercentage = null;
            if (totalDownloadSize.HasValue)
                progressPercentage = Math.Round((double)totalBytesRead / totalDownloadSize.Value * 100, 2);

            ProgressChanged(totalDownloadSize, totalBytesRead, progressPercentage);
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }

My last wish would be to be able to run downloads in bundles of 3-4 and handle 404 errors when the target file is missing. Work In Progress. If anyone has a clue.
Thanks @steeeve for your comment.