text:
Q: How to change title name in HTML forcefully I have a project it consist of 30+ 'JS' files and a index file. I have changed the title name of page in the index file but it only shown to me when I reload the page. After the reload complete it show me old title name
Now I am accepting is there any forceful script which always change the title and used as priority in changing the title name or any way by i can find that which particular 'JS' file has been used in changing the title
Explained above

A: You can always use this line document.title = "Some title";, the problem is, you have to know where to put this, cuz it's probable that currently in your project, the title is set by js dynamically and there might be some triggers for that (e.g. on a lifecycle DOMContentLoaded). To tackle that, it's also possible to freeze the title so that it can't be changed anymore after this code is executed, but you can try this:
Object.defineProperty(document, 'title', {
  enumerable: false,
  configurable: false,
  writable: false,
  value: "Some title"
});

though the latter might have some side effects that I have no idea, but hopefully it could satisfy the requirement.


text:
Q: HTML block stored as var javascript I am trying to store a block of HTML in javascript variable like this,
var element =

      leicester

      Opening Times

        Monday:

        9am - 8pm

        Tuesday:

        9am - 8pm

        Wednesday:

        9am - 8pm

        Thursday:

        9am - 8pm

        Friday:

        9am - 8pm

        Saturday:

        9am - 6pm

        Sunday:

        11am - 5pm

        Get directions

        <form onsubmit="GetDirectionsFromInfoBox( this, 0 ); return false;" id="directionsForm-1" method="post" action="" class="directions">
          From
            <input type="text" id="infoboxDir1" value="birstall" class="text">

          <input type="image" class="map-submit" src="css/winter-sale-2010/images/multimap/go-button.gif">
        </form>
        Zoom to this location

However it is throwing js errors saying unecapuslated strings. How can I do this please?

A: You need a backslash at the end for string that span multiple lines and some quotes to encapsulate it overall, like this:
var element = '
 \

 \
  ....';

Also as @T.J. points out if you had any ' in the string (or whichever wrapping quotes you used), be sure to use the escaped form, for example \' here.

A: You could store it inside an ID'ed script tag instead:

First div

Second div

By the way, there's a jQuery plugin using this method: http://api.jquery.com/category/plugins/templates/

A: First of you need to use either ' or " to encapsulate strings literals.
Also, you need to add a \ add the end of each line, otherwise JavaScript won't recognize multi line strings.
Something like this will work:
var element = '
\

\

\
      leicester\
      '

Make sure to escape any ' inside that string, and if you want to have line breaks you need to add a \n in front of the trailing \.

A: Here is a handy tool that I've been using
http://htmltojavascript.com
It automatically creates a list of html tags, keeping
the indentation. I believe this using join is better
compared to concatenation as some members suggested.
I have ran your code on that site and it seems like
it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exporting Account Name, Domain & Timestamp from Security Auditing Event Log I am currently exporting the last 7 days of Security microsoft windows security auditing logs via powershell to csv.
It works, but with way to much detail, and also, not properly formatted. For instance, from the csv, the 'message' cell has this in

"An account was successfully logged on.
Subject:  Security ID:        X   Account Name:       -   Account Domain:     -
    Logon ID:       0x0
Logon Type:           3
Impersonation Level:      Impersonation
New Logon:    Security
  ID:       X   Account
  Name:     XXX Account Domain:     XXX Logon ID:       XXX     Logon
  GUID:     {XXX}
Process Information:  Process ID:     0x0     Process Name:       -
Network Information:  Workstation Name:   -   Source Network
  Address:  XXX.XXX     Source Port:        XXX
  ............

Now to get the above into csv i am using this powershell script
[xml]$CustomView = @"
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">*[System[(EventID=4624 or EventID=4672 or EventID=4648 or EventID=463) and TimeCreated[timediff(@SystemTime) <= 604800000]]] </Select>
  </Query>
</QueryList>
"@

Get-WinEvent -FilterXML $CustomView | Export-CSV "C:\CustomView_$(Get-Date -format "yyyy-MM-DD").csv"

How is it possible to export a csv with the following columns?
Event Id, Security ID, Account Name, Account Domain, Logon ID, Logon, TimeCreated

A: The details from the event message body are stored in the event XML. You can convert the event to XML and then extract each of the XML fields. The thing to keep in mind is that you should only query multiple event IDs when they share a common schema, otherwise the event properties may not be consistent in the output. There is a good write-up explaining the process and event schema issue here.
There is a cmdlet on GitHub called Get-WinEventData that does all the heavy lifting for you. The output contains properties for all the main event fields like machine name, provider name, and message. It also contains properties for all of the XML event data. To use this, simply pipe your Get-WinEvent command into Get-WinEventData, select the properties you want, then export to CSV. Of course you will need to import the Get-WinEventData function beforehand.
Example usage:
Get-WinEvent -FilterHashtable @{LogName="Security";Id=4624,4672;StartTime=(Get-Date).AddDays(-1)} | Get-WinEventData | Select-Object TimeCreated,Id,EventDataSubjectUserSid,EventDataSubjectUserName,EventDataSubjectDomainName,EventDataSubjectLogonId | Export-CSV "Output.csv" -NoTypeInformation


text:
Q: Работа с бинарными файлами в C Работа программы заключается в следующем: в бинарный файл пишется блоками инфа о студентах. При каждой операции добавления проверяется на наличие свободных мест последний считанный из файла блок. Если мест не осталось, то создается новый. Проблема заключается в следующем: при создании блока внутри функции добавления и записи его, в файле наблюдаются многочисленные буквы "М", то есть, как будто созданный блок остался неинициализированным, хотя отладчик говорит об обратном:
Проблема решается, если создать глобальную переменную типа "блок", но, мне кажется, это не лучший выход из данной ситуации. Ниже прилагаю код метода добавления студента в файл:
void AddStudent(Student tempStudent)
{
    filePointer = fopen(FILE_NAME, "rb+");

    if (fileSize == SIZE * BLOCK_SIZE)
    {
        numberOfBlocks++;
    }

    int pastePosition = -1;

    for (int i = 0; i < BLOCK_SIZE;
            i++) //Находим позицию в блоке для добавления студента
    {
        if (buffer.students[i].id == 0)
        {
            pastePosition = i;
            break;
        }
    }

    if (pastePosition !=
            -1)        //Если есть место в блоке, вставляем запись
    {
        buffer.students[pastePosition].id = tempStudent.id;
        strcpy(buffer.students[pastePosition].surname, tempStudent.surname);
        strcpy(buffer.students[pastePosition].name, tempStudent.name);
        strcpy(buffer.students[pastePosition].patronymic,
               tempStudent.patronymic);
        buffer.students[pastePosition].groupNumber = tempStudent.groupNumber;

        for (int i = pastePosition + 1; i < BLOCK_SIZE;
                i++)//Заполняем нулями остальные места в блоке
        {
            buffer.students[i].id = 0;
            strcpy(buffer.students[i].surname, "");
            strcpy(buffer.students[i].name, "");
            strcpy(buffer.students[i].patronymic, "");
            buffer.students[i].groupNumber = 0;
        }

        fseek(filePointer, SIZE * BLOCK_SIZE * numberOfBlocks , SEEK_SET);
        cout << ftell(filePointer);
        system("pause");
        fwrite(&buffer, sizeof(DataBlock), 1, filePointer);
    }
    else
    {
        DataBlock tempBlock;                //Иначе создаём новую
        tempBlock.students[0].id = tempStudent.id;
        strcpy(tempBlock.students[0].surname, tempStudent.surname);
        strcpy(tempBlock.students[0].name, tempStudent.name);
        strcpy(tempBlock.students[0].patronymic, tempStudent.patronymic);
        tempBlock.students[0].groupNumber = tempStudent.groupNumber;

        for (int i = 1; i < BLOCK_SIZE;
                i++) //Заполняем нулями остальные места в блоке
        {
            tempBlock.students[i].id = 0;
            strcpy(tempBlock.students[i].surname, "");
            strcpy(tempBlock.students[i].name, "");
            strcpy(tempBlock.students[i].patronymic, "");
            tempBlock.students[i].groupNumber = 0;
        }

        numberOfBlocks++;
        fseek(filePointer, SIZE * BLOCK_SIZE * numberOfBlocks, SEEK_SET);
        cout << ftell(filePointer);
        system("pause");
        fwrite(&tempBlock, sizeof(DataBlock), 1, filePointer);
    }

    fseek(filePointer, 0, SEEK_END);
    fileSize = ftell(filePointer);
    fclose(filePointer);
}


text:
Q: How to delete row from mysql using php and javascript I am trying to delete the entire row using the php code.
But before that my page has a multiple rows ended with radio button
before clicking delete button we have to select anyone of the radio button, then we can click on delete.
but what i want is, i have written a java-script code that gets the radio button value and after that i want to get that javascript variable value to php code and then execute the delete command..
Here is what i have tried
code
javascript
<script>
function getResults() {
    var radios = document.getElementsByName("address");
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) {
        var a = radios[i].value
            alert(a);
            break;
        }
    }
</script>

php code:
  <?php
      $_GET['a']
      mysql_connect("localhost", "tiger", "tiger") or die (mysql_error ());
      mysql_select_db("theaterdb") or die(mysql_error());
      $strSQL =("DELETE FROM theater WHERE theater_name='"$_POST["a"]"'");
      $rs = mysql_query($strSQL);
      mysql_close();
    ?>
    }

But this is not working
i even tried this also.it is also not working
<?php
    if ($_POST['submit'])
    {
      $_GET['a'];
      mysql_connect("localhost", "tiger", "tiger") or die (mysql_error ());
      mysql_select_db("theaterdb") or die(mysql_error());
      $strSQL =("DELETE FROM theater WHERE address='".$_POST["a"]."'");
      $rs = mysql_query($strSQL);
      mysql_close();
      }
    ?>

A: in js
    <script>
        function getResults() {
            var radios = document.getElementsByName("address");
            for (var i = 0; i < radios.length; i++) {
                if (radios[i].checked) {
                var apost = radios[i].value
                     //send set state request
                $.ajax({
                    type: "POST",// here you can use get/post  if use get then in php use $_GET['a'] or use post then in php $_POST['a']

                    url: "your php file name with path",
                    data: {a:apost},
                    beforeSend: function () {

               },
                    success: function (data, textStatus, XmlHttpRequest) {
if(data==1)// see php file code you will know how i use data==1
{
    // do your action
 }
else{
// in you php there is someyhing error
}
     },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

    // do you action
                   }
                });

                    break;
                }
            }
        </script>

in PHP
   <?php

          mysql_connect("localhost", "tiger", "tiger") or die (mysql_error ());
          mysql_select_db("theaterdb") or die(mysql_error());
          $strSQL =("DELETE FROM theater WHERE theater_name='".$_POST["a"]."'");
          $rs = mysql_query($strSQL);
            echo 1;  // here i use 1 to get response if this is done successfully then in ajax we get 1 in data
          mysql_close();

        ?>

A: You must send the where condition value from js into delete query..
<script>
    function getResults() {
        var radios = document.getElementsByName("address");
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].checked) {
            var a = radios[i].value
                alert(a);
                document.yourformname.action="yourphp.php?a="+a;
                document.yourformname.submit();
                break;
            }
        }
    </script>

A: Hey you need to append php variable as below
 $strSQL =("DELETE FROM theater WHERE theater_name='".$_POST["a"]."'");

A: you have to send the value from html
assigning the javascript variable doesn't added in GET
you have to send the value something like
<script>
function getResults() {
    var radios = document.getElementsByName("address");
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) {
            var a = radios[i].value;
            header.location.href = "yourphp.php/?a=" + a; //changed
            break;
        }
    }
</script>

Php Code
<?php
      $t_name = $_GET['a']
      mysql_connect("localhost", "tiger", "tiger") or die (mysql_error ());
      mysql_select_db("theaterdb") or die(mysql_error());
      $strSQL =("DELETE FROM theater WHERE theater_name='" . $t_name . "'"); //changed Line
      $rs = mysql_query($strSQL);
      mysql_close();
    ?>


text:
Q: Using Handlebars with Node.js/Express, need login and logout to render according to user signing in Hoping someone can help me with this. I am using Handlebars as a template engine with Node/Express blog I am building.  I am trying to get the login and logout buttons rendered according to when the user is logged in or not.
I know I need to use the session somehow but I thought I was using the syntax correctly. I have rendered everything else I was doing but I am stumped on this one.
       {{#if sessionSwitch}}

Logout

        {{else}}

Login

        {{/if}}

Here is the controller where I am sure I need to use the session.
module.exports = async (req, res) => {
const {
    email,
    password
} = req.body;
// try to find the user
await User.findOne({
    email
}, (error, user) => {
    if (user) {
        // compare passwords.
        bcrypt.compare(password, user.password, (error, same) => {
            if (same) {
                // store user session.
                const sessionSwitch = req.session
                sessionSwitch.userId = user._id
                res.redirect('/')
                console.log({ Message: "Success"})
            } else {
                res.redirect('/auth/login')
            }
        })
    } else {
         res.redirect('/auth/login')
    }
})

}


text:
Q: Javascript plot package to move points/lines I am looking for an interactive plot Javascript library for an educational book. I want the user to be able to do things like move a line up or down and see the resulting intersection point or region.
There have been many questions about interactive plots in javascript:

*

*A lightweight javascript library for interactive graph plotting?

*Interactive javascript chart without jQuery and with cursor plotting
None seem interactive in the sense I am looking for AFAIK. (They seem to be interactive in the sense that they show balloon text and can react to simple events like clicking in points.)
Please see here an example of something I want my plot to support.
Does a plotting package that allows this kind of interactiveness exist or should I implement my own? Thanks!

A: How about Flot plus the Flot cursors plugin
This demo seems to look alike the one you made https://rawgit.com/cipix2000/flot-cursors-plugin/master/example.html - just turn of the Dynamic chart data, then you can drag the line
Or maybe make your own flot plugin.


text:
Q: Нужна помощь со вложенным запросом Mysql структура и данные таблицы тут https://pastebin.com/u1GY7gvr
запрос вида
SELECT login, subs_id, ip, login_out
FROM cam.test
WHERE subs_id IN (SELECT subs_id
                  FROM cam.test
                  GROUP BY subs_id
                  HAVING COUNT(id) > 1);

на что получаю
login      |subs_id|ip            |login_out |
-----------|-------|--------------|----------|
baka       |     90|0.0.0.0       |         0|
baka2      |     90|92.24.19.31   |1578325414|
aniko1     |    143|76.18.113.22  |1578325421|
aniko2     |    143|111.195.16.161|1578325422|

Но мне нужно еще перед запросом отсеять те значения login_out, которые
UNIX_TIMESTAMP(NOW()) - login_out) < 30

Тоесть в итоге я должен получить
login      |subs_id|ip            |login_out |
-----------|-------|--------------|----------|
aniko1     |    143|76.18.113.22  |1578325421|
aniko2     |    143|111.195.16.161|1578325422|

A: Ну так и запишите то что вам нужно
SELECT
  login,
  subs_id,
  ip,
  login_out
FROM
  cam.test
WHERE
  subs_id IN (SELECT subs_id FROM cam.test GROUP BY subs_id HAVING COUNT(id) > 1)
  and (UNIX_TIMESTAMP() - login_out) < 30;

Либо, если я неверно понял условие, вариант 2:
SELECT
  login,
  subs_id,
  ip,
  login_out
FROM
  cam.test
WHERE
  subs_id IN (
    SELECT
      subs_id
    FROM
      cam.test
    WHERE
      (UNIX_TIMESTAMP() - login_out) < 30
    GROUP BY subs_id
    HAVING COUNT(id) > 1
  );

A: решение такое:
SELECT login, subs_id, ip, login_out
FROM cam.test
WHERE subs_id IN (SELECT subs_id
                  FROM cam.test
                  where (UNIX_TIMESTAMP() - login_out) < 30
                  GROUP BY subs_id
                  HAVING COUNT(id) > 1
                  )
and login_out > 0;


text:
Q: Receiving Notifications/Indications on Ionic 2 Framework (BLE-Plugin) I't trying to received notifications/indications from a connected BLE-Device from Ionic-Application (on Android).
Reading and writing of Characteristics is working, if I activate notifications they are set on the BLE-Device. It will send data to my application, but I get no data.
If the page is loaded, I check the connection state. If the application is connected, I start notification and write data to the device.
Here is how I activate the notifications.
BLE.startNotification("MAC-Address", "service-UUID", "characteristic-UUID").subscribe(buffer => {
    this.notificationReceived(buffer);
});
BLE.write("MAC-Address", "service-UUID", "characteristic-UUID", start.buffer)
  .then(data => {
      console.log('prepared for download, wait for response');
  }, error => {
    console.error('Failed to initialize Data transfer ' + error);
  });

The notificationReceived is called once, just before BLE.write. The notifications are enabled on the BLE-Device (I have added some debug-outputs on it). In the debug-outputs of the BLE-Device I can see it will send a notification, but in the Ionic-App I receive nothing.
Anybody a hint for me what I could check? I'm new to TypeScript, so this could be anything, I have no Ideas what I could check next.

A: The Problem was:
There was no Problem.
The Notification was received, just before the output of the write response.


text:
Q: add new Element to a specific part of xml tree i need to add a new Element to a specific part of xml tree but i can't make it work.
this is my xml input
    <structMap LABEL="Logical Structure" TYPE="LOGICAL">

</structMap>

and here is my desired output
   <structMap LABEL="Logical Structure" TYPE="LOGICAL">

        <fptr>
          <area BETYPE="IDREF" FILEID="ALTO0011" BEGIN="P11_TB3"/>
        </fptr>

</structMap>

and here is my code
var b = dc.Descendants().Attributes("TYPE").Where(ee => ee.Value == "TITLE").First();

i don't have b.AddFist. how can i make it work?

A: Usse xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement title = doc
               .Descendants("div")
               .Where(x => (string)x.Attribute("TYPE") == "TITLE")
               .FirstOrDefault();

            title.Add(new XElement("fptr", new object[] {
               new XElement("area", new object[] {
                   new XAttribute("BETYPE","IDREF"),
                   new XAttribute("FILEID","ALTO0011"),
                   new XAttribute("BEGIN","P11_TB3")
               })
            }));
        }
    }
}

A: Assuming, of course, that you're using LINQ to XML, it's not surprising that you wouldn't have b.AddFirst(). b is an XAttribute, not an XElement.
It looks like you're looking for b.Parent.AddFirst().


text:
Q: How to write Laravel One to One relationship model and migration With One To One relationship, I'm supposed to have only one phone entry per user.

*

*So, why am I able to add multiple phone numbers ?

*Does it mean that App\User::find(1)->phone only returns the first phone found in the database ?

*Should I add a unique constraint to the user_id column in the phones migration ?

User Model:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

Phone model
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Users table migration:
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Phone migration:
Schema::create('phones', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->string('phone');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

A: 1) So, why am I able to add multiple phone numbers?
**  While adding a phone number to the database, simply search if the current user has a phone number. If yes, then update it. Else, create a new one. Check updateOrCreate
// If there is a user with id 2 then SET the phone to 7897897890.
// If no user with id 2 found, then CREATE one with user_id 2 and phone number to 7897897890
Phone::updateOrCreate(
    ['user_id' => 2],
    ['phone' => '7897897890']
);

2) Does it mean that App\User::find(1)->phone only returns the first phone found in the database?
**  As long as your relation is hasOne, you fetched data will be one where user_id = current user. If you are planning to have one phone number for each user throughout the project then might I suggest to simply add the phone number column to the users table.

3) Should I add a unique constraint to the user_id column in the phones migration?
**   Yes, you can. However, as I suggested in the second point, just have a phone column in the users table (if you want to, otherwise this will work too)

A: Schema::create('phones', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id')->unique();
    $table->string('phone');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

A: You can try this ....
In the User model, define the One-to-One relationship with the Phone model:
User Model
class User extends Model
    {
        public function phone()
        {
            return $this->hasOne(Phone::class);
        }
    }

In the Phone model, define the reverse relationship:
Phone Model
class Phone extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}


text:
Q: Putting combiner to use in mapreduce secondary sorting I have implemented secondary sorting for my application.
File-1                          File-2                    File-3
------                          ------                    ------

name,pos,r,value           name,pos,r,value            name,pos,r,value

   aa,1,0,123                 aa,2,1,1                    aa,3,1,11
   bb,1,0,234                 aa,2,2,34                   aa,3,2,12
                              aa,2,3,55                   aa,3,3,13
                              bb,2,1,99                   bb,3,1,15
                              bb,2,2,54                   bb,3,2,19
                              bb,2,3,32                   bb,3,3,13

For every record in File-1, three records will be available in File2 and File3 each.
composite key is ::name + (pos+r)
natural key is :: name
sorting order is based on the composite key. Ascending order based on (pos+r)
Expected output is
File1 contents of a particular name (aa) followed by all file2 contents (three rows of aa ordered based on pos+r) and then followed by file three contents (three rows of aa ordered based on pos+)
aa,123,1,34,55,11,12,13
bb,234,99,54,32,15,19,13
I have implemenyed this in secondary sorting using setGroupingComparatorClass, setSortComparatorClass and custom partitioner.
My doubts are : ??
1) How to add combiner for this scenario.

*

*According to my understanding, the grouping and sorting happens in the
reducer phase once all the map outputs (which are partitioned based on
natural key)are transferred to reduce machine.

2) If combiner is added, how and when the sorting will happen so that
   the reduce function receives outputs from all mapper in proper order .

*

*Will the map outputs be sorted twice, once in combiner that's executed
 after every map and again on the reducer side to sort all the combiner
 outputs ?

A: Will suggest you to kindly go through
http://bytepadding.com/big-data/map-reduce/understanding-map-reduce-the-missing-guide/

*

*Sorting happens on mapper .

*Merging (sorting and merging) happens on reducer.

*Combiner is a extra layer, Where you try to reduce on Mapper.

*A reducer always receives all given values for a given key.

*Mapper sends the values of a given key in sorted fashion.

Please makeyourself aware about group comparator and Sort comparator and use it appropriately.


text:
Q: How to hide e-mail signature in Thunderbird I'd like to know if there is a way to auto-hide e-mail signatures in Thunderbird (setting or extension). Ideally, it should only show a line with some text like "Click here to display signature".
It's pretty annoying when in an e-mail thread some people write 2-3 lines of content and have 15 line signatures.

A: The 2.8.1 version of the Thunderbird Conversations extension claims to have the ability to collapse signatures by default.

A: You might try the add-on
Element Hiding Helper for Adblock Plus.
It should work as long as the signature is a separate block in the message.
If this is not the case, I don't think there is an easy solution.

Element Hiding Helper is a companion extension for Adblock Plus meant
  to make creating element hiding rules easier.
You simply select the element you want to be hidden and then choose
  which attributes of this element should be taken into account when
  hiding it in future. The element hiding rule is generated and added
  automatically.
This add-on requires the following add-ons to work properly: Adblock
  Plus.


text:
Q: Solve a System of mixed SDE and ODE I have a system of differential equation to solve, but it's a mixed system of ODE and SDE. I'm not sure whether there is any way to solve this kind of system or not. My equations are:
s'[t] == -a s[t] i[t]
di[t] == (a s[t] i[t] - µ i[t] + c (1 - s[t] -i[t]) i[t]) dt + σ dB
i[0]=.5
s[0]=.5

with the parameters a,c,σ,µ greater than 0. Is there any known way to solve this numerically?

A: You want to use RandomFunction and ItoProcess to solve these stochastic differential equations.
a = 1;
μ = 0.1;
c = 1;
σ = 0.1;

sol = RandomFunction[ItoProcess[{
  \[DifferentialD]s[t] == -a s[t] i[t] \[DifferentialD]t,
  \[DifferentialD]i[t] == (a s[t] i[t] - μ i[t] + c (1 - s[t] - i[t]) i[t]) \[DifferentialD]t
  + σ \[DifferentialD]W[t]},
  {s[t], i[t]}, {{s, i}, {0.5, 0.5}}, t, W \[Distributed] WienerProcess[0, 1]],
  {0, 20, 0.01}];

ListLinePlot[sol, PlotRange -> All]


text:
Q: How to create a generic persistent array of ObservableObjects in Swift I have a class that implements an array of ObservableObjects that will save itself to persistent storage whenever one of the objects changes. Here is a very simplified version of the working code:
class MyObject : ObservableObject {
    @Published var name: String = ""
    // Lots of other @Published variables
}

class MyArray {
    @Published var objects: [MyObject] = []
    @Published private var objectWillChange: Void = ()

    private var objectChanged: AnyCancellable?

    init() {
        loadFromStorage()

        for object in objects {
            object.objectWillChange.assign(to: &$objectWillChange)
        }

        objectChanged = $objectWillChange.dropFirst().sink() {
            self.saveToStorage()
        }
    }

    func loadFromStorage() {
        // Loads objects from persistent storage
    }
    func saveToStorage() {
        // Saves objects to persistent storage
    }
}

This all works fine. Now I would like to create a generic version of this code, but I can't get it to compile.
Here is what I have so far
class MyPersistentArray: PersistentArray<MyObject> {
}

class PersistentArray<Object: ObservableObject> {
    @Published var objects: [Object] = []
    @Published private var objectWillChange: Void = ()

    private var objectChanged: AnyCancellable?

    init() {
        loadFromStorage()

        for object in objects {
            object.objectWillChange.assign(to: &$objectWillChange) // DOES NOT COMPILE
        }

        objectChanged = $objectWillChange.dropFirst().sink() {
            self.saveToStorage()
        }
    }

    func loadFromStorage() {
        // Loads objects from persistent storage
    }

    func saveToStorage() {
        // Saves objects to persistent storage
    }
}

In Xcode 14.2, the call to object.objectWillChange gives the following compiler error:

Cannot convert parent type 'Published<Void>' to expected type 'Published<Object.ObjectWillChangePublisher.Output>'

How can I fix this compiler error?

A: I will answer my own question. I figured out that I had to constrain the ObservableObject using a where clause to limit the type of ObjetWillChangePublisher.Output to Void, like this:
protocol PersistentObject: ObservableObject where ObjectWillChangePublisher.Output == Void {
}

class MyObject : PersistentObject {
    @Published var name: String = ""
    // Lots of other @Published variables
}

class MyPersistentArray: PersistentArray<MyObject> {
}

class PersistentArray<Object: PersistentObject> {
    @Published var objects: [Object] = []
    @Published private var objectWillChange: Void = ()

    private var objectChanged: AnyCancellable?

    init() {
        loadFromStorage()

        for object in objects {
            object.objectWillChange.assign(to: &$objectWillChange)
        }

        objectChanged = $objectWillChange.dropFirst().sink() { _ in
            self.saveToStorage()
        }
    }

    func loadFromStorage() {
        // Loads objects from persistent storage
    }

    func saveToStorage() {
        // Saves objects to persistent storage
    }
}


text:
Q: Storing List in System.Web.HttpRuntime.Cache, is it serialized? Trying to find out if the System.Web.HttpRuntime.Cache or any other possible caching is serialized?
Basically i need to store list in Cache, and it has to be Read/Write by many users.
So, I can out a list in cache, i can get it back out.
What happens when many people try to access the list?
Do i have to lock the list? when changing it, I'm guessing I'll have to re-add the list.
Or any other suggestions? Besides using the DB or writing to a file.

A: Came up with a possible solution.
Since my list was going to contain a GUID anyway, I could just use the Cache it self as a list, using the GUID as the Key.
But I am still curious if objects or cache still need to be locked when access them, and re-adding them back to the Cache?


text:
Q: tune2fs: Bad magic number in super-block while trying to open /dev/sda1 I have a healthy file system, but I cannot run tune2fs on it:
# tune2fs -l /dev/sda1
tune2fs 1.42.9 (28-Dec-2013)
tune2fs: Bad magic number in super-block while trying to open /dev/sda1
Couldn't find valid filesystem superblock.

A: tune2fs is for ext file systems, and if this filesystem is healthy, then this filesystem cannot be an ext type filesystem (or it would have a super-block).
To check the type, use blkid.
e.g.
# blkid
/dev/sda1: UUID="6e264bd8-e7df-4003-b145-e65667361d65" TYPE="xfs"

For xfs file systems, instead of tune2fs, use xfs_info.
e.g.
# xfs_info  /dev/sda1
meta-data=/dev/sda1              isize=256    agcount=4, agsize=32000 blks
...


text:
Q: Defining img tag without height and width The w3c specification says that the width and height are implied and not required. I have always been told that you're supposed to put it in anyway. If I remember correctly his reason was that the browser may not correctly detect the image size. Is this true?

A: It harkens back to the dark days of Netscape in the v4 and older versions. The rendering engines were primitive and wouldn't "reflow" content as they built pages and figured out sizes. If you didn't specify an image size, the whole page's rendering would get paused (or a full-page refresh would get pulled) once the image was downloaded and parsed for height/width. This looked bad from a user perspective, so the rule was to ALWAYS specify a size.
Nowadays, engines are better, and can handle an unspecified image size gracefully. Reflowing content is still a somewhat expensive operation, but does look cool from a user perspective as things glide/flow around as images pop in and text shifts to accomodate them.

A: The reason is that if you do not put them in, the browser will put a default size in, download the image, find the actual size then have to re-flow everything around the new size.
Re-flows are expensive operations - the rendering on screen has to be updated for each such image.
If you provide the size, the browser puts in a placeholder with the correct size and doesn't have to re-flow once the image downloads.

A: In my experience, not supplying width and height tags will cause the browser to render the image at its original size.
I've found this behaviour to be consistent in modern browsers.
As an aside, I always try to supply images at the size I want them rendered at in order to reduce the amount of bandwidth used and to ensure image quality.

A: I'm not sure about browsers not detecting it correctly, I've never seen that happen.
But to answer your question, I think the answer depends more on what you are trying to do, and possibly likely to do, which makes the difference.
For example, if the image you are adding is a banner ad which needs to conform to predetermined height/width, then by all means, hard code the height and width.
But if the image is something that might change over time, I would suggest NOT coding the height and width, as more than likely this means that the new image, if not the same exact height/width as the old one, will now be distorted. This is especially true on a dynamic website where images change all the time.


text:
Q: Spring mvc jpa mysql exception:: org.hibernate.hql.internal.ast.QuerySyntaxException: I get exeption
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Guest is not mapped  [SELECT g FROM Guest g ORDER BY g.id]
when i change the datasouce of the Spring Guestbook application from objectdb to local mysql
I am quite green in spring and i believe it a configuration i am missing, just cant find out where.
the summary stacktrace is:
exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Guest is not mapped [SELECT g FROM Guest g ORDER BY g.id]
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Guest is not mapped [SELECT g FROM Guest g ORDER BY g.id]
    org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1750)
    org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
    org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:350)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
    com.sun.proxy.$Proxy383.createQuery(Unknown Source)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    com.sun.proxy.$Proxy379.createQuery(Unknown Source)
    zw.co.rproj.project.dao.GuestDao.getAllGuests(GuestDao.java:25)
    zw.co.rproj.project.dao.GuestDao$$FastClassByCGLIB$$9ec02fdb.invoke(<generated>)
    net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
    org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:617)
    zw.co.rproj.project.dao.GuestDao$$EnhancerByCGLIB$$bb594ff0.getAllGuests(<generated>)
    zw.co.rproj.project.control.GuestController.guestbook(GuestController.java:26)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause

org.hibernate.hql.internal.ast.QuerySyntaxException: Guest is not mapped [SELECT g FROM Guest g ORDER BY g.id]
    org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:96)
    org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
    org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1796)
    org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:342)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
    com.sun.proxy.$Proxy383.createQuery(Unknown Source)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    com.sun.proxy.$Proxy379.createQuery(Unknown Source)
    zw.co.rproj.project.dao.GuestDao.getAllGuests(GuestDao.java:25)
    zw.co.rproj.project.dao.GuestDao$$FastClassByCGLIB$$9ec02fdb.invoke(<generated>)
    net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
    org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:617)
    zw.co.rproj.project.dao.GuestDao$$EnhancerByCGLIB$$bb594ff0.getAllGuests(<generated>)
    zw.co.rproj.project.control.GuestController.guestbook(GuestController.java:26)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause

org.hibernate.hql.internal.ast.QuerySyntaxException: Guest is not mapped
    org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
    org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)
    org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:95)
    org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:331)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3633)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3522)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
    org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1796)
    org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:342)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
    com.sun.proxy.$Proxy383.createQuery(Unknown Source)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    com.sun.proxy.$Proxy379.createQuery(Unknown Source)
    zw.co.rproj.project.dao.GuestDao.getAllGuests(GuestDao.java:25)
    zw.co.rproj.project.dao.GuestDao$$FastClassByCGLIB$$9ec02fdb.invoke(<generated>)
    net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
    org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:617)
    zw.co.rproj.project.dao.GuestDao$$EnhancerByCGLIB$$bb594ff0.getAllGuests(<generated>)
    zw.co.rproj.project.control.GuestController.guestbook(GuestController.java:26)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

persistance unit
<persistence-unit name="InvPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/proj_inventory?zeroDateTimeBehavior=convertToNull"/>
      <property name="javax.persistence.jdbc.user" value="kms"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.password" value="?pass3"/>
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  </persistence-unit>

and the spring-servlet.xml
<context:component-scan base-package="zw.co.rproj.project"/>

  <!-- Use @Controller annotations for MVC controller definitions -->
  <mvc:annotation-driven />

  <!-- Add JPA support -->
  <bean id="emf" class=
       "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
     <property name="loadTimeWeaver">
        <bean class=
 "org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
      </property>
  </bean>

  <!-- Add Transaction support -->
  <bean id="myTxManager"
     class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf"/>
  </bean>

  <!-- Use @Transaction annotations for managing transactions -->
  <tx:annotation-driven transaction-manager="myTxManager" />

  <!-- View resolver -->
 <bean class=
     "org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="prefix" value="/WEB-INF/jsp/"/>
 </bean>

</beans>

the pom.xml
<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>zw.co.rproj.project</groupId>
    <artifactId>springInventory</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>springInventory</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>objectdb</id>
            <name>ObjectDB Repository</name>
            <url>http://m2.objectdb.com</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.objectdb</groupId>
            <artifactId>objectdb</artifactId>
            <version>2.6.2_02</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.10</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <finalName>springInventory</finalName>
    </build>

</project>

guest.java
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "guest")
public class Guest implements Serializable {
    private static final long serialVersionUID = 1L;

    // Persistent Fields:
    @Id @GeneratedValue
    Long id;
    private String name;
    private Date signingDate;

    // Constructors:
    public Guest() {
    }

    public Guest(String name) {
        this.name = name;
        this.signingDate = new Date(System.currentTimeMillis());
    }

    // String Representation:
    @Override
    public String toString() {
        return name + " (signed on " + signingDate + ")";
    }
}


text:
Q: Error in Openquery Stored Procedure To keep this as simple as possible I have just copied the line of code causing an error. I'm trying to run a openquery in a stored procedure and keep getting the following error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '*'.

I'm pretty sure it is to do with where I have quotations but I really need a second pair of eyes as I have tried all sorts of combinations:
SET @SQL_ResultID = 'SELECT * FROM OPENQUERY([23-SQL3000], ''SELECT ResultID FROM [Portfolio].[dbo].[Program] P INNER JOIN [Portfolio].[dbo].[Results] A ON P.ProgramID = A.ProgramID WHERE ProgramName = ''''' + @P + ''''' AND ResultsName = ''''' + @A + ''''''')';

Thanks in advance


text:
Q: $_GET function in php not working correctly im using this URL:
http://domain.co.uk/iphone/index.php?c=knnKVLO4ROKPvvtxUCDu&bhsirf=Q8IP6OKRtaOCjcCgpb94&9froifhew3=ux9XI0vjKfzieTVS6rTt&40289njgw=We80L1RXDPIQj4ENL3QM&AdjoirtGERG^%%C2%A3fd=ozS60iysc1Vd9QgVDZIP&jorw4958fq%C2%A3$=2kbCk7EXRNMZlYMhDdkhVm2E3j4sNDtmo8ho2Ag6&ffjg^GDDFGn2FFGHe=8fuTCaTzKbf1VYQPcornK8LOK4ERPT43XoegnvTByli9c1rIInTwvwvShxkN&a@@^%45383fhreFGGew=48bFy4U6bBYcMqLHnVfK2kbCk7EXRNMZlYMhDdkh&fGHDFb.fewfrgopewFRWGREG=gbBYKubAEk7DcpQ69M7ZkxVGa2aSWiYlrEXOUqDINYsKnnMhf0hHqhQGdMUS9M3Zy74em2NIrubulwS5XcPmgHytg8we8f1y9aR2&gfiegrowu895743fdGTRY%C2%A3QT%C2%A3%yewhfuigw9545TRWTRYEgsgfnfht34o=vXBuTfXODHxQsHJZH9MQx4TrFZ38eaEmm5eowcKVgeH69YYGWofJQI0Y4jE9GDhFrHdFhMc2Tqtlb4LwWEO47z5IrEp42QppEYMlLzx4yIFlxpNZ3g4gU384DqYPNo9c3Ks2RGGNEVaMhJNewC6g48WHeEhP6r5tfOpI5OyCsNiukHXfoAqVxtaggqt6xkce74hP4f22

and then this in my PHP:
<?php
if($_GET["c"] == 'knnKVLO4ROKPvvtxUCDu' and $_GET["bhsirf"] == 'Q8IP6OKRtaOCjcCgpb94' and $_GET["9froifhew3"] == 'ux9XI0vjKfzieTVS6rTt' and $_GET["40289njgw"] == 'We80L1RXDPIQj4ENL3QM' and $_GET["AdjoirtGERG^%£fd"] == 'ozS60iysc1Vd9QgVDZIP' and $_GET["jorw4958fq£$"] == '2kbCk7EXRNMZlYMhDdkhVm2E3j4sNDtmo8ho2Ag6' and $_GET["ffjg^GDDFGn2FFGHe"] == '8fuTCaTzKbf1VYQPcornK8LOK4ERPT43XoegnvTByli9c1rIInTwvwvShxkN' and $_GET["a@@^%45383fhreFGGew"] == '48bFy4U6bBYcMqLHnVfK2kbCk7EXRNMZlYMhDdkh' and $_GET["fGHDFb.fewfrgopewFRWGREG"] == 'gbBYKubAEk7DcpQ69M7ZkxVGa2aSWiYlrEXOUqDINYsKnnMhf0hHqhQGdMUS9M3Zy74em2NIrubulwS5XcPmgHytg8we8f1y9aR2' and $_GET["gfiegrowu895743fdGTRY£QT£%yewhfuigw9545TRWTRYEgsgfnfht34o"] == 'vXBuTfXODHxQsHJZH9MQx4TrFZ38eaEmm5eowcKVgeH69YYGWofJQI0Y4jE9GDhFrHdFhMc2Tqtlb4LwWEO47z5IrEp42QppEYMlLzx4yIFlxpNZ3g4gU384DqYPNo9c3Ks2RGGNEVaMhJNewC6g48WHeEhP6r5tfOpI5OyCsNiukHXfoAqVxtaggqt6xkce74hP4f22')
{
    //fine
}
else
{
    header("Location: /iphone/error.php");
}
?>

but its redirecting to error.php page even though everything is correct. are my strings too long or is there something else wrong?
heres the var_dump for $_GET:
errorarray(10) { ["index_php?c"]=> string(20) "knnKVLO4ROKPvvtxUCDu" ["bhsirf"]=> string(20) "Q8IP6OKRtaOCjcCgpb94" ["9froifhew3"]=> string(20) "ux9XI0vjKfzieTVS6rTt" ["40289njgw"]=> string(20) "We80L1RXDPIQj4ENL3QM" ["AdjoirtGERG^%£fd"]=> string(20) "ozS60iysc1Vd9QgVDZIP" ["jorw4958fq£$"]=> string(40) "2kbCk7EXRNMZlYMhDdkhVm2E3j4sNDtmo8ho2Ag6" ["ffjg^GDDFGn2FFGHe"]=> string(60) "8fuTCaTzKbf1VYQPcornK8LOK4ERPT43XoegnvTByli9c1rIInTwvwvShxkN" ["a@@^E383fhreFGGew"]=> string(40) "48bFy4U6bBYcMqLHnVfK2kbCk7EXRNMZlYMhDdkh" ["fGHDFb_fewfrgopewFRWGREG"]=> string(100) "gbBYKubAEk7DcpQ69M7ZkxVGa2aSWiYlrEXOUqDINYsKnnMhf0hHqhQGdMUS9M3Zy74em2NIrubulwS5XcPmgHytg8we8f1y9aR2" ["gfiegrowu895743fdGTRY£QT£%yewhfuigw9545TRWTRYEgsgfnfht34o"]=> string(200) "vXBuTfXODHxQsHJZH9MQx4TrFZ38eaEmm5eowcKVgeH69YYGWofJQI0Y4jE9GDhFrHdFhMc2Tqtlb4LwWEO47z5IrEp42QppEYMlLzx4yIFlxpNZ3g4gU384DqYPNo9c3Ks2RGGNEVaMhJNewC6g48WHeEhP6r5tfOpI5OyCsNiukHXfoAqVxtaggqt6xkce74hP4f22" }

A: Found one error:
You use the following key which does not exist in the array:
$_GET["fGHDFb.fewfrgopewFRWGREG"]

This one exists though:
$_GET["fGHDFb_fewfrgopewFRWGREG"]

(See Amirs answer for explanation).
Also, $_GET["c"] is not a valid key. Somehow, maybe because of a rewrite rule (as suggested by Michael Berkowski in comments to your question), it is changed to $_GET["index_php?c"].
With that said, your solution does not seem optimal, because you risk running into problems like these... What are you exactly trying to accomplish?

A:
Dots and spaces in variable names are converted to underscores. For
example <input name="a.b" /> becomes $_GET["a_b"] refer here

A: It is possible that the issue has to do with operator precedence and and && are not equal.
I would try replacing and with &&.

A: The first and the second codes your posted seems to be OK for me but for some reason you are redirected to the error page.
The user "Frederik Wordenskjold" stated a difference of keys you might want to see if it is OK.
My suggestion to solve this problem or at least get a clue of where it is would be to print every $_GET you receive in that file (comment the "if-else" statement just to test this) so you can realise if the problem is in the file you are looking or in what you receive through $_GET


text:
Q: Make UITextField Placeholder private in didSet I am subclassing a UITextField to build a textfield in which a user can enter a certain amount of money in a certain currency. I want the placeholder to be get only or be private. Instead you set the currency and the amount you want the placeholder to be. Then the textfield automatically adapts the string, e.g. to a certain number of decimals etc.
The code below stops at:
    placeholder = oldValue
This makes sense because it keeps calling the setter and ends in an infinite loop. I can not find a better way to do this, anybody knows how I could make this work?
Thanks
var placeholderAmount: Float = 0{
    didSet{
        self.placeholder = String(self.roundedStringWithAmount(placeholderAmount, to: self.numberOfDecimalPlaces)) + self.currencyString

    }
}

override var placeholder: String?{
    didSet{
        placeholder = oldValue
        print("Placeholder Set to CurrencyTextField. Do not do that")
    }
}

A: You cannot restrict the access level of a variable declared in a super class.  It's a bit hacky, but you could just set a flag that allows to not loop infinitely:
var ignoreUpdates = false

override var placeholder: String?{
    didSet{
        if !ignoreUpdates {
            ignoreUpdates = true
            placeholder = oldValue
            ignoreUpdates = false
            print("Placeholder Set to CurrencyTextField. Do not do that")
        }
    }
}

A: This should work and be a little less hacky.
override var placeholder: String?{
    didSet{
        if placeholder != oldValue {
            placeholder = oldValue
            print("Placeholder Set to CurrencyTextField. Do not do that")
        }
    }
}


text:
Q: Calculating wealth values from richness in QGIS I have 6 species distribution maps. These species are modelled under certain climatic conditions. As a result, I have 6 raster maps. I would like to obtain a map that shows the richness of these 6 species on the same map.
I believe this can be done by converting raster maps to presence or absence maps. Then add the maps and then obtain the wealth value of each species at each point. I would like to reflect that on a map with a wealth scale of 0 to 6.

A: I may suggest a couple of workflow according to your QGIS version.
Personally I prefer Greater than frequency tool, which keeps me from reclassifying each of the input distribution maps.

Classic approach (prior to QGIS 3.16)
This is the workflow what you have described.

*

*Reclassify your distribution map (continuous values) into binary ([0 or 1]) raster. Several tools are available, such as Reclassify by table.

*Add the maps using Raster Calculator.

QGIS 3.16
There is Greater than frequency tool in the QGIS Processing Toolbox > Raster Analysis.
This tool outputs the frequency (number of times) the values of an input stack of rasters are greater than the value of a value raster. (I wish we could provide the threshold value as a constant, but it has to be a raster).

*

*Create a constant raster by Create constant raster layer tool (in Processing Toolbox > Raster creation). In your case, the constant value needs to be Zero.

*Start Greater than frequency and select the constant raster (all zero) as Input value raster. Also select all your 6 distribution maps in the Input raster layers.


text:
Q: Selected or not... word automatically deleting space after sentence Once again I have a problem of understanding the behavior of Word. What I want to do is to replace text in big word documents. Most of the VBA code is working precisely as expected… are parts are not (or at least not in my brain…).
Consider a word document with these three sentences:
This is the first sentence. This is the second sentence. This is the third sentence.
When I select the second sentence, from the capital letter T (This) to the end of the sentence including the space after the dot, and run this code
Sub SelectAndReplace()

    Dim myRange As Range
    Dim myText As String

    Set myRange = Selection.Range
    myText = "This is the sentence in the middle."

    myRange.Delete
    myRange.text = myText

End Sub

Then I get no space between the second and third sentence (middle.This). This is logical in my mind. But I get exactly the same result if I select the second sentence without the space at the end. Word seems to decide for me that the space at the end should also be deleted. But I do not want this to happen.
When researching this I get a lot of information about the smart selecting of word. I have been tinkering with these settings but is does not have an effect when running the code. This actually makes me happy because I do not want the code to run differently on separate computers depending on these settings. A lot of other people actually are looking for solutions to get rid of extra spaces (which is making my search difficult)
Can anyone point me in the right direction?
Just adding an extra space at the end of my replacement text is not going to help. Sometimes the selection/range will be in the middle of a word (and then I do not want an extra space).
Thanks

A: Thanks to Timothy
Sub SelectAndReplace()

    Dim myRange As Range
    Dim myText As String
    Dim beginStatusPasteAdjustWordSpacing As Boolean

    beginPasteAdjustWordSpacing = Options.PasteAdjustWordSpacing 'store status
    Set myRange = Selection.Range
    myText = "This is the sentence in the middle."

    Options.PasteAdjustWordSpacing = False
    myRange.Delete
    myRange.text = myText
    Options.PasteAdjustWordSpacing = beginPasteAdjustWordSpacing 'set back original status

End Sub


text:
Q: It says Incorrect syntax near ',' when I try to insert an item into my database? Code :
Private m_cn As New SqlConnection
Private m_DA As SqlDataAdapter
Private m_CB As SqlCommandBuilder
Private m_DataTable As New DataTable
Private m_intRowPosition As Integer = 0

Private Sub InsertDatabaseItem_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    m_cn.ConnectionString = "Data Source=My-PC\SQLSERVEREXPRESS;Initial Catalog=ConvienienceProducts;Integrated Security=True"

    m_cn.Open()
    m_DA = New SqlDataAdapter("Select * From ProductIndex", m_cn)
    m_CB = New SqlCommandBuilder(m_DA)
End Sub

Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
    Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES(" &
                              txtID.Text & "," &
                              txtName.Text & "," &
                              txtPrice.Text & "," &
                              txtDesc.Text & ")"), m_cn)

    cmd.ExecuteNonQuery()

    MsgBox("Success....", MsgBoxStyle.Information, "SUCCESS")

    Me.Hide()

    txtID.Clear()
    txtName.Clear()
    txtPrice.Clear()
    txtDesc.Clear()

    m_cn.Close()
    m_cn.Dispose()
End Sub

Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
    Me.Hide()
End Sub

This is the error message :

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near ','.

A: You code should be using parameters.  Try this:
Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES(" &
                          "@ID," &
                          "@Name," &
                          "@Price," &
                          "@Desc)"), m_cn)

cmd.Parameters.Add("@ID", SqlDbType.Char)
cmd.Parameters("@ID").Value = txtID.Text
cmd.Parameters.Add("@Name", SqlDbType.Char)
cmd.Parameters("@Name").Value = txtName.Text
cmd.Parameters.Add("@Price",  SqlDbType.Char)
cmd.Parameters("@Price").Value = txtPrice.Text
cmd.Parameters.Add("@Desc",  SqlDbType.Char)
cmd.Parameters("@Desc").Value = txtDesc.Text

The types are probably wrong (especially Price, and probably ID), but as you know what they are, and I don't, you can easily correct them.

A: You need to wrap your string values in single quotes
Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES('" & txtID.Text & "',

Hard to see but there is a single quote just before and after the double quotes surrounding your variables.
I have answered your particular question but you should be using parameters


text:
Q: tracing connection-url of data source with JPA How to print/show the url-connection to the database from a Java code?
It's a Java EE 6 classic application with persistence.xml (JNDI entry to Jboss 7 or WAS 8 datasource, JPA/hibernate)


text:
Q: What are the security implications of HTML5 local storage for credit card info Storing credit card info in web servers under my company's control creates severe security risk. It is an incentive to break in. It forces us to guard acces to our our database with great care. It is a legal liability.
Obviously this would only really be useful to users who are on the same browser from one session to another, so there is a UX hit.
Would it be a security improvement to put this info in HTML5 local storage?

A: POSSIBLY
By storing the credit card details on an individual's machine, you reduce the chance that a successful hack of a single server (or 'system') leads to the credit details of many (hundreds/thousands of) users being compromised. An ideal solution would entail a similar (or lower) risk as storing things on the server, but distribute the attack surface and hence massively reduce the impact.
Here is the summary of a suggested approach (which I've posed fully as a SO question HERE, with no 'poo-poos' as of yet):

*

*Retrieve an encryption key from the server over HTTPS.

*Use it (in javascript) to encrypt the credit card details in local storage at the same time as they are being entered by the user.

*Throw the key away when the user navigates away from the page.

*If the user returns later, they can retrieve the same key from the server, as well as a new key with which to cache the details going forward (to avoid the same key being used again and again).

*The server doesn't have to keep a copy of the credit card details, and a hacker would need to gain a level of access such that they could anyway see the details being entered on the page by the user.

A: No.
Because then anyone could come to the computer and get the unencrypted credit card information. Local storage is not encrypted on the computer. Storing it encrypted on a secured server is a better option (even with the legal issues).
But the best option is to not store it at all. That reduces the legal and financial issues for everyone. If people are upset with the user experience, explain to them that not storing their credit card number is for their protection.


text:
Q: How tomcat is running my project in Eclipse? I know how to configure tomcat to run my Dynamic web project created in eclipse.
Can any body please explain me the step by step process which tomcat does to run my web project?

A: I could see a detail clarification regarding this in following links;
Where does Eclipse deploy web applications using WTP?
http://oreilly.com/pub/a/java/archive/tomcat.html?page=1
http://www.mulesoft.com/tomcat-deploy


text:
Q: What does `uicache` command do on jailbreak iphone? I use the command Whenever I install a jailbreak app and the app's icon doesn't show up.  What are some of the command's other use cases? What's the mechanism behind the command?

A: SpringBoard (the "home screen" application) keeps a cache of all app icons. When installing or removing apps from the App Store, installd performs those changes and updates that cache to reflect them. When installing apps by other means (such as through Cydia), installd is not involved in any way, so for the app to show up properly on the home screen, the cache has to be updated "manually" somehow.
That is exactly what uicache was designed to do. How exactly it achieves that varies between iOS version, but it's mostly a combination of removing the cache files, killing/reloading the services dealing with them and iterating over the installed applications to build a new cache.
You can check its source code on saurik's git repo.


text:
Q: Mute and UnMute in Objective-C on iOS Hi guys ive been trying to find a way to mute and unmute (that is play audio) via Objective-C in-code, regardless of whether the app is in mute mode or not (physical mute toggled)
I see Instagram does that, where you can press the mute icon even if your phone is mute, and it will play video audio.

A: You want to look at audio session categories
With this code you can play audio when the Ring/Silent switch to silent.
NSError *setCategoryError = nil;
BOOL success = [[AVAudioSession sharedInstance]
            setCategory: AVAudioSessionCategoryPlayback
                  error: &setCategoryError];

if (!success) { /* handle the error in setCategoryError */ }


text:
Q: Could NOT find pocketsphinx (missing: pocketsphinx_DIR) I am trying to setup gaitech_edu ROS package in order to build a turtlebot line follower. But, when I am trying to compile the package using catkin_make, I am getting following error:

I installed pocketsphinx library for python 2.7 using
pip install pocketsphinx.
But, even after that I am getting the same error. I am using ros melodic and python version is 2. Your help/advice will be highly appreciated. Thank you in advance.

A: I am able to solve this problem using this ros package for pocketsphinx.


text:
Q: Designing db for multiple forms of a single type What is the best approach to design DB tables for an type which has multiple forms.
For example Animal which can be any animal with its specific properties.
a table for animal with common columns and individual tables for the each type. But how to maintain the foreign key references in the main animal table? We can not keep one key for each type has if the types grow the references will also grow. And for one row  only one type exists and all other keys in the animal table will be null.
Is there any best way to design the tables other than this way?
For example consider the below tables
Furniture table:
Id    FurnituretypeId NoofLegs ChairId    TableId
-------------------------------------------------
int   int             int       int        int

Chair Table:
Id    Name        CansSwing   CanDetachable
-------------------------------------------------
int   Varchar(25) boolean      boolean

Cot Table:
Id    Name        CotType      Storage   StorageType
-------------------------------------------------
int   Varchar(35) Varchar(25)  boolean   Varchar(25)

Considering the above example if i have to insert the a chair then TableId in Furniture table will be null. If there are multiple types of furniture then i have to add those type ids as foreign keys in Furniture table but at a time only one type i can add.

A: Just an idea, in case of having multiple properties, would be to create an animal table with all the common stuff, and an animal property table with columns animal(FK),property,value. This, of course, is an un-pivoted solution, which might or might not suit you.


text:
Q: How to test files that use browserify-shim global's in Jest? I'm downloading the google maps API v3 via a script tag, and I'm adding the dependency to my modules with the following (relevant) package.json configuration:
"browserify-shim": {
   "google": "global:google"
}

And I can add the dependency in my files with the following:
var google = require('google');

When I run my code in the browser, it works fine.
The problem is, when I run my tests with Jest, it tells me that it can't find the 'google' module:
Error: /src/app/assets/javascripts/__tests__/helpers-test.js: Cannot find module 'google' from '/src/app/assets/javascripts/__tests__'

Note:
This dependency is being required in the file that I'm testing, not the test itself. I find this confusing since I thought that Jest mocks all dependencies unless it is specified otherwise, but from what I can see, it first needs to correctly satisfy the dependencies before mocking.
Any ideas of what am I missing or what approach should I take?

A: You'll need to alias 'google' properly in your package.json, see here.


text:
Q: Why HttpURLConnection stops its execution? I want to ping url with this AsyncTask
@SuppressLint("StaticFieldLeak")
    private inner class ActivationAsyncTask : AsyncTask<Void, Void, Int>() {

        override fun doInBackground(vararg params: Void?): Int? {
            HttpURLConnection.setFollowRedirects(false)
            val activationUrl = ActivationManager.shared.getActivationUrl()
            val httpURLConnection = (URL(activationUrl).openConnection() as HttpURLConnection)
            httpURLConnection.requestMethod = "HEAD"
            var result = 520
            result = try {
                httpURLConnection.responseCode // trouble is here
            } catch (e: IOException) {
                520
            } catch (e: UnknownHostException) {
                520
            }
            Log.d("Tag", "This log never shows up")
            return result
        }

        override fun onPostExecute(result: Int?) {
            super.onPostExecute(result)
            val response = when (result) {
                200     -> MainHttpStatus.OK
                401     -> MainHttpStatus.Unauthorized
                else    -> MainHttpStatus.Unknown
            }
            listener.completion(response)
        }
    }

But when I try to get .responseCode the task does not continue as if execution froze forever. What's wrong?

A: You have to call httpURLConnection.connect() method before reading the response code.


text:
Q: Why when I make a new instance of text view outside of a method the program compiles but crashes? Inside one of my java files I have to use this new instance of a TextView in two separate methods, so rather than creating the new instances of the TextView in both methods I thought I would just declare it outside of the methods although still inside the class.
I didn't receive any errors before compiling however when I tried to get to the activity this class is concerned with the app crashes. I fixed this by putting the declaration in both separate methods and the app stopped crashing I was just wondering why and would there be a more eloquent way of doing it as I'm trying to stick to the DRY principle.
Here's the line of code:
final TextView tv_scoreDisplay = (TextView) findViewById(R.id.tv_scoreDisplay);

Logcat:

10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime: FATAL EXCEPTION: main
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime: Process: com.example.aaron.dartpro, PID: 9474
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.aaron.dartpro/com.example.aaron.dartpro.FiveZeroOne}: java.lang.NullPointerException
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:135)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5001)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:  Caused by: java.lang.NullPointerException
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.Activity.findViewById(Activity.java:1884)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at com.example.aaron.dartpro.FiveZeroOne.(FiveZeroOne.java:26)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at java.lang.Class.newInstanceImpl(Native Method)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at java.lang.Class.newInstance(Class.java:1208)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:135)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5001)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
  10-21 16:05:18.150 9474-9474/com.example.aaron.dartpro E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

A: It was crashing because you need to call findViewByID after setContentView() method si called, if tv_scoreDisplay is a field variable, you cannot declare it final.

A: You can declare the TextView as a member attribute of your activity but you need to initialize it in the onCreateView and you need to first inflate your layout with setContentView(R.layout.your_layout) for instance.
public class YourActivity{
   private TextView tv_scoreDisplay;

   public void onCreate(){
      setContentView(R.layout.your_layout);
      tv_scoreDisplay = (TextView) findViewById(R.id.tv_scoreDisplay);
   }
}

A: findViewById(R.id.tv_scoreDisplay);  could be the issue.
You load an activity and then call setContentView() this loads the view now all the R.id will be available from the loaded xml any call prior to setContentView() referring to R.id will crash the app. Also see if that id exists in the same xml you loaded ? These happens during runtime because during compilation syntax etc.. are checked but the allocation is determined only during runtime... there arises situation when we want to get the height of view and it will return 0 this happens because the view is not yet painted on the screen so all these things and factors occur during runtime...
thanks

A: My guess is you're getting a null reference error at run time, which probably means you're not getting the view reference at the correct time and storing globally. You want to make sure you view isn't null, which can be ensured by grabbing the view @ onCreate() AFTER setting the content view So..
public myActivity extends Activity{
  View myView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_layout);
    myView = (View)findViewById(R.id.myview);
  }

  public void fnc1(){//myView is accessible from here
  }
  public void fnc2(){//and from here
  }
 }


text:
Q: C++ class that mandates const objects First let me ask a general question:

*

*It seems to me that C++ is a language whose point is to provide tons of capabilities, to give the programmer the greatest possible flexibility in doing things in whatever way he finds suitable. In other words, it's a flexible language that allows the programmer to express himself in more ways than probably any other language that I've seen. Is this right?

Then a specific one:

*

*Why doesn't C++ seem to support creating classes whose objects can be only const? In other words, classes where you get a compile-time error if you try to create a non-const object of it. This seems like a natural thing to do in many cases, yet C++ doesn't allow it.
What is the reason behind this? (Sure, I can make all the members const, but that is somewhat of a copout.)

A: Your first paragraph details how C++ is flexible and allows you to express many different programs.
Your second paragraph asks why C++ doesn't allow a programmer to enforce a highly stringent limitation that is of questionable benefit (when you can simply mark all the members const to achieve almost the same result).
Let us each draw our own conclusions from this dichotomy. :)

A:
Why doesn't C++ seem to support creating classes whose objects can be only const? In other words, classes where you get a compile-time error if you try to create a non-const object of it. This seems like a natural thing to do in many cases, yet C++ doesn't allow it. What is the reason behind this?

The first question that comes to mind is when having a type for which all objects are const is a natural thing. There are types that are naturally immutable, in some languages it's even recommended to make as many types as possible immutable, but that is not the same thing as enforcing that all objects are const.
In your class design it is trivial to control whether any of your member functions modifies the state of the object achieving an immutable object. Encapsulation will then do its magic, and if you don't expose any mutating function, then the type is immutable and as good as const. You can also (if you want the extra safety) qualify all your member data as const to let the compiler tell you if you violate your own constraint in your own code. Note that forcing all the objects to be const implicitly would mark all your member data to be const, and your non-const functions useless.
Given that the high level effect can be achieved in different ways with little cost, why would you make a complex language even more complicated for no added value?
While the question above may seem rhetoric it is not. One of the criteria to consider extensions to the language is the return on investment: What will we be able to do with this feature that was not possible without it? (i.e. is this an enabling feature?) If the answer is nothing, then the next question is How much simpler will programmer's life be with this feature compared to the current state? (for non-enabling features, what is the value of adding them?)
In the enabling category the example would be rvalue-references; without that language feature, you cannot implement perfect-forwarding, nor move-semantics. In the second category you can consider lambdas — there is nothing that can be done with lambdas that was not doable without them — whose value lies on simplifying user code (code that would have to be convoluted: create a functor, declare all members of the proper types, provide a constructor that initializes — does the capture — the members…) but the code becomes much simpler with lambdas. Note that it took quite a bit of arguing from Sutter to convince Stroustrup that lambdas had value.
In your case, what you are asking for is not an enabling feature, and the cost of supporting the use cases without the feature is low enough that it does not grant providing that as a core language feature.

A: The crux of the C++ language's design is that it provides abstraction at very little (often zero) cost. Using classes is no more expensive than providing a struct and related functions in C, but the compiler can enforce restrictions on your code such that the semantic benefits of classes are realised. This is just as true for templates, references, lambdas, copy/move semantics, strings, I/O, etc. You don't pay for what you don't use and, when you do use something, you pay very little.
Another important design principle of C++ is that it doesn't provide language features that can't just be easily built from other language features or that don't provide a useful form of abstraction for the author. Each language feature is a building block that can be used to make a fully expressive program. This aids flexibility. If the language were to provide the feature you're looking for, it would be reducing that flexibility. If you want the state of your object to be const regardless of how the client wants to use it, you need to make every member of your object const - the members are your object's state. C++ doesn't want to give you absolutely everything; it just gives you the necessary tools to write fully expressive code with minimal cost.

A: Just create your instance of the class as const. This will ensure all the internals are const.
E.g. const MY_TYPE obj;

A: I have been in this situation a few times.
That is,
I designed a class that due to unacceptable performance requirements, it was basically immutable.
Immutable in the sense that its instance can defined at construction and never modified.
In effect, all its member function were const.
(Well, there is a side question as it is whether it can be assignable still, but let's go on).
It would be nice to be able to force the use to declare the instances const to make the intent more evident.
I don't think C++ supports this without adding a level of indirection, that is to access the object through a const pointer and disabling direct construction. (Or even better a unique_ptr).
struct A{ // this class is immutable, so in princple `A a` and `A const a` should behave the same
    int f() const{return 5;}
    private:
    A(){}
    public:
    template<class... Args>
    static A const* make_const(Args&&... args){return new A(std::forward<Args>(args)...);}
};

int main(){
    std::unique_ptr<A const> a(A::make_const());
    std::cout << a->f() << std::endl;
}

Note that the following doesn't compile, as intended:
A a; // doesn't compile because the constructors are private

nor does
std::unique<A> a(A::make_const()); // make creates pointers to const, so this doesn't compile.

Only the following compiles, and effectively you are mandating const:
std::unique_ptr<A const> a(A::make());

One can make it better by using std::indirect http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0201r1.pdf and in the future overloading operator. will also help.
Of course a much cheaper alternative is to give the name of the class have const in the name like struct A_const{... or struct cA{... to hint that only const makes sense.
(Perhaps, If you decide to have mutating members later, you can inherit from this, struct A : A_const{...).


text:
Q: Rails - methods that are working but don't seem to be defined anywhere? I'm trying to make some changes to our conference registration platform.  It calls a couple of methods that don't appear to be defined anywhere.  I'm pretty sure they are the methods I need to edit to make the necessary changes.  What am I missing?  Where should I be looking for them?
In conferences_controller.rb, two methods (that I've noticed so far) are called in spite of not having any apparent definitions.
On lines 82-83:
# get the current step
@step = current_registration_step(@this_conference, current_user)

On lines 96-97:
# set up the next step
result = registration_step(@step, @this_conference, current_user)

I can't find method definitions for either of these.  I threw some file writes in for debugging and confirmed that current_registration_step() and registration_step() are returning plausible values.  I just can't figure out where they're getting them.
There's a definition for registration_steps() in conferences_controller.rb.  There are definitions for registration_steps() and current_registration_steps() in registration_helper.rb.  I've read about some pluralization stuff in Rails so I put file writes in these and even tried commenting a couple of them out with no effect.  It looks like they aren't being called.
Incidentally, "include RegistrationControllerHelper" appears on line 6 of conferences_controller.rb, but I can't find RegistrationControllerHelper defined anywhere in the project.  This seems like it might be relevant?
So... got any idea where registration_step() and current_registration_step() are defined?
Note: I have no background with Ruby or Rails; the person who developed this platform has very little availability right now.  I'm the only volunteer on hand with much coding experience, and these changes would make for a big improvement when we open registration for the upcoming conference.

A: You can use source_location to find these methods, assuming they have been defined the normal way, directly in some Ruby source file:
puts method(:registration_step).source_location


text:
Q: Treeview in angular ui-grid I am trying to get a tree view working in angular ui-grid.  However I always get the error that the template for the treeViewRowHeader cannot be found.
In the example there is no such template and no call is made to the server for this template.
Anyone know where/how i should specify this template?
BTW: Using RC21

A: Sorry, stupid mistake in using the wrong css file for angular grid.


text:
Q: Run Matlab Coder Output Project on Visual Studio or g++ I wanted to convert my simulation code in Matlab to C++ and run it with a C++ compiler such as Visual Studio or g++. I modified my code to successfully build a C++ project using Matlab Coder.
The coder returns a .prj file in the top project directory, and tens or hundreds of c++ source/header/object files in the dll directory. I tried to open the .prj files with Visual Studio 2012 or 2013 (I tried with both versions) that was unsuccessful and they cannot even open a .prj file.
I have made sure to configure the Visual Studio as the C++ language compiler in Matlab using mex -setup.
Does anyone have any idea how to handle the .prj and the subsequent files with Visual Studio or g++? I don't want to make it executable at the moment; I just want to run it with either compilers and make sure it's working.
Thanks

A: The prj file that is generated is used for the MATLAB Coder GUI, rather than Visual Studio. If you double-click that file in MATLAB, the Coder GUI will open and you can generate code using it.
For a simple example of using the generated code in Visual Studio you can refer to the documentation.
If you are going to use the generated code on the same platform on which you are running MATLAB, I would recommend changing the output type to a static library (LIB) or a shared library (DLL). Doing so will cause the C or C++ code to be generated and then compiled into a library using the compiler that you specified. Then you can write code that calls the functions declared in the generated header file(s) and link in the generated library when compiling your hand-written code.
For Visual Studio, you'll need to add the codegen directory, codegen/lib/<proj_name> to the include path and add the generated LIB/DLL file as a dependency. With GCC, you'll need to add the same directory to the include path when compiling your code and link in the library.
The second half of my other answer has more information in it.
Alternatively, if you have a C main function written, you can set the output type to EXE and specify the main function to have MATLAB Coder generate code, compile it with your provided main and compile a standalone executable.

A:
Does anyone have any idea how to handle the .prj

you supposed to run "mcc" on .prj file, I believe
Quote
"Specify that mcc use settings contained in the specified project file. Use
-F project_name.prj
to specify project_name as the project file name when calling mcc. This option enables the .prj file, along with all of its associated settings, to be fed back to mcc. Project files created using either mcc or deploytool are eligible to use this option. When using -F, no other arguments may be invoked against mcc."