text:
Q: What is the easiest way to resolve c++ linking error I have multiple c++ class files and header files when i attempt to compile them i get the following error.I even tried using cmake to make my life easier but i still get it:
make: Warning: File `Makefile' has modification time 11 s in the future
make[1]: Warning: File `CMakeFiles/Makefile2' has modification time 11 s in the future
make[2]: Warning: File `src/CMakeFiles/simulation.dir/flags.make' has modification time 11 s in the future
Scanning dependencies of target simulation
make[2]: warning:  Clock skew detected.  Your build may be incomplete.
make[2]: Warning: File `src/CMakeFiles/simulation.dir/flags.make' has modification time 11 s in the future
[  4%] Building CXX object src/CMakeFiles/simulation.dir/OS.cxx.o
[  9%] Building CXX object src/CMakeFiles/simulation.dir/Ram.cxx.o
[ 14%] Building CXX object src/CMakeFiles/simulation.dir/RamQueues.cxx.o
[ 19%] Building CXX object src/CMakeFiles/simulation.dir/HardDisk.cxx.o
[ 23%] Building CXX object src/CMakeFiles/simulation.dir/CpuRegisters.cxx.o
[ 28%] Building CXX object src/CMakeFiles/simulation.dir/BankersAlgorithm.cxx.o
[ 33%] Building CXX object src/CMakeFiles/simulation.dir/Clock.cxx.o
[ 38%] Building CXX object src/CMakeFiles/simulation.dir/random.cxx.o
[ 42%] Building CXX object src/CMakeFiles/simulation.dir/PCB.cxx.o
[ 47%] Building CXX object src/CMakeFiles/simulation.dir/File.cxx.o
[ 52%] Building CXX object src/CMakeFiles/simulation.dir/Jobs.cxx.o
[ 57%] Building CXX object src/CMakeFiles/simulation.dir/Cpu.cxx.o
[ 61%] Building CXX object src/CMakeFiles/simulation.dir/JobCreationFactory.cxx.o
[ 66%] Building CXX object src/CMakeFiles/simulation.dir/StateQueue.cxx.o
[ 71%] Building CXX object src/CMakeFiles/simulation.dir/Keyboard.cxx.o
[ 76%] Building CXX object src/CMakeFiles/simulation.dir/Mouse.cxx.o
[ 80%] Building CXX object src/CMakeFiles/simulation.dir/Monitor.cxx.o
[ 85%] Building CXX object src/CMakeFiles/simulation.dir/ReadyQueue.cxx.o
[ 90%] Building CXX object src/CMakeFiles/simulation.dir/TerminatingQueue.cxx.o
[ 95%] Building CXX object src/CMakeFiles/simulation.dir/WaitingQueue.cxx.o
[100%] Building CXX object src/CMakeFiles/simulation.dir/osTester.cxx.o
Linking CXX executable simulation
CMakeFiles/simulation.dir/osTester.cxx.o: In function `main':
osTester.cxx:(.text+0xa3): undefined reference to `JobCreationFactory::createFiles(HardDisk)'
osTester.cxx:(.text+0xb9): undefined reference to `JobCreationFactory::createJobs(HardDisk)'
osTester.cxx:(.text+0xee): undefined reference to `HardDisk::setNumberOfJobs(int)'
osTester.cxx:(.text+0x2fe): undefined reference to `OS::setSchedulingAlgorithm(int)'
osTester.cxx:(.text+0x32c): undefined reference to `OS::osTakeOver(HardDisk, Ram, Cpu, Mouse, Monitor, Keyboard)'
collect2: ld returned 1 exit status
make[2]: *** [src/simulation] Error 1
make[1]: *** [src/CMakeFiles/simulation.dir/all] Error 2
make: *** [all] Error 2

how can i fix this error?
CODE follows :
#include <iostream>
#include <ostream>
#include <vector>
#include<string>
//#include <boost/shared_ptr.hpp>
#include "OS.hxx"
#include "Ram.hxx"
#include "Cpu.hxx"
#include "HardDisk.hxx"
#include "JobCreationFactory.hxx"
#include "Mouse.hxx"
#include "Monitor.hxx"
#include "Keyboard.hxx"

using namespace std;
typedef vector<int>LISTOFINT;
typedef LISTOFINT::iterator INT_ITER;

//namespace bo=boost;
//using bo::shared_ptr;
/* This is the main driver of the simulation,it makes all simulated devices available
 and ready for use before operating system takes over(osTakeOver())
 */

int main(){

    int numberOfJobs = 0;
    bool simulate = false;
    string start;
    LISTOFINT schedulingAlgorithms; // 1 for SJF(Shortest Job first) and 2:for RR(Round Robbin)
    LISTOFINT numberOfResourcesAvailable;
    int mouseAvailable;
    int monitorAvailable;
    int keyboardAvailable;
    HardDisk HD;
    OS myOS;
    Cpu myCpu;
    Ram myRam;
    Mouse myMouse;
    Monitor myMonitor;
    Keyboard myKeyboard;
    JobCreationFactory j;

    j.createFiles(HD);
    j.createJobs(HD);

    //set defaut number of jobs to be used in the simulation .. allow user to input number of jobs
    cout << "***For simulation we use multiple instances of Mouse Monitor and Keyboard, this is actually the number of process a DeviceQ can handle at a g***\n";
    cout << "Enter number of Jobs to be used in the simulation (eg 40000) follwed by the number of available resources say ( 6 8 9) followed by 's' then hit Carriage return key>>>\n";
    while (cin >> numberOfJobs >> mouseAvailable >> monitorAvailable >> keyboardAvailable && !simulate) {
        simulate = true;
        HD.setNumberOfJobs(numberOfJobs);
    }
    numberOfResourcesAvailable.push_back(mouseAvailable);
    numberOfResourcesAvailable.push_back(monitorAvailable);
    numberOfResourcesAvailable.push_back(keyboardAvailable);
    //setAvailable Resources
    //myOS.setAvailable(numberOfResourcesAvailable);

    INT_ITER aBegin = numberOfResourcesAvailable.begin();
    INT_ITER aEnd = numberOfResourcesAvailable.end();
    cout << "Initial number of resources Available (Mouse Monitor Keyboard):";
    for (; aBegin != aEnd; ++aBegin) {
        cout << *aBegin << " ";
    }
    cout << endl;
    /*simulate based on SJF then RR using the same number of resources then compare results
     *repeating the same algorithm a few more times would give a better comparison since this simulation
     *is entirely based on random number generation
    */
    schedulingAlgorithms.push_back(1);
    schedulingAlgorithms.push_back(2);
    INT_ITER sBegin = schedulingAlgorithms.begin();
    INT_ITER sEnd = schedulingAlgorithms.end();

    //at this point all devices are ready so an assumption can be made that
    //BIOS has successfully checked devices hence BIOSdone = true
    //once everything is ready BIOS Loads OS
    cout << "SJF and RR are represented by:";
    for (; sBegin != sEnd; ++sBegin) {// for both algorithms
        cout << *sBegin <<" ";
        myOS.setSchedulingAlgorithm(*sBegin);
        myOS.osTakeOver(HD,myRam,myCpu,myMouse,myMonitor,myKeyboard);
    }
    cout << "respectively\n";
    cout << endl;
    //for now the smulation progress will be seen on the console

    return 0;

}

A: The easiest way is to look if you have defined this symbol

undefined reference to
  `JobCreationFactory::createFiles(HardDisk)'

In the JobCreationFactory.cxx.o translation unit. Most likely you have declared it in JobCreationFactory.hxx but have not defined it in the corresponding implementation.

based on your other question that this one is a near exact duplicate of, I think I know what's going on. In JobCreationFactory.cxx you are not defining the class methods, you are redeclaring them
class JobCreationFactory{
    int numOfJobs;
    int numOfFiles;
    int time;
    int size;
    LISTOFINT header;

    JobCreationFactory()
    :numOfJobs(0),time(0),size(0)
    {
    }

Don't do that, do this instead
JobCreationFactory::JobCreationFactory() : numOfJobs(0),time(0),size(0)
{

}

and so on, for all the methods declared in JobCreationFactory.h. If this concept is confusing to you, you might want to get a good book about C++.

A: Linking errors are usually due to:

*

*Forgetting to define the symbol/function. Some people simply forget to do the implementation on the .cpp file.

*Defining the wrong symbol. It was supposed to be one thing but it was defined as another, very similar.

*Not linking with the right library. If that function was not implemented by you, it means the symbol is defined somewhere else.

A: Try to use IDE like Visual Studio or Code::Block, etc. That tools may help you with these compile and link problem.


text:
Q: Получить индекс перечисления Имеется перечисление вида:
enum MyControls: ulong { elementONE = 18410924985427079801, elementTWO = 88410924985427079804, elementF = 58410924985427079802};

Так же имеется массив, который инициилизируется при старте так:
MyClass[] mc1 = new MyClass[Enum.GetNames(typeof(MyControls)).Length];

экземпляры myclass добавляются и соответствуют тому же порядку, что описан в mycontrols.
Можно ли как то получить доступ к элементам такого массива, используя запись вида mc1[MyControls.elementF]. ( index elementF == 2)
Интересуют любые способы получения индекса в данном перечисление!
Можно было бы завести дополнительное перечисление, например
enum MyControlsNames = {elementONE, elementTWO, elementF }

и свободно писать mc1[MyControlsNames.elementF], но интересует 1й способ.
Благодарю за ответы!

A: Сделайте не массив, а Dictionary
var mc1 = new Dictionary<MyControls,MyClass>();
mc1.Add(MyControls.elementF, new MyClass(MyControls.elementF));

A: Можно перегрузить индексатор
class MyClass {

    public int this[ulong i]
    {
        get
        {
            // ваш код извлечения необходимой записи
        }
    }
}

Почитать про перегрузку индексаторов можно тут и тут.

A: Приведите к типу хранения, напишите (byte)MyEnumVariant - выводит индекс

redpajama_set_name: RedPajamaStackExchange


text:
Q: I cannot solve IndexError Code:
x = np.linspace(nodes[edges[i,0],0], nodes[edges[i,1],0], 10)
Error:
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
I am trying to make a cylinder shaped edge in a 3d network graph, but I can't solve this index error


text:
Q: Rails query rows with unique column I have Booking model and a 'bookings' table with the following columns: id, date, class_id.
Sample data:

*

*(1, 2021-09-23, 47)

*(2, 2021-09-23, 47)

*(3, 2021-09-22, 23)

*(4, 2021-09-20, 12)

*(5, 2021-09-20, 12)

*(6, 2021-09-20, 47)

A class can take place regularly (e.g. weekly) which can be booked by multiple people on the same day. For example, there are two bookings for the same class on 2021-09-23 and there is another booking for the same class but earlier on 2021-09-20.
How can I query all bookings with only one booking per class and date? For the above sample data I'd like to get:

*

*(1, 2021-09-23, 47)

*(3, 2021-09-22, 23)

*(4, 2021-09-20, 12)

*(6, 2021-09-20, 47)

bookings = Booking.??


text:
Q: How can I run my program code after fixed intervals? I have this Perl script for monitoring a folder in Linux.
To continuously check for any updates to the directory, I have a while loop that sleeps for 5 minutes in-between successive loops :
while(1) {

    ...
    sleep 300;
}

Nobody on my other question suggested using cron for scheduling instead of a for loop.
This while construct, without any break looks ugly to me as compared to submitting a cronjob using crontab :
0 */5 * * * ./myscript > /dev/null 2>&1

*

*Is cron the right choice? Are there any advantages of using the while loop construct?

*Are there any better ways of doing this except the loop and cron?

Also, I'm using a 2.6.9 kernel build.

A: The only reasons I have ever used the while solution is if either I needed my code to be run more than once a minute or if it needed to respond immediately to an external event, neither of which appear to be the case here.
My thinking is usually along the lines of: cron has been tested by millions and millions of people over decades so it's at least as reliable as the code I've just strung together.
Even in situations where I've used while, I've still had a cron job to restart my script in case of failure.
My advice would be to simply use cron. That's what it's designed for. And, as an aside, I rarely redirect the output to /dev/null, that makes it too hard to debug. Usually I simply redirect to a file in the /tmp file system so that I can see what's going on.
You can append as long as you have an automated clean-up procedure and you can even write to a more private location if you're worried about anyone seeing stuff in the output.
The bottom line, though, is that a rare failure can't be analysed if you're throwing away the output. If you consider your job to be bug-free then, by all means, throw the output away but I rarely consider my scripts bug-free, just in case.

A: *

*Why don't you make the build process that puts the build into the directory do the notification?  (See SO 3691739 for where that comes from!)

*Having cron run the program is perfectly acceptable - and simpler than a permanent loop with a sleep, though not by much.

*Against a cron solution, since the process is a simple one-shot, you can't tell what has changed since the last time it was run - there is no state.  (Or, more accurately, if you provide state - via a file, probably - you are making life much more complex than running a single script that keeps its state internally.)

*Also, stopping the notification service is less obvious.  If there's a single process hanging around, you kill it and the notifications stop.  If the notifications are run by cron, then you have to know that they're run out of a crontab, know whose crontab it is, and edit that entry in order to stop it.

*You should also consider persuading your company to upgrade to a version of Linux where the inotify mechanism is available.

A: If you go for the loop instead of cron and want your job run at regular intervals, sleep(300) tends to drift. (consider the execution time of the rest of your script)
I suggest using a construct like this:
use constant DELAY => 300;

my $next=time();
while (1){
    $next+=DELAY;

    ...;

    sleep ($next-time());
};

A: Yet another alternative is the 'anacron' utility.

A: if you don't want to use cron.
this http://upstart.ubuntu.com/ can be used to babysit processes.
or you can use watch whichever is easier.


text:
Q: Newsstand register for push notifications issue Im using the following code to register for push notifications for a Newsstand app.
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeNewsstandContentAvailability];

It calls didRegisterForRemoteNotificationsWithDeviceToken and i get a device token. When i log enabledRemoteNotificationTypes it returns 0 and didReceiveRemoteNotification is never called.
It works fine if i register with UIRemoteNotificationTypeAlert enabledRemoteNotificationTypes returns 4 and i get the notifications.
I have added the required background mode in the plist.
Any ideas?
Thanks.


text:
Q: Difference between "a daughter of a policeman" and "the daughter of a policeman" Example 1:

(1) She is a daughter of a policeman.
(2) She is the daughter of a policeman.

Does the (1) imply that her father policeman has more than one daughter?
Does the (2) imply that her father policeman has only one daughter?

How about this
Example 2:

(1) This is a wheel of a truck.
(2) This is the wheel of a truck.

These two sentence doesn't quite give me the feeling that the truck has only one wheel.

So, why is that?
Is it because the number of children is something hard to predict while the number of wheels on a truck are usually more than one?

A: She is a daughter of a policeman just doesn't sound natural. I can't explain why. We would say either She is a policeman's daughter or She is the daughter of a policeman. It has nothing to do with how many girls there are in the family.
I think that to say This is the wheel of a truck implies that it's a part of the truck, and This is a wheel from a truck names the object and then adds what kind of wheel it is as an afterthought.
Does that make sense?


text:
Q: Returning data from one function to insert into another function using JavaScript I am trying to create a Map on my website using the Google Maps JavaScript API in my ASP.NET Core Razor Pages project. The user will enter an address, which will be saved as TempData and then inserted into the parameters for the Google Maps Geocoder API, which will then turn the address into coordinates. I want to, then, use these coordinates as parameters to the Google Maps Javascript API call.
I have a function called getLatitude and a function called getLongitude, as shown:
     function getLatitude() {
        searchedAddress = @Html.Raw(Json.Serialize(ViewData["searchString"]));
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params: {
                address: searchedAddress,
                key: 'xxxxxx'
            }
        })
            .then(function (response) {
                var lat = response.data.results[0].geometry.location.lat;

                // This prints the correct value to the console.
                console.log(lat)

                // I want to return this value when I call the method.
                return lat;
            })
            .catch(function (error) {
                console.log(error);
            });
    }

     function getLongitude() {
        searchedAddress = @Html.Raw(Json.Serialize(ViewData["searchString"]));
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params: {
                address: searchedAddress,
                key: 'xxxxxx'
            }
        })
            .then(function (response) {
                var lng = response.data.results[0].geometry.location.lng;

                // This prints the correct value to the console.
                console.log(lng);

                // I want to return this value when I call the method.
                return lng;
            })
            .catch(function (error) {
                console.log(error);
            });
    }

Then I have a function called initMap, which creates the map using the Google Maps JavaScript API:
    function initMap() {
        var latitude = getLatitude()
        var longitude = getLongitude()

        // This is where I need to input the getLatitude and getLongitude data
        const location = { lat: latitude, lng: longitude }

        var options = {
            zoom: 15,
            center: location
        }
        const map = new google.maps.Map(document.getElementById('map'), options);
        const marker = new google.maps.Marker({
            position: location,
            map: map,
        });
    }

How can I use the data that I am able to print to the console in my getLatitude and getLongitude functions and put it into the initMap function location variable?

A: Axios provides asynchronous functions, and the latitude and longitude vars initialize as empty because initMap() has already finished running before the data is returned. console.log() prints the location data after axios.get() successfully returns the data but too late for initData().
I suggest you get the (lat, lon) with axios and run initMap() inside the then to ensure your data has arrived before moving on.
WARNING UNTESTED
Maybe something like this.
function getLatLong() {
  searchedAddress = @Html.Raw(Json.Serialize(ViewData["searchString"]));
  axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
    params: {
      address: searchedAddress,
      key: 'xxxxxx'
    }
  })
    .then(function (response) {
      var lng = response.data.results[0].geometry.location.lng;
      var lat = response.data.results[0].geometry.location.lat;

      // This prints the correct value to the console.
      console.log(lat, lng);

      // This is where I need to input the getLatitude and getLongitude data
      const location = { lat: latitude, lng: longitude }

      var options = {
        zoom: 15,
        center: location
      }
      const map = new google.maps.Map(document.getElementById('map'), options);
      const marker = new google.maps.Marker({
        position: location,
        map: map,
      })
        .catch(function (error) {
          console.log(error);
        });
    }

A: You can use async/await
  async function getLatitude() {
    searchedAddress = @Html.Raw(Json.Serialize(ViewData["searchString"]));
    const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
        params: {
            address: searchedAddress,
            key: 'xxxxxx'
        }
    });

    let lat = response.data.results[0].geometry.location.lat;
    return lat;
}

   async function getLongitude() {
    searchedAddress = @Html.Raw(Json.Serialize(ViewData["searchString"]));
    const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
        params: {
            address: searchedAddress,
            key: 'xxxxxx'
        }
    });
    let lng = response.data.results[0].geometry.location.lng;
    return lng;
}

Your caller function initMap()
    async function initMap() {
    let latitude = await getLatitude()
    let longitude = await getLongitude()

    const location = { lat: latitude, lng: longitude }

    var options = {
        zoom: 15,
        center: location
    }
    const map = new google.maps.Map(document.getElementById('map'), options);
    const marker = new google.maps.Marker({
        position: location,
        map: map,
    });
}


text:
Q: string to array return array in parameter I get a string something like this, "voornaam, achternaam"
I give that to a function.
When I used the string to get the data from the database.
mysql_query("SELECT."$string". FROM ...")
this all goes good.
Now. I want to give back the values that I selected from the DB.
I tried something like this.
<?php
function user_info($user_id, $fetch = "")
{
if (ctype_digit($user_id))
{
    if (empty($fetch))
    {
        $fetch = "*";
    }
    $query = mysql_query("SELECT ".$fetch." FROM accounts WHERE ID = '".$user_id."'");
    $data = mysql_fetch_assoc($query);
    $data['password'] = NULL;
}

if (empty($fetch))
{
    return $data;
}
else
{
    $fetch = explode(", ", $fetch);
    print_r($fetch);
    while($param = $fetch) {
        return $data[$param];
    }
}

//$item_result['created_by'] gives back a digit
user_info($item_result['created_by'], 'voornaam, achternaam')

Im stuck in the while loop.
I am not realy that good in the loops.
So i tried something and to me its seems logical.
But in some way it wont work.

A: try change
  while($param = $fetch) {
    return $data[$param];
}

on foreach loop:
$temp = array();
foreach($featch as $key){
  $temp[$key] = (empty($data[$key]) ? ''  :  $data[$key] );
}
return $temp;

UPDATE
Or you can use for loop :
$temp = array();
for( $i =0; $i < count($fetch); $i++){
  $temp[$fetch[$i]] = (empty($data[$fetch[$i]]) ? ''  :  $data[$fetch[$i]] );
}
return $temp;

UPDATE 2
OR while loop
$temp = array();
while(count($fetch)){
  $key = array_shift($fetch);
  $temp[$key] = (empty($data[$key]) ? ''  :  $data[$key] );
}
return $temp;

A: It is working now!
What I have now is:
$fetch = explode(", ", $fetch);
    $temp = array();
    for ($i = 0; $i < count($fetch); $i++) {
        $temp[$fetch[$i]] = (empty($data[$fetch[$i]]) ? '' : $data[$fetch[$i]]);
    }
    foreach ($temp as $data) {
        echo $data . ' ';
    }

A: The problem is in -
$fetch = explode(", ", $fetch);
print_r($fetch);
while($param = $fetch) {
    return $data[$param];
}

$fetch is an array now and $param is not defined.

You can try this -
$fetch = explode(", ", $fetch);
$i = 0;
$newData = array();
while($i < count($fetch)) {
    $newData[$fetch] = $data[$fetch];
    $i++;
}
return $newData;

I would suggest to use foreach instead of while.

A: Alternatively you could use the following if it HAS to be in a while loop
$data=array();
while (list($var, $val) = each($fetch)) {
        $data[$var]=$val;
}


text:
Q: PHP not returning any data when sent an ajax request When I send an ajax post request to my getMessages.php file it doesn't return anything.
I've tried manually setting the array values and printing them in the console and that seems to work.
getMessages.php
<?php

require_once "mysqli.php";

$data = array();

if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
    $username = $_SESSION["username"];

    $result = mysqli_query($conn, "SELECT msg_startuser, msg, time
        FROM messages
        WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
        UNION
        SELECT msg_startuser, msg, time
        From messages
        WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
        order by time;
    ");

    while ($row = mysqli_fetch_array($result)) {
        $data['startuser'] = $row['msg_startuser'];
        $data['msg'] = $row['msg'];
    }
}

echo json_encode($data);
exit;
?>

js ajax
function getChat() {

    $.ajax({
        url: 'getMessages.php',
        type: 'POST',
        data: {getChat: 'yes'},
        dataType: 'JSON',
        success: function(data) {
            // testing
            console.log(data.startuser, data.msg);
        }

    })

}

I want it to print out in the console for testing.

A: data is overwritten in the loop again and again, I guess you would like to do something like this:
$x = 0;
while ($row = mysqli_fetch_array ($result)) {
        $data[$x]['startuser'] = $row['msg_startuser'];
        $data[$x]['msg'] = $ row['msg'];
        $x++;
}

A: Ooops!
I forgot to start the session!
Thanks PatrickQ!

A: This will solve the problem since you are returning response as objects
An Updates:
You will need to initialize session

and data parameters for an array should be inside the the if statements
Try code below
<?php

require_once "mysqli.php";
session_start();

if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
    $username = $_SESSION["username"];

$data = array();

    $result = mysqli_query($conn, "SELECT msg_startuser, msg, time
        FROM messages
        WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
        UNION
        SELECT msg_startuser, msg, time
        From messages
        WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
        order by time;
    ");

    while ($row = mysqli_fetch_array($result)) {
         $startuser = $row['msg_startuser'];
        $msg = $row['msg'];

$data = array("startuser" =>$startuser, "msg" =>$msg);
    }

echo json_encode($data);
exit;

}
?>

so in ajax console. this line of code will work fine
console.log(data.startuser, data.msg);

A: Hi you can try this way:
The php script :
<?php
require_once "mysqli.php";
session_start();// start the session
$data = array();
if (isset($_SESSION["username"])) {
  if (isset($_POST["endUser"]) &&  isset($_POST["action"])) {
  $case = $_POST["action"];
  $endUser = $_POST["endUser"];
  $username = $_SESSION["username"];
  switch (case) {
    case 'getChat':
    $result = mysqli_query($conn, "SELECT msg_startuser, msg, time
        FROM messages
        WHERE msg_startuser = '{$username}' and msg_enduser = '{$endUser}'
        UNION
        SELECT msg_startuser, msg, time
        From messages
        WHERE msg_startuser = '{$endUser}' and msg_enduser = '{$username}'
        order by time;
    ");

    while ($row = mysqli_fetch_assoc($resultado)) {
        if (isset($row['msg_startuser']) && isset($row['msg'])) {
          $temp = array(
            "user"=>$row['msg_startuser'],
            "msg"=>$row['msg']
          );
        }
        $data[] = $temp;
    }
    echo json_encode($data);
      break;
  }
  }
}else {
  echo "error-403";
}
 ?>

The javascript :
 function getChat() {

    return $.ajax({
         url: 'getMessages.php',
         type: 'POST',
         data: {action: 'getChat',endUser:'mariokiller470'},
         dataType: 'JSON'
     })

 }

getChat()
.done(function(response){
  console.log(response);
})

Hope it Helps


text:
Q: Strange requests to to my hostname, like "server.hostname.xx OPTIONS * HTTP/1.0" I setted up a new dedicated server, but I'm noticing strange requests, shown on the page Main >> Server Status >> Apache Status, WHM
11-1    -   0/0/159 .   0.16    57  0   0.0 0.00    0.66    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0
12-1    -   0/0/63  .   0.00    59  0   0.0 0.00    0.20    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0
13-1    -   0/0/161 .   0.00    58  0   0.0 0.00    0.75    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0
14-1    -   0/0/94  .   0.00    137 0   0.0 0.00    0.50    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0
15-1    -   0/0/55  .   0.00    136 0   0.0 0.00    0.42    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0
16-1    -   0/0/71  .   0.00    135 0   0.0 0.00    0.34    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0
17-1    -   0/0/48  .   0.19    71  0   0.0 0.00    0.29    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0
18-1    18132   0/60/116    _   0.29    6   14  0.0 0.28    0.50    41.226.107.166  server.hostname.com NULL
19-1    17678   0/87/98 _   0.46    9   15  0.0 0.59    0.64    200.165.138.70  server.hostname.com NULL
20-1    18424   0/16/36 W   0.09    0   0   0.0 0.06    0.19    127.0.0.1   server.hostname.com GET /whm-server-status/ HTTP/1.0
21-1    -   0/0/78  .   0.71    408 0   0.0 0.00    0.35    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0
22-1    -   0/0/1   .   0.00    734 0   0.0 0.00    0.00    127.0.0.1   server.hostname.com OPTIONS * HTTP/1.0

I really have a big ammount of these kind of requests, and what I think that it's strange, are the ip's where they came from.
I know 127.0.0.1 is normal, but there are requests from several different ips, like from korea, united states, etc.
What this means? Should I worry?

A: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

and

If the Request-URI is an asterisk (" * "), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the " * " request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).

So yes, it can be used as preparation procedure before any attack, so you should watch your logs, but it isn't attack necessarily. This type of call is literally standard
better to use some type of LogWatch utility to alert you on non-standard requests


text:
Q: Finding multiple max elements in a vector C++ So.. I am trying to find the maximum value of a vector and its position in the vector. I am using a for loop, and it's working fine. My problem is, that if the maximum value appears more than once, I want to know all the positions in which it appears in the vector.. So, how could I manage this?
So far, this is the code I am using: (the vector called v has elements that I read from a file but I will not add that part of the code)
std::vector<double>v;
double maxvalue;
int position=0;
maxvalue = v[0];

for (unsigned int i=0; i<v.size(); i++){
    if (v[i]> maxvalue){
        maxvalue=v[i];
        position= i;
    }
}

A: You could modify your approach to keep a vector of indices where the maximum occurred:
#include <cfloat>
#include <iostream>
#include <utility>
#include <vector>

std::pair<double, std::vector<std::size_t>> FindMaxElements(std::vector<double> const& v)
{
    std::vector<std::size_t> indices;
    double current_max = -DBL_MAX;

    for (std::size_t i = 0; i < v.size(); ++i)
    {
        if (v[i] > current_max)
        {
            current_max = v[i];
            indices.clear();
        }

        if (v[i] == current_max)
        {
            indices.push_back(i);
        }
    }

    return std::make_pair(current_max, indices);
}

int main()
{
    auto result = FindMaxElements({1, 4, 7, 2, 7, 3});
    std::cout << "max: " << result.first << '\n';
    std::cout << "indices: ";
    for (auto i : result.second)
         std::cout << i << ' ';
}

Output
max: 7
indices: 2 4

A: Here is a two-pass version using the standard library (whereas it might be cleaner without it):
#include <vector>
#include <algorithm>

int main()
{
    std::vector<double> v {/* fill it*/ };
    std::vector<int> pos;

    auto it = std::max_element(std::begin(v), std::end(v));
    while (it != std::end(v))
    {
        pos.push_back(std::distance(std::begin(v), it));
        it = std::find(std::next(it), std::end(v), *it);
    }
    //...
}

A: The function template below, find_maximums(), returns an std::vector<size_t> that contains the positions where the maximums are in the input vector. Note that it returns an empty vector of indexes if the input vector is empty.
template<typename T>
auto find_maximums(const std::vector<T>& v) {
   std::vector<size_t> indexes;

   for (auto it_max = std::max_element(v.begin(), v.end()); it_max != v.end();
        it_max = std::find(it_max+1, v.end(), *it_max))
   {
      auto index = std::distance(v.begin(), it_max);
      indexes.push_back(index);
   }

   return indexes;
}

As an example of use:
auto main() -> int {
   std::vector<int> v = {11, 7, 3, 11, 0, 7, 1, 11, 11};
   auto max_indexes = find_maximums(v);

   if (max_indexes.empty())
      return 1;

   std::cout << "max: " << v[max_indexes.front()] << std::endl;
   std::cout << "max at positions: ";
   for (auto idx: max_indexes)
      std::cout << idx << ' ';
   std::cout << '\n';
}

It outputs:
max: 11
max at positions: 0 3 7 8

A: Passing a couple of iterators and a comparator
template <class It,
          class Comp = std::less<typename std::iterator_traits<It>::value_type>>
auto max_elements_indices(It first, It last, Comp cmp = Comp{})
{
    // This function returns a vector of indices, so to get the maximum, the caller
    // should first check if the returned vector is empty and then use one of
    // those indices to retrieve the value.
    std::vector<std::size_t> indices;
    if (first == last)
        return indices;

    // Using the first element instead of a sentinel value is easier to generalize
    indices.push_back(0);
    auto value = *first;

    for (auto i = std::next(first); i != last; ++i)
    {
        // The most common case should be an element below the maximum
        if ( cmp(*i, value) )
            continue;
        else
        {
            if ( cmp(value, *i) )
            {
                value = *i;
                indices.clear();
            }
            indices.push_back(std::distance(first, i));
        }
    }
    return indices;
}

It is testable here.


text:
Q: Can't parent objects in unity for oculus quest grab script preface: i am very new to c#, and this is an object grabbing script i have taken from a prefab and edited.
script goal: detect if a game object is in pickup distance. if it is, when the grip trigger is pressed, parent the object to the virtual hand. when the trigger is released, remove the parent relationship. Also, while the object is parented to the controller, if the B button is held, scale the object up, and if the A button is held, scale the object down, and reset the scale upon thumbstick click.
I can see when my controller collides with the game object, but when i press the designated button to parent the object, nothing seems to happen.
I'd really appreciate any help I could get with this script, as there might be a significant amount i'm doing wrong.
I should mention that I don't really need any sort of physics simulations, all i need is the ability to manipulate an object floating in space for viewing purposes.
Thanks in advance!
Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Grabber : MonoBehaviour
{

    // Update is called once per frame
    void Update()
    {
        OVRInput.Update();

        if ((OVRInput.Get(OVRInput.Axis1D.SecondaryHandTrigger)) > 0.2f && CollidingObject)
        {
            GrabObject();
        }
        if ((OVRInput.Get(OVRInput.Axis1D.SecondaryHandTrigger)) < 0.2f && ObjectInHand)
        {
            ReleaseObject();
        }
        if (OVRInput.Get(OVRInput.Button.Two) && ObjectInHand)
        {
            ScaleUp();
        }
        if (OVRInput.Get(OVRInput.Button.One) && ObjectInHand)
        {
            ScaleDown();
        }
        if (OVRInput.Get(OVRInput.Button.SecondaryThumbstick) && ObjectInHand)
        {
            ScaleReset();
        }
    }

    public GameObject CollidingObject;
    public GameObject ObjectInHand;

    public void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.GetComponent<Rigidbody>())
        {
            CollidingObject = other.gameObject;
        }
    }

    public void OnTriggerExit(Collider other)
    {
        CollidingObject = null;
    }

    private void GrabObject()
    {
        ObjectInHand = CollidingObject;
        ObjectInHand.transform.SetParent(this.transform);
        ObjectInHand.GetComponent<Rigidbody>().isKinematic = true;
    }

    private void ReleaseObject()
    {
        ObjectInHand.GetComponent<Rigidbody>().isKinematic = false;
        ObjectInHand.transform.SetParent(null);
        ObjectInHand = null;
    }

    Vector3 scaleChangeUp = new Vector3(0.01f, 0.01f, 0.01f);
    Vector3 scaleChangeDown = new Vector3(-0.01f, -0.01f, -0.01f);
    public void ScaleUp()
    {
        ObjectInHand.transform.localScale += scaleChangeUp;
    }

    public void ScaleDown()
    {
        ObjectInHand.transform.localScale += scaleChangeDown;
    }

    private void ScaleReset()
    {
        ObjectInHand.transform.localScale = Vector3.one;
    }

}


text:
Q: .net core 2.2 site looks files on wrong path I am doing maintenance to a .net core 2.2 application. On several computers it works perfectly, but when I publish it to the server where it should be it gives error in all references to a file. Example: File.ReadAllText ("./App/Config.json").
The problem is that it looks for the file in c:\windows\system32\inetsrv..., instead of looking for it in the folder where the site is published. This generates errors like:
Could not find a part of the path 'c:\windows\system32\inetsrv\App\Config.json'.
of course the site is published in c:\inetpub\wwwroot[sitename]
What could be causing this behavior?

A: Using relative paths is not good practice on server side code.
What you should use instead is IWebHostEnvironment and it's property WebRootPath
To access that you can do it inside your controller like this:
public class MyController : Controller
{
    private IWebHostEnvironment _env;

    public MyController(IWebHostEnvironment env)
    {
        _env = env;
    }

    public SomeMethod()
    {
        foreach(string filePath in Path.Combine(_env.WebRootPath))
        {
            string file = filePath;
        }
    }
}

If you do not want to inject it like this or you need to access in out of controller inside Startup.cs add public static IWebHostEnvironment _env and edit this:
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
    Configuration = configuration;
    _env = env;
}

and now you can access it from anywhere with Startup._env


text:
Q: Pass Variables to SSIS package C# I am wanting to pass a couple of Variables into my SSIS package when calling it but I can't seem to get the correct syntax for it to work.
Microsoft.SqlServer.Dts.Runtime.Wrapper.Application app = new Microsoft.SqlServer.Dts.Runtime.Wrapper.Application();

Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSPackage100 pkg = app.LoadPackage(pkgLocation, false, null);

So the above bits work but when I go to add a variable it does not work:
pkg.Variables["mode"].Value = "test";

The error I am getting:
'IDTSPackage100' does not contain a definition for 'Variables' and no extension method 'Variables' accepting a first argument of type 'IDTSPackage100' could be found (are you missing a using directive or an assembly reference?)'

A: Ben,
Any reason why you are using the wrapper assemblies? IDTSPackage100 interface does not contain the Variables property. But the Package class found in the Microsoft.SqlServer.Dts.Runtime namespace contains the Variables property.
So use the Application and Package classes from the Microsoft.SqlServer.Dts.Runtime namespace (found in the Microsoft.SqlServer.ManagedDTS assembly) instead of the wrapper namespace/assembly and you should be able to access the Variables property.
Update:
If you still want to use the wrapper namespace, you can cast the IDTSPackage100 object to the IDTSContainer100 object and then access the Variables from there.
IDTSContainer100 container = (IDTSContainer100)pkg;
container.Variables["User::mode"].Value = "test";

Update 2:
The call on Execute method would then look like this:
pkg.Execute(null, container.Variables, null, null, null);


text:
Q: How to copy from host machines to control machine using Ad-hoc command? Previously, I ran a shell-script from control host and redirected all contents to output files. So, those files are in host provided directory.
Then I wanted to copy all the files from hosts to control host.
Is there anyway to do that?
For Ansible ad-hoc command to copy, as far as I know is something like
ansible all -m copy -a "src=..... dest=....."

I'm not sure if this also can bring back from host to control host?

A: use: fetch modeule
Example from documentation
# Store file into /tmp/fetched/host.example.com/tmp/somefile
- fetch:
    src: /tmp/somefile
    dest: /tmp/fetched


text:
Q: Content resize ionic 2 I'm having a problem with usage of content.resize(); in tabs with native keyboard plugin. Can any anyone guide me how to use and where to use content resize with tabs when the content dimension changes due to native keyboard appearance? Below is the code I'm using:
this.keyboard.onKeyboardHide().subscribe(() => {
      this.isKeyboardHide = true;
      setTimeout(() => {
        this.content.resize();
      }, 500);
    });

I'm unable to resize my child view content once the android keyboard appears. Here is the sample code on github.


text:
Q: How to append input values into HTML elements with React I'm trying to build an input form that will display submitted values in another page using React hooks. I can see the values when console logged and what I'm looking for is how to append them as HTML elements.
The following code is a simplified version of my work.
const DisplayList = ({ inputs }) => (

page 2 (parent component)

{inputs}

);

const AddList = () => {
  const onSubmitForm = () => {
    console.log(`
      First name: ${inputs.firstName}
      Last name: ${inputs.lastName}`);
  };

  const { inputs, handleInputChange, handleSubmit } = InputForm(onSubmitForm);

  return (

page 1 (child component)

      <form onSubmit={handleSubmit}>
        First Name:
        <input
          type="text"
          name="firstName"
          onChange={handleInputChange}
          value={inputs.firstName || ""}
          required
        />
        Last Name:
        <input
          type="text"
          name="lastName"
          onChange={handleInputChange}
          value={inputs.lastName || ""}
          required
        />
        <button type="submit">Submit</button>
      </form>

      <DisplayList />

  );
};

export default AddList;

Any help and guide provided are greatly appreciated!
Here's a link to check out full code: Code Sandbox

A: I'm not sure what you are trying to do maybe:
Pass inputs in AddList:
<DisplayList inputs={inputs} />
And change DisplayList to:
const DisplayList = ({ inputs }) => (

page 2 (parent component)

{JSON.stringify(inputs)}

);

A: I just gave inputs object as props for DisplayList component and call the properties of firstName and lastName within p tags.
<DisplayList inputs={inputs} />

const DisplayList = ({ inputs }) => (

page 2 (parent component)

First Name:{inputs.firstName}

Lastname:{inputs.lastName}

);

A: Passed input as props to second page component like below.
DisplayList inputs={inputs} />

And
Used it in the component like below.
const DisplayList = ({ inputs }) => (

page 2 (parent component)

{inputs.firstName}

{inputs.lastname}

);


text:
Q: What is the difference between a reference variable and a const pointer variable?
Possible Duplicate:
Difference between pointer variable and reference variable in C++

This is a continuation of this question
Is a reference variable just another name of const pointer variable? If they are different what is the difference between a variable declared as a reference variable and a variable declared as a const pointer variable?

A: Just for fun:) A reference can not be NULL but a const pointer can be.

A: OK. The problem is that there is no such thing like reference variable. Reference is not a variable at all. It is not an object. It actually has no size at all. It is just alternative name of the original object.
Check this:
struct A
{
   int i[5];
};

int main()
{
   std::cout << (sizeof(A&) == sizeof(A)) << std::endl;
   std::cout << (typeid(A&) == typeid(A)) << std::endl;
   return 0;
}

A& has the same size as A
A& has the same type as A

A:
Is a reference variable just another name of const pointer variable?

No.

If they are different what is the difference between a variable declared as a reference variable and a variable declared as a const pointer variable?

They are completely different things, and there is not enough room to explain everything you need to know here. Read this. Actually, read the entire FAQ. You'll learn a lot.


text:
Q: Is there any before page load event? I need actually to show a div with activity indicator before the page is loaded?

A: Just put the div on the page and hide it when the page loads. There's no need for an event..

A: Do you have JQuery? JQuery provides a ready() method that can (apparently) be used on any element.


text:
Q: limiting ANCOVA comparisons in R So I have my data
 str(data1)
'data.frame':   12 obs. of  11 variables:
 $ Genotype      : Factor w/ 2 levels "EXP","WT": 2 2 2 2 2 2 1 1 1 1 ...
 $ Stimulus       : Factor w/ 2 levels "2oo","o": 2 2 2 1 1 1 2 2 2 1 ...
 $ MI          : num  0.08 -0.13 0.08 -0.39 -0.29 -0.16 0.13 0.08 0.08 -0.31  ..
 ...

and I perform my anova
 aov.MI <- aov(MI ~ Genotype*Stimulus, data=data1)

But if I run a TukeyHSD I get all the possible combinations
    $`Genotype:Stimulus`
                  diff          lwr       upr     p adj
WT:2oo-EXP:2oo -0.08000000 -0.363226668 0.2032267 0.8031324
EXP:o-EXP:2oo   0.29666667  0.013439999 0.5798933 0.0403984
WT:o-EXP:2oo    0.21000000 -0.073226668 0.4932267 0.1599365
EXP:o-WT:2oo    0.37666667  0.093439999 0.6598933 0.0118146
WT:o-WT:2oo     0.29000000  0.006773332 0.5732267 0.0448986
WT:o-EXP:o     -0.08666667 -0.369893335 0.1965600 0.7644713

How can I set the TukeyHSD, or do any other appropriate post-analysis only to have the
WT:2oo-EXP:2oo
EXP:o-EXP:2oo
WT:o-EXP:2oo
WT:o-EXP:o
comparisons and ignore the ones which do not share a common factor i.e. WT:2oo-EXP:o and WT:o-EXP:2oo? Can I use the 'which' option in TukeyHSD to be so specific? Is there an easier way to do it?
Thanks for your kind help.


text:
Q: How to keep the ANSI code when I write it in a file I want to write in a file a word with a code ANSI but slurm remove it leash only the word
job.sh
 #!/bin/bash
    #SBATCH --job-name=test
    #SBATCH --nodes=1               # number of nodes
    #SBATCH --ntasks-per-node=1     # number of cores
    #SBATCH --time=24:00:00          # walltime
    #SBATCH --output=out.txt
    #SBATCH --error=err.txt

module load R
Rscript test.R

test.R
library(crayon)
fileConn<-file("output.txt")
x <- as.character(yellow("hello world"))
writeLines(x, fileConn)
close(fileConn)

output.txt
hello world
# i want this \033[33mhello wrold\033[39m

When I use the Rscript command only, it works as I wish (it writes the ANSI code in the output.txt file), but if I go through slurm with the sbatch job.sh command, it does not write the code ANSI.


text:
Q: Vaadin object is not an instance of declaring class I'm trying to call a method in class named (DataActions) to the dashboard view so the grid can be able to receive the objects given after the method execution, but still no luck solving this error (java.lang.IllegalArgumentException: object is not an instance of declaring class).
-Class (DataSession) is the class responsible for opening the database session.
-Class (DataActions) is the class responsible for the methods used to extract information from the database using a session created by an (DataSession object)
-Method updateGrid calls a method in (DataActions) using an object created.
This project was created with vaadin hello world example project, so it uses springboot (version 2.4.5) and vaadin flow (version 14.7.0).
--Dashboard View--
package com.example.application.views.dashboard;

import com.example.application.Controller.DataActions;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.example.application.Model.PatientsTblEntity;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.PageTitle;
import com.example.application.views.MainLayout;
import com.vaadin.flow.router.RouteAlias;

@PageTitle("Dashboard")
@Route(value = "dashboard", layout = MainLayout.class)
@RouteAlias(value = "", layout = MainLayout.class)
public class DashboardView extends VerticalLayout {

    Grid<PatientsTblEntity> patients_grid = new Grid<>(PatientsTblEntity.class);
    DataActions actions = new DataActions();
    public DashboardView(){
        addClassName("list-view");
        configureGrid();
        add(patients_grid);
        updateGrid();

    }

    /*
        -Configuring grid properties, so it can handle data coming from another function
     */
    public void configureGrid(){
        patients_grid.addClassName("contact-grid");
        patients_grid.setSizeFull();
//        patients_grid.setColumns("txtCode", "txtName", "dblAge", "datDateOfBirth", "datOfLasttVisit");
        patients_grid.getColumns().forEach(patientsTblEntityColumn -> {
            patientsTblEntityColumn.setAutoWidth(true);
        });
    }

    /*
        -Update grid with information coming from the database using actions from class DataActions
     */
    public void updateGrid(){
            patients_grid.setItems(actions.getAllPatientsList());

    }

}

--DataActions class--
package com.example.application.Controller;

import com.example.application.Model.PatientsTblEntity;
import org.hibernate.Session;

import java.util.List;

public class DataActions {
    public DataActions(){}
    DataSessions dataSessions = new DataSessions();
    /*
        -Variable where session is created
        -Created as a variable, so it can be opened and closed at ease in every function
     */
    private Session session = dataSessions.getSession();

    public List<PatientsTblEntity> getAllPatientsList(){
        session.beginTransaction();
        List<PatientsTblEntity> list = session.getSession().createQuery("FROM PatientsTblEntity P").getResultList();
        session.close();
        return list;
    }

--Pom.xml file--
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- Vaadin project from https://start.vaadin.com/project/a13f6a96-e47e-432d-bf78-e4e60571348e -->
    <groupId>com.example.application</groupId>
    <artifactId>asd-8</artifactId>
    <name>Project base for Spring Boot and Vaadin Flow</name>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <java.version>8</java.version>
        <vaadin.version>14.7.0</vaadin.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
    </parent>

    <repositories>
        <!-- The order of definitions matters. Explicitly defining central here to make sure it has the highest priority. -->

        <!-- Main Maven repository -->
        <repository>
            <id>central</id>
            <url>https://repo.maven.apache.org/maven2</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <!-- Repository used by many Vaadin add-ons -->
        <repository>
            <id>Vaadin Directory</id>
            <url>https://maven.vaadin.com/vaadin-addons</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <!-- Main Maven repository -->
        <pluginRepository>
            <id>central</id>
            <url>https://repo.maven.apache.org/maven2</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-bom</artifactId>
                <version>${vaadin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>com.vaadin</groupId>
            <!-- Replace artifactId with vaadin-core to use only free components -->
            <artifactId>vaadin</artifactId>
            <exclusions>
                <!-- Webjars are only needed when running in Vaadin 13 compatibility mode -->
                <exclusion>
                    <groupId>com.vaadin.webjar</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.webjars.bowergithub.insites</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.webjars.bowergithub.polymer</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.webjars.bowergithub.polymerelements</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.webjars.bowergithub.vaadin</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.webjars.bowergithub.webcomponents</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-spring-boot-starter</artifactId>
            <exclusions>
                <!-- Excluding so that webjars are not included. -->
                <exclusion>
                    <groupId>com.vaadin</groupId>
                    <artifactId>vaadin-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.vaadin.artur</groupId>
            <artifactId>a-vaadin-helper</artifactId>
            <version>1.7.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-testbench</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>9.2.1.jre8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.5.7.Final</version>
        </dependency>

        <!-- Include JUnit 4 support for TestBench and others -->
        <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <defaultGoal>spring-boot:run</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- Clean build and startup time for Vaadin apps sometimes may exceed
                     the default Spring Boot's 30sec timeout.  -->
                <configuration>
                    <wait>500</wait>
                    <maxAttempts>240</maxAttempts>
                </configuration>
            </plugin>

            <!--
                Take care of synchronizing java dependencies and imports in
                package.json and main.js files.
                It also creates webpack.config.js if not exists yet.
            -->
            <plugin>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-maven-plugin</artifactId>
                <version>${vaadin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>prepare-frontend</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <!-- Production mode is activated using -Pproduction -->
            <id>production</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.vaadin</groupId>
                        <artifactId>vaadin-maven-plugin</artifactId>
                        <version>${vaadin.version}</version>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>build-frontend</goal>
                                </goals>
                                <phase>compile</phase>
                            </execution>
                        </executions>
                        <configuration>
                            <productionMode>true</productionMode>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <id>it</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>start-spring-boot</id>
                                <phase>pre-integration-test</phase>
                                <goals>
                                    <goal>start</goal>
                                </goals>
                            </execution>
                            <execution>
                                <id>stop-spring-boot</id>
                                <phase>post-integration-test</phase>
                                <goals>
                                    <goal>stop</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>

                    <!-- Runs the integration tests (*IT) after the server is started -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <trimStackTrace>false</trimStackTrace>
                            <enableAssertions>true</enableAssertions>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

    </profiles>
</project>

A: I have found the solution, I was missing the annotation @Component in the class where the method is, and the annotation @Autowired where I want the instance of the class to be created.


text:
Q: QDialog not such file or directory - Qt Windows I just installed Qt Creator 2.6.1 based on Qt 5.0.
I'm trying to open a project made on 4.8 but I can't compile it. It keeps showing me errors of "not such file or directory".
error: C1083: Cannot open include file: 'QtGui/QApplication': No such file or directory

error: C1083: Cannot open include file: 'QDialog': No such file or directory

error: C1083: Cannot open include file: 'QMainWindow': No such file or directory

error: C1083: Cannot open include file: 'QWidget': No such file or directory

And many more.
I added the qmake.exe path to PATH...do I need to do something else?

A: I had this problem, made two changes

*

*echo "QT += widgets" >> /fileProject.pro

*add #include  QDialog  in the file containign QDialog declarations
previously including QtGui was enough but QT5 splits widgets into more .h files, thus making necessary to include them. For example QtMenuBar was included in QtMenu.h but now it requires QtMenuBar.h to be #included

A: Read the transition guides from Qt4 to Qt5. Link1 Link2 Link3

One of the major internal infrastructural changes in Qt 5 compared to
  Qt 4 is the splitting of widgets from the QtGui module into a new
  QtWidgets module. This obviously will require buildsystem changes at
  least, but also causes the need for downstreams to add includes for
  headers which were not needed before, as those includes were removed
  from headers which now remain in the QtGui module.
Another includes-related issue in porting from Qt 4 to Qt 5 is dealing
  with includes for classes which have moved to the QtWidgets module.
  Whereas Qt 4 based code might use

#include <QtGui/QWidget>
This must be updated to either

#include <QtWidgets/QWidget>
Or more portably (Which works in Qt 4 and Qt 5):

#include <QWidget>


text:
Q: Angular CLI: Mount app to domain subpath - relative paths for static files My Angular2 application, built with ng build --prod, is mounted to https://[domainname]/app.
The problem is that scripts and styles injected in index.html have paths like
src="styles.8e0edbbd6ad2cb36be49.bundle.js"

so page is trying to look for them in root.
How to change it to:
src="./styles.8e0edbbd6ad2cb36be49.bundle.js"

Or is there other correct way to deploy app to domain subpath with Angular CLI?

A: use below  command for building angular 2 using cli
# Sets base tag href to /myUrl/ in your index.html
ng build --base-href /myUrl/
ng build --bh /myUrl/


text:
Q: Firebase: Create New Object With Push and Then Push to it Simultaneously Tools: Vanilla Firebase and Vanilla JavaScript
So I'm creating a new convo and adding it's first message in one go.
convos:{
    uniqueConvoID1:{
        uniqueMessage:{
          text:"Hi Gus"
        },
        ...
    },
    ...
}

But because both need a unique Id I essentially need to do two pushes simultaneously.One creates the new object (like uniqueConvoID1), and then creates a new message inside like (uniqueMessageId).
I've tried creating an empty object first and then pushing the message but I don't think creating an empty object first is valid.
Question:
  How do I then initialize an object within an object where both objects need a unique key?
What I tried:(I pushed a new message and got the convo back.)
var newConvoIDRef =  firebaseConvosRef.push({
    authorName: 'Nick',
    text:"Hey!How you been?",
    timestamp: Date.now() - 99999
 });

Which created this in the Dashboard:
-convos
     - -K2111111111111111 //unique convo id
         -authorName:"Nick"
         -text:"Hey! How have you been?"
         -timestamp:1446866141625

But what I need to initial the new convo this way:
 -convos
     - -K2111111111111111 unique convo id
         - -K222444444444444 unique message id
             -authorName:"Nick"
             -text:"Hey! How have you been?"
             -timestamp:1446866141625

A: I think you're seriously overcomplicating things. Firebase creates paths automatically as you add new values. So this will create the entire chain:
var convosRef = new Firebase('https://yours.firebaseio.com/convos');
var convRef = convosRef.push();
var msgRef = convRef.push();

msgRef.set({
    authorName: 'Nick',
    text:"Hey!How you been?",
    timestamp: Date.now() - 99999
 });

Note: Firebase also cleans paths up automatically when all values under them are removed. So you can remove the entire branch of the tree, by:
msgRef.remove();


text:
Q: I do not know how to evaluate an expression with two? I am not sure how to evaluate this expression inside the while loop.  I understand that when the statement is true you do the first one and false you do the second but its is confusing me on what I should do when there are two conditional statements.
int x = 152487;
int ct1 = 0;
int ct2 = 0;

while(x > 0)
{ x % 2 ? x > 5 ? ct1++ : ct2++ : ct2++;

  x /= 10;
}

printf("ct1: %d\n", ct1);
printf("ct2: %d\n", ct2);

A: Parenthesize the expression and it will be clear.
x % 2 ? (x > 5 ? ct1++ : ct2++) : ct2++;

If x is odd, then x % 2 evaluates to true. This means the value of the above expression is
(x > 5 ? ct1++ : ct2++)

which is again a conditional expression. If x is even, the expression evaluates to
ct2++


text:
Q: wpcf7 dynamic email-tag content Description:

*

*WordPress Contact Form 7;

*Mailing using smtp;

*Form Settings: "use html-format" + "mail2 use html-format" checked;

*Form Settings: Email body : just one mail-tag [calculated-template];

*Problem with paragraph tag solved (all mail-tags upon receiving are shown inside "p" html-tag);

[calculated-template] is a mail-tag dynamically filled with html, based on submitted objects handled by VueJS2 on frontend;
[calculated-template] is populated by hooking at action 'wpcf7_posted_data':
add_action('wpcf7_posted_data', array('vue_handler','handle'), 1, 1);

vue_handler::handle($data) receives $data array with some wpcf7 data which can be modified. Contents of $data array:
_wpcf7 = "1166"
_wpcf7_version = "4.9.2"
_wpcf7_locale = "ru_RU"
_wpcf7_unit_tag = "wpcf7-f1166-p1167-o1"
_wpcf7_container_post = "1167"
columns-stringified = ""
fences-stringified = ""
your-name = "name"
your-email = "email@test.com"
calculated-template = ""

Then vue_handler::handle($data) injects html into email-tag [calculated-template].
Problem:
Finally [calculated-template] html-contents rendered escaped (Mailtrap.io, "HTML Source" tab):

<!doctype html>

<title>Title</title>

Example Header

The main idea of the snippet: opening and closing html-tag symbols "<", ">" rendered escaped: "<", ">";

A: SOLVED
By using another hook wpcf7_before_send_mail
In which I fully replaced mail body with my dynamic html.
List of all hooks:
http://hookr.io/plugins/contact-form-7/4.5.1/hooks/#index=a


text:
Q: OpenCL mandlebrot plot, very noisy on GPU In an attempt learn OpenCL I decided to make a plot of the Mandlebrot set.
It seems to work fine, on the CPU that is. The two images below shows, first the kernel executed on the CPU (Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz), and the second image shows the image when rendered on the GPU (HD Graphics 4000).
This is the kernel:
typedef float2 Complex;

Complex complex_mul(Complex a, Complex b)
{
    return (Complex)(a.s0*b.s0-a.s1*b.s1, a.s1*b.s0+a.s0*b.s1);
}

__kernel
void mandelbrot (__global float* p)
{
    const int x = get_global_id (0);
    const int y = get_global_id (1);
    const int arrlen = PIXELS_WIDTH * PIXELS_HEIGHT;

    float width = PIXELS_WIDTH;
    float height = PIXELS_HEIGHT;

    float whRatio = width / height;

    float tx = x;
    float ty = y;

    float px = ((tx / float(PIXELS_WIDTH)) - 0.5) * 2.0;
    float py = ((ty / float(PIXELS_HEIGHT)) - 0.5) * 2.0 / whRatio;

    Complex z;
    z.s0 = 0;
    z.s1 = 0;
    Complex c;
    c.s0 = px;
    c.s1 = py;

    float color = 0.0;

    int iterations = 500;
    for (int i = 0; i < iterations; i++)
    {
        z = complex_mul(z,z) + c;

        if ( length(z) > 2.0)
        {
            float u,o;
            u = i;
            o = iterations;
            color = ( u / o );
            break;
        }
    }

    const int pId =  y * PIXELS_WIDTH + x;
    if ( pId < arrlen )
    {
        p[ pId ] = color;
    }
}

And the host program... at least the interesting bit (I hope):
size_t globalSizes[2] = { PIXEL_WIDTH, PIXEL_HEIGHT };

cl_mem image_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(image_data), NULL, &error);
CheckError(error);

error = clSetKernelArg(kernel, 0, sizeof(cl_mem), &image_buffer);
CheckError(error);

error = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, globalSizes, NULL, 0, NULL, &computeDone);
CheckError(error);

clWaitForEvents(1, &computeDone);

error = clEnqueueReadBuffer(queue, image_buffer, CL_TRUE, 0, sizeof(image_data), image_data, 0, NULL, NULL);
CheckError(error);

clReleaseMemObject(image_buffer);

I run this on a MacBook Pro with OS X 10.9.5. The noisy part around the set changes slightly (randomly) for each execution.
I hope that I've supplied enough information, and if anyone have a suggestion on what might be wrong, I'll be glad to hear!
Thanks : )

EDIT
I did the following:
change all number literals to floats as suggested by huseyin tugrul buyukisik in the comment.
Then changed length(z) > 2.0 to (z.s0 * z.s0) + (z.s1 * z.s1) > 4.0f
and then tried to play around with the iteration counter.
It seems that the noise is very sensitive to the iteration number.
For example, 1000 iterations generates very much noise, yet 1009 iterations makes a very smooth image. Any suggestions on why this happens?
Cheers

A: Sometimes drivers have bugs on implementations of vectors on driver side. Trying a "scalar" version simply solves it if fp64 support or host-side element alignment checking doesn't do anything.
For example, my fx-8150 cpu had issues with float8 and float16 but gpus were ok with any native vector and there were no issues with fx-8150 in the distant past. Maybe we are forced(accidentally or knowingly) to buy new tech.
You should try different versions of drivers since sometimes corporations deliberately or accidentally tweak settings and corrupt support lists.
Maybe I'm wrong and your integrated gpu is dying.

A: Code works well with minor modifications (e.g. (float)(PIXEL_WIDTH) and 0.5f, etc.) on Windows 8.1 on the GPU using the latest driver for your type of processor, so this suggests a graphics driver issue on Mac.


text:
Q: Debugging revel with IntelliJ How can we configure IntelliJ to debug revel apps?
In Run/Debug Configurations, it's not at all obvious what to enter for File, Go tool arguments, and and Program arguments

A: Create your project, for this example i will be using canonical revel new github.com/myaccount/my-app

*

*Run in terminal revel run github.com/myaccount/my-app to generate tmp/main.go - this file is needed by intellij

*Select "Edit configuration" to create Run configuration. Select Go Build

*Select YOUR file "main.go"

*Paste in "Program arguments" string -importPath github.com\myaccount\my-app

*Click on "Before launch: ..." and create "Run external tool"

*There: Program: <your gopath>/bin/revel(Windows - revel.exe) Paramerets: build github.com/myaccount/my-app, Working dir <your gopath>/bin
Screenshot Example Config
Now You can Run and Debug in panel IntelliJ


text:
Q: Некорректно работает phpStorm с подсказками Всем привет!
Работаю в phpStorm и проекте yii2. Сначала все шло хорошо. Затем после очередного открытия данного проекта, исчезли возможности подсказки IDE касательно классов и методов классов. Например, создаю модель Category, где прописываю:
use yii\db\ActiveRecord;

В сообщениях phpStorm в нижней панели на вкладке Problems появляется сообщение 'Undefined class ActiveRecord'. Или, например, в контроллере прописываю use для модели Category, и IDE PHPStorm не видит такой путь. А, если писать в методе контроллера следующее:
 $this->data = Category::find()->all();

То при наборе текста, не подсвечивает методы Category, но видит свойство data у объекта $this. И таких примеров много. Как вернуть режим подсказок от phpStorm, чтобы правильно подсвечивало методы и свойства, а также namespace и use?

A: Иногда шторм глючит. Попробуйте в меню выбрать
File → Invalidate Caches
и перезагрузить шторм. Он пересчитает данные и индексы и должно стать хорошо.


text:
Q: docker for php5.3 on centos image I want to run legacy php 5.3 apps on centos 7. Since there is no php 5.3 build on centos 7, docker container looks like a preferred option.
I referred to this article to build a docker container but I am unable to access the php web pages from port 9003 in local host. The following are places where I may need help.

*

*There was an issue with using sockets in line 1 of the script, so I just deleted this line

*The container runs fine but when I run localhost:9003 on the browser I am not able to serve php pages from /var/www/html

I want to have apache and php files on local and only want to run php on the container..
help is greatly appreciated

A:
The container runs fine but when I run localhost:9003 on the browser I
  am not able to serve php pages from /var/www/html

You need to expose the ports by adding -p 9003:9003 to the run command.

A: Try run docker with network parameter like --network=<NETWORK>. looking for available network use command docker network ls.
i advise to use the bridge network mode:
docker --network=bridge


text:
Q: prime number problem: How can I show that;

For any prime $p,$ there exist $u, v\in\mathbb{N}\setminus{\{p\}}$  ( and depend on $p$) such that $\color{Purple}{p\mid uv}$ and both $$\color{Green}{\dfrac{u^2+p^2}{\dfrac{uv}{p}-p}}\,\,\,\,\,\text{,}\,\,\,\,\,\color{Red}{\dfrac{v^2+p^2}{\dfrac{uv}{p}-p}}\,\,\,\,\,\text{are integers.}$$

I have no idea to attempt this question. Any idea, hint or explanation would be appreciate.
Thank you.

A: $u=p, v = p+1$ work. I was just playing with it, so no constructive hint how to tackle this other than the obvious one that $u$ or $v$ or both need $p$ as a factor.
Edit: you added the constraint $u, v \ne p$. Then $u=2p, v= 3p$ work. If you try to make both the numerators and the denominator multiples of $p$, in the form denominator $ip$, numerator $ki p^2$, it's arguably the second natural attempt (after declining (2,2) as powers).

A: Take any two integers $m,n$ such that $mn-1 | p$ then $u=mp, v=np$ will work.


text:
Q: Hide the domain name on Sharepoint site On my Sharepoint document workspace site the users are able to publish files, news and tasks. Whenever a user for example publish a news post, the author name is displayed as DOMAIN\Username.
Is there any way I can hide the domain name from the author description? I want the site to show only Username.


text:
Q: Bootstrap dropdown nav only working with current page in dynamic navigation I build a website while learning PHP, SQL etc.
I am now trying to build on the original page I have made every works fine with the standard navigation, when I try to add a bootstrap navbar the dropdown box only appears for pages I am currently on.
On index.php none of the dropdowns work. The page has a CMS in the back end and I am trying to have the public side of the side just look nicer, and ensure that no matter how many new pages or subjects are in the database the css is applied to everything.
any assistance will be greatly appreciated!
bonus question: I would also like the carats to only appear when the "subject" has more than one page associated with it if that's possible, i cant figure out how to make that work either. eg: so when clicking on the subject you goto its only page on click, however if there is more than 1 page, a carrat appears and the dropdown menu is where you select your desired page from
My navigation is a function and works fine its only the css causing my initial issue.
function public_navigation($subject_array, $page_array) {
        $output = "";
        $output .= "
";
        $output .= "
";
        $output .= "<button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\"#myNavbar\">";
        $output .= "";
        $output .= "";
        $output .= "";
        $output .= "</button>";
        $output .= "Company";
        $output .= "
";
        $output .= "
";
        $output .= "
";
        $subject_set = find_all_subjects();
        while($subject = mysqli_fetch_assoc($subject_set)) {
            $output .= "
";
            $output .= "";
            $output .= htmlentities($subject["menu_name"]);
            $output .= "";

            if ($subject_array["id"] == $subject["id"] ||
                $page_array["subject_id"] == $subject["id"]) {
                $page_set = find_pages_for_subject($subject["id"]);
                $output .= "
";
                while($page = mysqli_fetch_assoc($page_set)) {
                    $output .= "
";
                    $output .= "";
                    $output .= htmlentities($page["menu_name"]);
                    $output .= "
";
                }
                $output .= "
";
                mysqli_free_result($page_set);
            }

            $output .= "
"; // end of the subject li
        }
        mysqli_free_result($subject_set);
        $output .= "

";
        return $output;
    }

EDIT: This is what the menu looks like
but if you click on anyof the other headings no dropdown box appears, and if on index.php with the generic welcome page none of the menus have dropdown boxes or let you navigate to them

A: Without knowing what is being passed in your $subject_array and $page_array it will be hard to say why this is failing, but almost certainly the problem is showing up in your if statement:
if ($subject_array["id"] == $subject["id"] || $page_array["subject_id"] == $subject["id"]) {

It looks like you don't need the if statement at all since you want to get the pages for the given subject every time. So I suggest you try removing the if and see what you get:
        $output .= "";

        $page_set = find_pages_for_subject($subject["id"]);
        $output .= "
";
        while($page = mysqli_fetch_assoc($page_set)) {
            $output .= "
";
            $output .= "";
            $output .= htmlentities($page["menu_name"]);
            $output .= "
";
        }
        $output .= "
";
        mysqli_free_result($page_set);

        $output .= "
"; // end of the subject li

now you'll have your dropdown menus for each subject and you only need to have a small if statement to add some extra CSS class or something to show which subject is the currently selected subject.


text:
Q: GDB with C++ substring passed to function gets overflow in printers.py to_string In GDB, I can print a substring, like so:
(gdb) print outStaticValue.substr(off,len)
$16 = "L"

But when I pass that substring to a function (say, second argument spec of edit_amt_justify) by value, the target function's argument variable is unprintable.  I get the following overflow error stepping into the function, and if I attempt to print spec separately, I get the same error:
edit_amt_justify (amt=..., spec=Traceback (most recent call last):
  File "/usr/share/gdb/python/libstdcxx/v6/printers.py", line 469, in to_string
    return self.val['_M_dataplus']['_M_p'].string (encoding, length = len)
OverflowError: signed integer is greater than maximum
, mp=0x89d6d0) at fmp_mapping_v3_class.cpp:3594
(gdb) next
(gdb) print spec
$17 = Traceback (most recent call last):
  File "/usr/share/gdb/python/libstdcxx/v6/printers.py", line 469, in to_string
    return self.val['_M_dataplus']['_M_p'].string (encoding, length = len)
OverflowError: signed integer is greater than maximum

The only thing I've been able to do to get around it is to put a temp string variable in the target function and assign the passed spec variable to it and then I can inspect the temp variable, e.g.:
std::string tmpstr = spec;

But that's tantamount to using the old printf approach of old, where it required adding custom code to debug your program.

GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-42.el5)

Is there a way to remedy this error?


text:
Q: Which UTM system do you recommend for Tamaulipas, Mexico? I'm working with QGIS 1.8.0. Could anyone tell me which UTM system would be better to project a map of Mexico? There are too many to choose from. I have to convert my maps from WGS84 to UTM to do some distance measurements.
Please let me know.
Regards!

A: Mexico (the country, not the city) covers 6 UTM zones: from WGS 84 / UTM zone 11N in the west to WGS 84 / UTM zone 16N in the east. It does not make sense to use one UTM zone for entire country. In this image you can see the UTM zones.
For the state Tamaulipas in the Northeast of Mexico zone 14 fit best.  Therefore these systems (amongst others) can be used in Tamaulipas:

*

*NAD 83 / UTM zone 14N

*WGS 84 / UTM zone 14N

A: The easiest way to tell is to go to the area in Google Earth then go to Tools-->Options --> Show Lat/Long and select "Universal Transverse Mercator" and click apply.
At the bottom just to the left of the coords is the UTM zone, move your mouse to the area you are working on.

A: As @Jens answered, UTM zone 14 North is the best zone for Tamaulipas.
If I remember correctly, Mexico provided information for the original NAD83 definition, but never officially published/converted to NAD83. INEGI did release a Red Geodesica Nacional 1993 datum (also known in the EPSG Geodetic Parameter Registry as Mexican Datum of 1993). The EPSG ID is 4487. EPSG has a null transformation (parameters are zeroes) only for Mexican Datum of 1993 to WGS84.
NAD83 (CSRS) should not be used because, as Jens pointed out, it's for Canada. NAD83 (CSRS) is a re-adjustment of the original NAD83, but for Canada only. Other re-adjustments include several for the US: NAD83 HARN, NAD83 (NSRS2007), and NAD83 (2011).
Even though the PROJ.4 definitions are the same, as Andre Joost said, an incorrect definition will cause confusion in the future, and make it more difficult to convert data to a different coordinate reference system, if necessary.
For
Note: I'm on the subcommittee that maintains the EPSG registry.

A: Here is the link for you to download UTM download should you or anyone who reads here
Enjoy !


text:
Q: two kind of description of model.compile get the different results have already tried
The data pipeline and model build function is right
code
The code is https://gist.github.com/MaoXianXin/cd398521546d967560942e702c243ba7
I want to know why this two kind of description of model.compile get the different results.
see the accuracy
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.01), loss='categorical_crossentropy', metrics=['acc'])
Epoch 1/50
2019-05-27 13:53:20.280605: I tensorflow/stream_executor/dso_loader.cc:153] successfully opened CUDA library libcublas.so.10.0 locally
468/468 [==============================] - 6s 12ms/step - loss: 14.4332 - acc: 0.1045 - val_loss: 14.4601 - val_acc: 0.1029
Epoch 2/50
468/468 [==============================] - 3s 6ms/step - loss: 14.4354 - acc: 0.1044 - val_loss: 14.4763 - val_acc: 0.1023
Epoch 3/50
468/468 [==============================] - 3s 6ms/step - loss: 14.4359 - acc: 0.1044 - val_loss: 14.4714 - val_acc: 0.1026
Epoch 4/50
468/468 [==============================] - 3s 6ms/step - loss: 14.4359 - acc: 0.1044 - val_loss: 14.4682 - val_acc: 0.1028

model.compile('adam', 'categorical_crossentropy', metrics=['acc'])
Epoch 1/50
2019-05-27 13:51:16.122054: I tensorflow/stream_executor/dso_loader.cc:153] successfully opened CUDA library libcublas.so.10.0 locally
468/468 [==============================] - 5s 12ms/step - loss: 3.6567 - acc: 0.7388 - val_loss: 0.0732 - val_acc: 0.9791
Epoch 2/50
468/468 [==============================] - 3s 6ms/step - loss: 0.0812 - acc: 0.9760 - val_loss: 0.0449 - val_acc: 0.9854
Epoch 3/50
468/468 [==============================] - 3s 6ms/step - loss: 0.0533 - acc: 0.9836 - val_loss: 0.0428 - val_acc: 0.9869
Epoch 4/50
468/468 [==============================] - 3s 6ms/step - loss: 0.0426 - acc: 0.9871 - val_loss: 0.0446 - val_acc: 0.9872
Epoch 5/50
468/468 [==============================] - 3s 6ms/step - loss: 0.0376 - acc: 0.9886 - val_loss: 0.0449 - val_acc: 0.9867


text:
Q: Pseudocódigo en c quisiera saber si está correcto lo que hice, estoy aprendiendo pseudocódigo en C y estoy haciendo ejercicios, me ayudaría mucho si pudieran corregir mis errores o darme recomendaciones. En este ejercicio debo sumar los elementos de un arreglo A en n posiciones, mi pseudocódigo es el siguiente:
declaro numeros = 1,2,54,28

longitud = tamañoNumeros / tamañoNumeros[0]

sumatoria = 0

for i = 0; i < tamaño; i++

    numeroActual = numeros[i]
    sumatoria = sumatoria + numeroActual

return(sumatoria)


text:
Q: iOS execute shell script from Activator I am using a jailbroken iOS device, and I want to add an action to Activator that executes a shell script stored in a known location. Does anyone know how to achieve this?

A: I'm not sure whether or not Activator can run scripts directly, but it certainly can run any app you install on your device, with whatever action (e.g. swipe, shake, button press) you like.  Just make a simple app that uses the system() function, or an exec function to invoke your script:
int main(int argc, char *argv[])
{
    int returnCode = system("/bin/myscript.sh arg1 arg2");
    return 0;
}

Then, setup Activator to run that app.
Edit:
That will cause a brief flash as the app starts, and then closes.  This also means that any other app that you're running will be closed (sent to the background). If you don't like that, Activator also lets you build a SBSettings toggle, and then run it on a user-defined action.    See here for building a SBSettings toggle.  You would just implement the setState method this way:
void setState(BOOL Enabled)
{
    int returnCode = system("/bin/myscript.sh arg1 arg2");
}


text:
Q: Determine file creation time in java
Possible Duplicate:
Determine file creation date in Java

I have a file named abc.txt which is created by my application in c:. Now I have to write logic in such way
that if file is created within 1 hour timeframe then I have to print:

file is created within 1 hour itself

and if file is created more than 1 hour before then to print the statement:

It has been more then 1 hour the file is created

How can I achieve this?

A: java.io.File.lastModified() should suit your needs.

A: Below is the code
File f = new File("path of file");
Date now = new Date();
Date filedate = new Date(f.lastModified());
if((now.getTime()-filedate.getTime())>60000){
    System.out.println("It has been more then 1 hour the file is created");
}else{
    System.out.println("file is created within 1 hour itself");
}


text:
Q: How can I exploit the vulnerabalties from my container via my host VM I am using this vulnerable image to learn pentesting:https://hub.docker.com/r/tleemcjr/metasploitable2
I ran the container using this command: docker run --name container-name -it tleemcjr/metasploitable2:latest sh -c "/bin/services.sh && bash"
How can I pentest this container from a remote machine such as SSH to the container etc.


text:
Q: How to ban traffic from a specific zone in Google Cloud Compute instance? I have created a google cloud compute instance. Even though the machine has no active website or services running on it yet, i noticed that in 24 hours the dashboard reported 1GB traffic from China. I dont have any customers outside of Central Zone. How do I ban all traffic from a particular zone, say China? Or conversely, how do I only allow HTTP traffic from Central Zone?

A: Similar question was answered on this thread (https://serverfault.com/questions/22462/relatively-easy-way-to-block-all-traffic-from-a-specific-country) which I believe what you are looking for.


text:
Q: how to get generic type through .class? The problematic code is shown below.
class GenericClass<T> {
    // ...
}

class RegisterHandler<T> {
    // ...
    public void register( Class<T> klazz ) {
        // do something
    }
    // ...
}

class GenericClassRegisterHandler extends RegisterHandler<GenericClass<?>> {
    // ...
}

public static void registerAll() {
    // ...
    new GenericClassRegisterHandler().register( GenericClass.class );
    // error: actual argument Class<GenericClass> cannot be converted to Class<GenericClass<?>> by method invocation conversion
    // ...
}

The only way was to use rawtypes, either by changing register to Class klazz instead of Class<T>, or by casting new GenericClassRegisterHandler() to (RegisterHandler)new GenericClassRegisterHandler(). Since both of these "fixes" exploit rawtypes and I don't want to use them (why should I? I should be able to get Class<GenericClass<?>> somehow by .class!), yet I see no other solution so far. Am I missing something obvious and it's possible without reifying wrappers etc, or is it just impossible?
Note: Wrapping a Class<?> type generics error is a nice & enlightening find, but doesn't work here.
Note 2: While Bloch in EJ 2nd is discussing similar problems, I were unable to find any explicit solution to this exact case.
BTW the obvious (Class<GenericClass<?>>) GenericClass.class doesn't work due to incompatible types: Class<GenericClass<?>> cannot be converted to Class<GenericClass>
Test snippet on http://ideone.com/Fr4yng

A: This task can be solved with small modification:
static class RegisterHandler<T> {
    public <E extends T> void register( Class<E> klazz ) { // <== Note additional generics customization.
        // do something
    }
}

Agree, generics are a bit tricky =)

A: My solution was to do a double cast.
 new GenericClassRegisterHandler()
    .register( (Class<GenericClass<?>>) (Class<?>) GenericClass.class );

While it's arguably not the most elegant one, in some situations (e.g. you're the producer, and the consumer's interface is set in stone, or you just don't want to change it for any other reason) it's the best one - because it's the only one possible.

A: How about
class GenericClassRegisterHandler extends RegisterHandler<GenericClass>?
I know, you said, you did not want to use "raw" types, but GenericClass<?> is no more "raw", than GenericClass for all intents and purposes.


text:
Q: Filter json by value of a key in JSONPath I'm having this json:
{
  "paths": {
      "foo": {
          "key": 1
      },
      "bar": {
          "key": 2
      }
  }
}

I would like to use JSONPath to find element "foo" by its name ("foo")
I tried something like $.paths.*.[?(~=='foo')] but it does not seem to work (I checked on https://jsonpath.com)

A: If you need the to find the element by its name, this expression
$.paths.foo

outputs
[
    {
        "key": 1
    }
]


text:
Q: How to create smooth rounded corners on a popup widget in Qt I've been searching for hours now - without much luck.
I have a widget with the windowsflag Qt::Popup set, and I'm trying to create smooth rounded corners.
I've tried using a stylesheet, but then the transparent part of the corners become black. The same happens if a overwrite the widget's paint event and draw a rectangle with rounded corners in the widget.
I've also tried to set a mask, but the result gets very pixelated.
After some reading I found out that the black corners appears because the widget is a top-level widget. But I would think that it's still possible somehow?
Does anyone know what I can do to either get rid of the black corners or to smoothen the mask? Any ideas are appreciated!
The paint event:
void PopUp::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QColor greyColor(0xFFC5C6C6);
    QRect rect(0, 0, width(), height());
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QBrush(greyColor));
    painter.setPen(QPen(greyColor));
    painter.drawRoundedRect(rect, 10, 10);
}

The function that sets the mask:
void PopUp::setRoundedCorners(int radius)
{
    QRegion verticalRegion(0, radius, width(), height() - 2 * radius);
    QRegion horizontalRegion(radius, 0, width() - 2 * radius, height());
    QRegion circle(0, 0, 2 * radius, 2 * radius, QRegion::Ellipse);

    QRegion region = verticalRegion.united(horizontalRegion);
    region = region.united(circle);
    region = region.united(circle.translated(width() - 2 * radius, 0));
    region = region.united(circle.translated(width() - 2 * radius, height() - 2 * radius));
    region = region.united(circle.translated(0, height() - 2 * radius));

    setMask(region);
}

A: *

*Create a widget with Qt::Window | Qt::FramelessWindowHint and Qt::WA_TranslucentBackground flag

*Create a QFrame inside of a widget

*Set a stylesheel to QFrame, for example:
border: 1px solid red;
border-radius: 20px;
background-color: black;


text:
Q: How to dynamically change the document structure, merge into an array from a scalar value? I have a collection of documents:
{"name":1,"b":3,"c":3}
{"name":1,"b":3,"c":5}
{"name":1,"b":3,"c":6}
{"name":2,"b":6,"c":6}
{"name":2,"b":6,"c":7}
{"name":2,"b":6,"c":3}
{"name":3,"b":2,"c":3}
{"name":4,"b":2,"c":3}

I would like to merge the collection into the following result:
{"name":1,"b":3,"c":[3,5,6]}
{"name":2,"b":6,"c":[6,7,3]}
{"name":3,"b":2,"c":3}
{"name":4,"b":2,"c":3}

Which means eliminating duplicate documents and save their c fields as an array. c would then be an array.
Notes: the first(e.g. "name") and second(e.g"b") fields are unique per document.
while (cursor.hasNext()) {
       DBObject currentObject = cursor.next();
       String currentName = (String)currentObject.get("name");
        if (currentName.equals(previousName) && !previousName.equals(""))
        {
            // what should i write here
            collection.remove(previousObject);
        }
        previousObject = currentObject;
        previousName = (String)previousObject.get("name");
    }

A: You can hold a map of names and DBObjects and push into the value as you progress, something like this:
    Map<String,DBObject> names = new HashMap<String, DBObject>();
    while (cursor.hasNext()) {
        DBObject currentObject = cursor.next();
        String currentName = (String) currentObject.get("name");
        DBObject o = names.get(currentName);
        if (o!=null) { //means you already have it.
            Integer c = (Integer) currentObject.get("c");
            collection.remove(currentObject);
            collection.update(o,new BasicDBObject("$push",new BasicDBObject("c",c)));
        }else {
            names.put(currentName,currentObject);
        }
    }

A: I don't know about MongoDB, but as naimdjon said you'll need some map.
Here is a generic Java solution to your problem:
A class to simulate your input
import java.util.HashSet;
import java.util.Set;

public class SomeDbObject {
    Integer name;
    Integer b;
    Set<Integer> c;

    public SomeDbObject(Integer name, Integer b, Integer c){
        this.name = name;
        this.b = b;
        this.c = new HashSet<>();
        this.c.add(c);
    }

    public String toString(){
        return c.toString();
    }
}

And now a test class with your data set (use name and b as your "keys"):
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Test;

public class SomeDbObjectTest {

    @Test
    public void testProblem(){

        List<SomeDbObject> l = new ArrayList<SomeDbObject>();
        l.add(new SomeDbObject(1,3,3));
        l.add(new SomeDbObject(1,3,5));
        l.add(new SomeDbObject(1,3,6));
        l.add(new SomeDbObject(2,6,6));
        l.add(new SomeDbObject(2,6,7));
        l.add(new SomeDbObject(2,6,3));
        l.add(new SomeDbObject(3,2,3));
        l.add(new SomeDbObject(4,2,3));

        Map<Integer,Map<Integer,SomeDbObject>> m = new HashMap<Integer,Map<Integer,SomeDbObject>>();

        for(SomeDbObject tc : l){
            Map<Integer,SomeDbObject> mTc = m.get(tc.name);

            if(mTc == null){
                mTc = new HashMap<Integer,SomeDbObject>();
                mTc.put(tc.b, tc);
                m.put(tc.name, mTc);
            } else {
                SomeDbObject alreadyExistingRec = mTc.get(tc.b);
                alreadyExistingRec.c.addAll(tc.c);
            }
        }

        System.out.println(m);
    }
}

A: You can do this using the aggregation framework using the below query in shell:
db.foo.aggregate([
{$group:{_id:{name:"$name", b:"$b"}, c:{$addToSet:"$c"}}},
{$project:{_id:0, name:"$_id.name", b:"$_id.b", c:1}}
])

This query can be translated to Java.


text:
Q: Haskell - zipping a list with a list of lists elementwise I have a list l1:
l1 = [1, 2, 3]

and a list of lists l2:
l2 = [[a, b, c], [d, e, f], [g, h, i]]

And I'm trying to zip the first element of l1 with the first list of l2 and second element from l1 with the second list from l2 etc, what I'm looking for is something like this:
l3 = [[(1, a), (1, b), (1, c)], [(2, d), (2, e), (2, f)], [(3, g), (3, h), (3, i)]]

How can I do this? I know it has to be some combination of map and zip. Any Help would be much appreciated.

A: Start by writing a function that pairs one element with a list,
f :: a -> [b] -> [(a, b)]
f x ys = ...

so that f 1 [a, b, c] == [(1, a), (1, b), (1, c)].
You can do this with explicit recursion or by using map.
Then write another function that calls this function for each pair in l1 and l2.
g :: [a] -> [[b]] -> [[(a, b)]]
g xs yss = ... f x ys ...

so that g l1 l2 == l3 according to your definitions of l1, l2 and l3.
You can do this with explicit recursion or by using zipWith.