text:
Q: Mysql, How to group a set of rows by using the max value of another column? I have a table that might have one or more rows with the same value for the key_property column.
I want to build a query in MySql that returns a set where every value of key_property is represented for only one of its corresponding rows and that it also receives a key_property filter for a like sentence, chosen by the max value of another column (say, event_id).
How can I achieve that?
UPDATE:
Here's a sample of the non-filtered table:
+--------------+--------+----------+
| key_property | others | event_id |
+--------------+--------+----------+
|    abcd      | B      |     1    |
|    abcd      | A      |     2    |
|    defg      | C      |     3    |
|    abcd      | D      |     4    |
|    hijk      | f      |     4    |
+--------------+--------+----------+

When executing the query with the filter setted as 'd', the result data should look like this:
+--------------+--------+----------+
| key_property | others | event_id |
+--------------+--------+----------+
|    abcd      | D      |     4    |
|    defg      | C      |     3    |
+--------------+--------+----------+

A: SELECT *
FROM tab WHERE (key_property,event_id) IN
( SELECT key_property, MAX(event_id)
  FROM tab
  WHERE key_property like '%d%'
  GROUP BY key_property
)


text:
Q: Sequence of rational numbers converging to any irrational number I attempting to solve the following question: "Show there is a sequence of rational numbers converging to any irrational number".
I don't understand how to tackle this problem because it says any irrational number.
I know for example that the sequence $s_n$ = $(1 + 1/n)^n$ converges to $e$, but I can't think of a sequence that will converge to any rational number.
As a caveat I have looked at other similar questions on stack exchange but none seem to cover this any aspect.
Thank you.

A: The space of real numbers $R$ is the metric completion of $Q$ the space of rational numbers. To construct $R$, start with $Q$, and let $C$ be the space of  Cauchy sequences of $Q$. Two elements $(x_n)$ and $(y_n)$ are equivalent if and only if $(x_n-y_n)$ converges towards $0$, then $R$ is the quotient space for this equivalence relation. You can identify $Q$ with the equivalence classes of constant sequences.
If $[x_n]$ is the class of the Cauchy sequence $(x_n)$, define $(y_n^i)$ by $y^i_l=x_i$ for every $l$. Then $([y^i_n])$ converges towards $[x_n]$ and $[y_n^i]$ can be identified with the rational $x_i$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to unlock Windows-hibernated disk? I'm trying to fix a Windows installation that won't boot, but I think part of the problem fixing it is that it was hibernated, and thus is still sort of locked to access.
Is there a way to unlock it? Any caveats to it?

A: You can use a Linux live disk that allows hard drive access and delete the file called hiberfil.sys on the main system disk.
The main downside is that this is the equivalent to forcefully shutting down the machine, anything open will be unsaved, and possibility of breaking things that were in the process of being updated.
As for unlocking it, I really need to know more - how far you get and what the specific errors are.

A: Some suggestions here.
Most of the time this is file system corruption that can be fixed by doing a:
chkdsk /r C:

from the recovery environment command prompt.
If chkdsk fails to get it booting do a "FixBoot" as described in this article.
If it is a OEM PC, Dell, HP ect, do not use the FixMBR command.


text:
Q: Java start multiple threads in a class I am consuming from a certain source (say Kafka) and periodically dumping the collected messages (to, say, S3). My class definition is as follows:
public class ConsumeAndDump {
   private List<String> messages;

   public ConsumeAndDump(){
      messages = new ArrayList<>();
      // initialize required resources
   }

   public void consume(){
      // this runs continuously and keeps consuming from the source.
      while(true){
         final String message = ...// consume from Kafka
         messages.add(message);
      }
   }

   public void dump(){
      while(true){
         final String allMessages = String.join("\n", messages);
         messages.clear(); // shown here simply, but i am synchronising this to avoid race conditions
         // dump to destination (file, or S3, or whatever)
         TimeUnit.SECONDS.sleep(60); // sleep for a minute
      }
   }

   public void run() {
      // This is where I don't know how to proceed.
      // How do I start consume() and dump() as separate threads?
      // Is it even possible in Java?

      // start consume() as thread
      // start dump() as thread
      // wait for those to finish
   }
}

I want to have two threads - consume and dump. consume should run continuously whereas dump wakes up periodically, dumps the messages, clears the buffer and then goes back to sleep again.
I am having trouble starting consume() and dump() as threads. Honestly, I don't know how to do that. Can we even run member methods as threads? Or do I have to make separate Runnable classes for consume and dump? If so, how would I share messages between those?

A: First of all, you can't really use ArrayList for this. ArrayList is not thread-safe. Check out BlockingQueue for example. You will have to deal with things like back pressure. Don't use an unbounded queue.
Starting a thread is pretty simple, you can use lambdas for it.

public void run() {
   new Thread(this::consume).start();
   new Thread(this::produce).start();
}

Should work, but gives you little to no control over when those processes should end.


text:
Q: AngularJS templates render locally, but not in Heroku I'm building an app with AngularJS & Rails 4, and am using Heroku to host the site.
I placed several templates under an assets/templates folder as haml files.
I created a haml initializer with Rails.application.assets.register_engine '.haml', Tilt::HamlTemplate and added the following line to my application.rb:
config.assets.paths << Rails.root.join('app', 'assets', 'templates')

I did this based on other threads on stackOverflow.
This works great locally, but when trying to access the site after pushing to heroku it can't seem to locate the templates in the assets/templates directory. I am referencing my template URL as templateUrl: ./assets/cityOverview.html
Specifically, my Heroku logs shows:

2014-02-10T05:17:25.042728+00:00 app[web.1]: ActionController::RoutingError (No route matches [GET] "/assets/cityWelcome.html"):

What am I missing? should I move my templates to views?

A: Your HTML templates on production may be appended with a hash! For instance, on development the file path will be /assets/cityOverview.html but on production the Rails asset pipeline will add a hash like this: /assets/cityOverview-41ac8fc9a65390498a34680a9uc53951.html
This means you can't specify the template name in your JS file as "/assets/cityOverview.html". You can rename your js file to .js.erb and then write "<%=asset_path '/assets/cityOverview.html'%>". This ensures that the filename will have the hash as well.

A: *

*I see that you join haml middleware to your application, but instead of using .haml templates you use .html templates

*Use absolute pathes (SITE_PATH:port/assets/TEMPLATE_NAME)


text:
Q: modifying tables in my database I have database with a table called members, which stores data for my admin,client,technicians all in one.But now I want to break this table into three separate tables as admin table,client table and techs table.As I have now written queries based on the members table I want to keep the common fields which were used in queries in the members table as they are now.Therefore I reduced the members table only to have fields ID,Name,UserName,Password,Level,Category.Throughout the site it is recognized if the user is a admin,client,or technician by setting levels(which corresponds to Level field).
When inserting data I tried using this code.First insert the common fields to members and then depending on the level write separate queries specifying to which table should data be inserted.
if($_POST['Submit']){
        if(mysql_fetch_array(mysql_query("SELECT * FROM `members` WHERE UN='$r[UN]' AND ID!='$r[ID]' "))) {
             ?><script language="javascript" type="text/javascript">alert('Username already exsits.Please enter another.');
             </script>
             <?php
             }
        else {
            mysql_query("INSERT INTO members (Name,UN,Password,Level,Category) VALUES ('$r[Name]','$r[UN]','$r[PW]','$r[Level]','$r[Category]')");
            $row=mysql_query("SELECT * FROM members WHERE Name='$r[Name]'") or die('query unsuccesful');

             if ($row['Level']==1){
                 mysql_query("INSERT INTO client(Name,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
                 }
            elseif($row['Level']==2){
                mysql_query("INSERT INTO techs (Name,,Category,Company,Price,Comments,Rate,Qualifications,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Category]','$r[Company]','$r[Price]','$r[Comments]','$r[Rate]','$r[Qualifications]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
                }
            else{
            mysql_query("INSERT INTO admin (Name,Mobile,Phone,Fax,Email,Address) VALUES ('$r[Name]','$r[Mobile]','$r[Phone]','$r[Fax]','$r[Email]','$r[Address]')");
            }
            if(!$user){
                 $user=$r;
                 $_SESSION['user']=$r;
                  }

But data gets inserted only to members table and nothing goes for client,techs or admin.Any idea how I can mend this please

A: You are not fetching data on the 2nd select.
$row=mysql_query("SELECT * FROM members WHERE Name='$r[Name]'") or die('query unsuccesful');
if(mysql_fetch_array($row)) {... }


text:
Q: Problema conexión SQL Me ha sucedido que repentinamente perdí el acceso al programa de contabilidad Contpaq, que requiere conexión a SQL en servidor, recientemente se actualizo el windows 10 y se perdió la conexión con las terminales, se modifico el usuario de windows y se restauro como estaba, ahora la contraseña le fue modificada y acudo a ustedes para saber alguna solución que me sea de ayuda.
Intente cambiar contraseña por CMD:

y agregar un nuevo usuario:

Pero no funcionó.

A: *

*Busca en el menú inicio dentro del grupo de programas del SQL Server
que tengas instalado el programa SQL Server Configuration
Manager

*En el panel de la izquierda selecciona Configuración de Red de SQL
Server XXXX

*En el panel de la derecha haz doble click en Protocolos de -
instancia de SQL Server que quieras modificar-"

*Ahora, en el panel de la derecha comprueba que TCP/IP está
habilitado. En caso contrario botón derecho encima de TCP/IP y
selecciona Habilitar

En el panel de la izquierda, deberías tener Configuración de SQL Native Client (32 bits) y otro sin lo de 32 bits (es el de 64 bits en caso que tengas un SQL Server de 64 bits).
En cada uno de ellos, tienes que tener una sección de Protocolos de Cliente, dentro de la cual deberías tener el TCP/IP habilitado también, y si pinchas dos veces en TCP/IP en la ventana que te saldrá deberías tener el puerto 1433 (o el que desees) indicado en Puerto Predeterminado
Esto que te he puesto es para el SQL Server 2005.
En los más modernos todo se hace desde Configuración de Red de SQL Server XXXX
En caso que tengas múltiples IPs en el servidor te saldrá una pestaña en la ventana de propiedades donde para cada IP puedes establecer una configuración diferente. Para poner en todas las IPs la misma configuración tienes que ponerlo en la sección IPAll.
En los SQL Server más modernos también hay un campo nuevo llamado Puertos Dinámicos TCP que deberías de dejar vacío o a 0.


text:
Q: FabricJS text color is object I am trying to load the text color in a color picker. However, when I do get("fill") on the activeobject I loaded from JSON, it gives me an object. Here is the offending JSON line:
"fill":{"ok":true,"format":"hex6","_tc_id":258,"alpha":1}

How am I supposed to turn that into a color and not an object Object?
Adding jsfiddle:
http://jsfiddle.net/Qb4Xe/5/
Just click on the text!

A: You are right, the problem is that you are restoring the canvans by loading a json that contains a wrong value for the fill property, explicitly:
 "fill":{"ok":true,"format":"hex6","_tc_id":258,"alpha":1}

probably this object is coming  from the serialization of a TinyColor
Unfortunately this can not be interpreted correctly by fabricjs and can not be converted back into a hex color (see the sources of TinyColor if you need to delve this point )
I create this fiddle to shows how it is possible to reproduce a similar mistake; suppose we have a TinyColor
var t = tinycolor("#ff0000");

We make a mistake if we use this TinyColor object as the value of the fill property ( i.e. fill: t ), for example:
canvas.add(new fabric.Rect({ width: 50, height: 50, fill: t, top: 100, left: 100 }));

by serializing the canvas we get a JSON that contains:
"fill":{"ok":true,"format":"hex","_tc_id":0,"alpha":1},

but this can not work and the actual fill is visualized as black ( the default ) instead of our color ( red ).
The  correct approach is to use fill: t.toHexString():
canvas.add(new fabric.Rect({ width: 50, height: 50, fill: t.toHexString(),  top: 150, left: 150 }))

this works fine ( the rectangle is red ) moreover by serializing the canvas we get a JSON that contains:
"fill":"#ff0000"

therefore this will work fine even when you will restore the canvans from JSON.
EDIT
Ultimately suggest is to fix the problem at the origini, but if you have to deal with a buggy json string also is possible to intercept the problem this way:
if (typeof hex == "object" && hex.hasOwnProperty("_tc_id")) {
   alert("no color available; return a default such as fill:'none'");
}

like in this fork the fiddle post in the question


text:
Q: How to Create a Folder in the Current Document Library if it's not already present? I modified the code. I can now upload to current document library (not more hardcoding the document library or the acutal url). All i need to do now is to make sure folder exists or not. create folder if it does not exists in the current document library. I will continue to update the code if I came across the solution.
Thanks
public override void ItemAdded(SPItemEventProperties properties)
{
    base.ItemAdded(properties);

    using (SPSite currentSite = new SPSite(properties.WebUrl))
    using (SPWeb currentWeb = currentSite.OpenWeb())

    {   SPListItem oItem = properties.ListItem;
        string doclibname = "Not a doclib";

        //Gets the name of the document library
        SPList doclibList = oItem.ParentList;

        if (null != doclibList)
        {
            doclibname = doclibList.Title;
        }
        // this section also not working.
        // getting Object reference not set to an instance of an object or something like that.
        //if (currentWeb.GetFolder("uHippo").Exists == false)
        //{

            SPListItem folder = doclibList.Folders.Add(doclibList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "uHippo");
            folder.Update();
        //}

    }
}

A: Assuming that "doclibList" is the Document Library which you want to create the folder in, you could just iterate through the folders in there and check if you find the necessary name. Put the following after your check for the if the doclibList is not null.
bool foundFolder = false; //Assume it isn't there by default
if (doclibList.Folders.Count > 0) //If the folder list is empty, then the folder definitely doesn't exist.
{
  foreach (SPListItem fItem in doclibList.Folders)
  {
    if (fItem.Title.Equals("uHippo"))
    {
      foundFolder = true; //Folder does exist, break loop.
      break;
    }
  }
}
if (foundFolder == false)
{
  SPListItem folder = doclibList.Folders.Add(doclibList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "uHippo");
  folder.Update();
}


text:
Q: When to use mutable objects? There are tons of articles and blog posts over the internet telling that mutable objects are bad and that we shouldn't use them and therefore we shall make all our objects immutable.
I have nothing against this except that the topic has gone so far that some people might be "tricked" into thinking that mutable objects shall never be used at all.
When do we have to resort to use mutable objects? What are the common kinds of problems that are unsolvable without using mutable state?

A: As to your fear, it's common. Every concept gets taken by some as to mean that nothing else shall ever be done, for any reason.
These are the people who try to make requirements fit their ideology, rather than the other way around (a.k.a. they're not pragmatic).
When to use mutables? Basically when you feel like it, when you think it makes sense.
Prime example is in low memory and high performance situations where creating a new instance that's identical except for one little thing from the old one is too expensive in either memory and/or CPU cycles.


text:
Q: issues having an additional admin login Currently I have a login which is based for a user however I would like to include code for an additional login for a admin. How would I go about implementing this without having two seperate logins?
if(isset($_POST['login'])) {

$username = $_POST['username'];

$password = $_POST['password'];

if(DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
        if(password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username)) [0]['password'])) {
            echo 'Logged in: ';
            header('Location: index.php');

                $cstrong = True;
                $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
                //echo $token;
                $user_id = DB::query('SELECT id FROM users WHERE username=:username',array(':username'=>$username))[0]['id'];
                DB::query('INSERT INTO login_tokens VALUES(\'\', :token, :user_id)', array(':token'=>sha1($token),'user_id'=>$user_id));

                setcookie("PLACEME", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
                setcookie("PLACEME_", $token, time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);

        } else {
            echo 'Incorrect password';
        }
} else {
    echo 'user not registered';
}

}

?>

<!DOCTYPE html>

    <title>Student login</title>
    <link rel="stylesheet" type="text/css" href="style.css">

        <form action="login.php" method="post">

                <input type="text" name="username" value="" placeholder="Username">

                    <input type="password" name="password" value="" placeholder="Password">

                    <input type="submit" name="login" value="Login">

        </form>

Register here if not a member

A: You could have all user types inside the same database, make sure the usernames are set to be unique and have a column called user_type or something like that. Check login regularly but make an additional step to check for user type, if an account of that type logs in, redirect or show the admin stuff. For all admin pages you should just check if your logged user is an admin.
or you can echo a script tag like so
 if($admin)
     echo '';

A: The obvious way to do this is to just add a column in your table that holds the access level of each user.
If you want a quick and dirty way, and assuming all your usernames are unique - you can simply test which user has logged in within your PHP and set a variable:

This is here as an example, however I would strongly advise utilising your tables properly and recording access level in your database

if(DB::query('SELECT username FROM users WHERE username=:username',
array(':username'=>$username))) {
        if(password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username)) [0]['password'])) {
            echo 'Logged in: ';
            header('Location: index.php');

                $cstrong = True;
                $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
                //echo $token;
                $user_id = DB::query('SELECT id FROM users WHERE username=:username',array(':username'=>$username))[0]['id'];
                DB::query('INSERT INTO login_tokens VALUES(\'\', :token, :user_id)', array(':token'=>sha1($token),'user_id'=>$user_id));

                setcookie("PLACEME", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
                setcookie("PLACEME_", $token, time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);

                // Set flag to determine if user is admin AFTER successful login
                $isAdmin = ($username == 'foo' || $username == 'bar');

        } else {
            echo 'Incorrect password';
        }
} else {
    echo 'user not registered';
}


text:
Q: Custom admin form save blank date as 0000-00-00 00:00:00 I have built a grid and admin form for editing a custom table with two date fields: "date_start" and "date_end"
It is saving correctly and if I enter a date it will save the date as I enter it. however if I do not enter a date it will instead save the date as if it was the current date. I need it to save an empty date as either blank or 0000-00-00 00:00:00 as this is later used in a method where a blank or empty date means we are not filtering by date.
The functionality could be replicated by adding two booleans for each date that say if you are filtering by that date but I find that is not the preferred method to do this.
I am assuming it would have to be in the controllers save action in the following section
$postData = $this->_filterDates($postData, array('date_start', 'date_end'));

// date code goes here

$shiprate_model->addData($postData);

But I am not sure what method would be needed.
The only other place I could think of is the table structure but they already have a default set
`date_end` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',

Solution
$date_start_null = false;
$date_end_null = false;

if(!$postData['date_start']) $date_start_null = true;
if(!$postData['date_end']) $date_end_null = true;

$postData = $this->_filterDates($postData, array('date_start', 'date_end'));

if($date_start_null) $postData['date_start'] = '0000-00-00 00:00:00';
if($date_end_null) $postData['date_end'] = '0000-00-00 00:00:00';

Was able to get it working using a mixture of the solutions bellow, thanks for the help

A: Try something like the following ... I am assuming the above is from your entity controller's saveAction(). So, if the field has also a html name="date_end", you could do a simple check and force-assign the values you need, if the field(s) are empty:
if(empty($postData['date_start'])) $postData['date_start'] = '0000-00-00 00:00:00';
if(empty($postData['date_end'])) $postData['date_end'] = '0000-00-00 00:00:00';

$postData = $this->_filterDates($postData, array('date_start', 'date_end'));

A: I'd implement the _beforeSave() function of your Model implementation.
public function _beforeSave() {
    if(!$this->getDateEnd()) {
        $this->setDateEnd("0000-00-00 00:00:00");
    }
    return parent::_beforeSave();
}


text:
Q: Is there a way to tell if a Corda node goes down? I have an application connected to a Corda node using CordaRPC. If I stop the Corda node, I can't see a good way to detect that from my app. Eventually, if I try to call an RPC function, I get an error. Is there any low-level way to detect a lost connection?

A: As of Corda 3.1, no. There is no exposed API to detect a lost connection.


text:
Q: C++ Copy Constructor Results in Memory Error so the code, basically an AList with multiple functions,  I have below currently runs fine and my passes all assertions and test cases that are assigned to my assignment, however, I lose .5 points because of a memory error. I believe the error lies somewhere in my copy constructor, but I am currently struggling to know where is the issue.
This is how my code looks along with my copy constructor.
#ifndef __ALIST_H__
#define __ALIST_H__

// size should not be negative
typedef unsigned long size_t;

#define RFACTOR 2 // use factor 2

namespace ds {

template <typename ItemType> class TestDriver; // for autograding; please ignore

/** Array-based list. */
template <typename ItemType> class AList {
  friend class TestDriver<ItemType>; // for autograding; please ignore

private:
  /** The underlying array. */
  ItemType *items;

  /** Stores the current size of the list. */
  size_t count;

  /** Max number of items allowed. */
  size_t maxCnt;

  /** Resize the underlying array to the target capacity. */
  void resize(size_t capacity) {
    maxCnt = capacity;
    ItemType *a = new ItemType[maxCnt];
    for (size_t i = 0; i < count; i++) {
      a[i] = items[i];
    }
    delete[] items;
    items = a;
  }

public:
  /**
   * Construct a new AList object.
   *
   * @param initSize initial size of the underlying array; default 100
   */
  AList(size_t initSize = 100) {
    count = 0;
    maxCnt = initSize;
    items = new ItemType[maxCnt];
  }

  /** Destroy the AList object. */
  ~AList() { delete[] items; }

  /** Return the number of elements in list. */
  size_t size() const { return count; }

  /** Return the i-th item in list .*/
  ItemType &get(int i) const { return items[i]; }

  /** Append `x` to the end of list. */
  void addLast(ItemType x) {
    if (count == maxCnt) {
      resize(count * RFACTOR);
    }
    items[count] = x;
    count += 1;
  }

  /** Return the last item in list. */
  ItemType &getLast() const { return items[count - 1]; }

  /** Delete and return the last item. */
  ItemType removeLast() {
    ItemType returnItem = getLast();
    count -= 1;
    return returnItem;
  }

  AList(const AList<ItemType> &other);
  void addFirst(ItemType x);
  ItemType &getFirst() const;
  ItemType removeFirst();
};

/** Copy constructor. */
template <typename ItemType>
AList<ItemType>::AList(const AList<ItemType> &other) {
  // TODO: create a list that is identical to `other`

  count = other.count;
  maxCnt = other.maxCnt;

  ItemType arr[maxCnt];
  items = new ItemType[maxCnt];

  for(size_t i = 0; i < count; i++)
  {
    items[i] = arr[i];
  }

  delete [] items;
  items = other.items;

}

/** Insert x at the front of list. */
template <typename ItemType> void AList<ItemType>::addFirst(ItemType x) {
  // TODO:

  if(count == maxCnt)
  {
   resize(count * RFACTOR);
  }

  for(size_t i = count; i > 0; i--)
  {
    items[i] = items[i - 1];
  }

  items[0] = x;
  count = count + 1;

}

/** Return the first element in list. */
template <typename ItemType> ItemType &AList<ItemType>::getFirst() const {
  // TODO:

  return items[0];
}

/** Delete and return the first element in list. */
template <typename ItemType> ItemType AList<ItemType>::removeFirst() {
  // TODO:

  ItemType temp = items[0];

  for(size_t i = 0; i < count - 1; i++)
  {
    items[i] = items[i + 1];
  }

  count = count - 1;
  return temp;

}

} // namespace ds

#endif // __ALIST_H__

When I run my code, this is what the memory error states:
Output: 'original list: [1]; copy & getFirst: 1; resulting list: [1]'
217Expected: 'original list: [1]; copy & getFirst: 1; resulting list: [1]'
218Error(s):
219==190== Invalid free() / delete / delete[] / realloc()
220==190== at 0x483D74F: operator delete[](void*) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
221==190== by 0x10979A: ds::AList<int>::~AList() (AList.h:51)
222==190== by 0x10962E: main (test_driver.cpp:55)
223==190== Address 0x4da3cc0 is 0 bytes inside a block of size 4 free'd
224==190== at 0x483D74F: operator delete[](void*) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
225==190== by 0x10979A: ds::AList<int>::~AList() (AList.h:51)
226==190== by 0x109608: main (test_driver.cpp:96)
227==190== Block was alloc'd at
228==190== at 0x483C583: operator new[](unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
229==190== by 0x109761: ds::AList<int>::AList(unsigned long) (AList.h:47)
230==190== by 0x10939F: main (test_driver.cpp:55)
231==190==

main program:
#define CATCH_CONFIG_MAIN
#include "AList.h"
#include "catch.hpp"
#include <cstdlib>

#define SIZE 5

TEST_CASE("All") {
  ds::AList<int> L;

  // randomly add SIZE ints to the array
  int nums[SIZE];
  srand(time(0)); // setting the seed for rand()
  for (int i = 0; i < SIZE; i++) {
    nums[i] = rand() % 20 + 1; // generating random numbers by rand()
    L.addLast(nums[i]);
  }

  SECTION("copy constructor") {
    ds::AList<int> *K = new ds::AList<int>(L);
    CHECK(L.size() == K->size());
    CHECK(K->getLast() == nums[SIZE - 1]);
    delete K; // this should not also delete L
  }

  SECTION("addFirst") {
    L.addFirst(123);
    L.addFirst(234);
    CHECK(L.getFirst() == 234);
    CHECK(L.get(2) == nums[0]);
  }

  SECTION("removeFirst") {
    int x = L.removeFirst();
    CHECK(x == nums[0]);
    CHECK(L.getLast() == nums[SIZE - 1]);
  }
}

If anyone could give any tips or suggestions on how I can fix this, it would be greatly appreciated!


text:
Q: How to increase and fit ImageView in CardView I'm using some TextView and CardView in Recycle with android property: android:orientation="vertical", when I change layout_width and layout_height of ImageView, it doesn't change size of ImageView.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardElevation="3dp"
    card_view:contentPadding="3dp"
    card_view:cardCornerRadius="3dp"
    card_view:cardMaxElevation="3dp"
    card_view:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <com.android.volley.toolbox.NetworkImageView
            android:id="@+id/VollyNetworkImageView1"
            android:layout_width="250dp"
            android:layout_height="100dp"
            android:src="@mipmap/ic_launcher"
            android:gravity="top" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:id="@+id/textView_item"
            android:text="Image View"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"/>

      </LinearLayout>

</android.support.v7.widget.CardView>

I have tried a lot of ways but I have not got it yet, I wish it same with file photo attachment

How to fix the problem ? Thank so much !

A: I think you just need to add the android:scaleType attribute to your ImageView.

A: Use
android:scaleType="centerCrop"

This will scale your image to fit the size of your ImageView


text:
Q: If $\arcsin x+\arcsin y+\arcsin z=\pi$,then prove that $(x,y,z>0)x\sqrt{1-x^2}+y\sqrt{1-y^2}+z\sqrt{1-z^2}=2xyz$ If $\arcsin x+\arcsin y+\arcsin z=\pi$,then prove that $(x,y,z>0)$
$x\sqrt{1-x^2}+y\sqrt{1-y^2}+z\sqrt{1-z^2}=2xyz$

$\arcsin x+\arcsin y+\arcsin z=\pi$,
$\arcsin x+\arcsin y=\pi-\arcsin z$
$\arcsin(x\sqrt{1-y^2}+y\sqrt{1-x^2})=\pi-\arcsin z$
$x\sqrt{1-y^2}+y\sqrt{1-x^2}=z$
Similarly,$y\sqrt{1-z^2}+z\sqrt{1-y^2}=x$
Similarly,$x\sqrt{1-z^2}+z\sqrt{1-x^2}=y$
Adding the three equations,we get
$x\sqrt{1-x^2}+y\sqrt{1-y^2}+z\sqrt{1-z^2}=\frac{x+y+z}{2}$
I am stuck here,please help me.Thanks.

A: Let $\sin^{-1}(x) = A\Rightarrow x=\sin A$ and $\sin^{-1}(y)=B\Rightarrow y=\sin (B)$
and $\sin^{-1}(z)=C\Rightarrow z=\sin C$
So above we have given $A+B+C = \pi$
Now we have to prove $\sin 2A+\sin 2B+\sin 2C=4\sin A\sin B\sin C$
So for $\bf{L.H.S}$
$$\sin 2A+\sin 2B+\sin 2C = 2\sin (A+B)\cdot \sin (A-B)+2\sin C\cos C$$
$$=2\sin C\cdot \sin (A-B)+2\sin C\cos C$$
$$=2\sin C\left[\cos(A-B)+\cos(\pi-(A+B))\right]$$
$$=4\sin C\cdot \left[\cos(A-B)-\cos(A+B)\right]$$
$$=4\sin A\sin B\sin C$$

A: Hint:
Write
$$x = \sin X \qquad y = \sin Y \qquad z = \sin Z$$
Where $X + Y + Z = \pi$ (meaning that those are the angles of a triangle).

A: All we need to facilitate analysis is the double angle formula
$$\sin(2a)=2\sin(a)\,\cos(a) \tag 1$$
the Prosthaphareis Identity
$$\cos (a-b)-\cos(a+b)=2\sin (a)\,\sin (b) \tag 2$$
along with the Reverse Prosthaphareis Identity
$$\sin (a)+\sin (b)=2\sin\left(\frac{a+b}{2}\right)\,\cos\left(\frac{a-b}{2}\right) \tag 3$$
Then, letting $x=\sin \alpha$, $y=\sin \beta$, and $z=\sin \gamma$ gives
$$\alpha +\beta +\gamma = \pi \tag 4$$
We wish now to transform the function $F(\alpha,\beta,\gamma)$ as given by
$$\begin{align}
F(\alpha,\beta,\gamma)&=\frac12 \sin (2\alpha)+\frac12 \sin (2\beta)+\frac12 \sin (2\gamma) \tag 5\\\\
&=x\sqrt{1-x^2}+y\sqrt{1-y^2}+z\sqrt{1-z^2}
\end{align}$$
First, use $(1)$ with $a=2\gamma$, $(3)$ with $a=2\alpha$ and $b=2\beta$, and $(4)$ to write $(5)$ as
$$\begin{align}
F(\alpha,\beta,\gamma)&=\sin(\alpha+\beta)\,\cos(\alpha-\beta)+\sin(\gamma)\,\cos (\gamma) \\\\
&=\sin(\pi-\gamma)\,\cos(\alpha-\beta)+\sin(\gamma)\,\cos (\pi-\alpha-\beta)
\end{align}$$
Next, substituting $(4)$ into $(6)$ and recalling that $\sin (\pi -a)=\sin(a)$ and $\cos (\pi-a)=-\cos(a)$ reveals
$$F(\alpha,\beta,\gamma)=\sin(\gamma)\left(\cos(\alpha-\beta)-\cos (\alpha+\beta)\right) \tag 7$$
Finally, using $(2)$ in $(7)$ yields
$$\begin{align}
F(\alpha,\beta,\gamma)&=\sin(\gamma)\left(2\sin(\alpha)\,\sin(\beta)\right)\\\
&=2\sin(\alpha)\,\sin(\beta)\,\sin)\gamma)\\\\
&=2xyz
\end{align}$$
Therefore, we obtain the identity
$$x\sqrt{1-x^2}+y\sqrt{1-y^2}+z\sqrt{1-z^2}=2xyz$$
as was to be shown!


text:
Q: C# WPF: Create TreeView from text file I create my TreeViewItems with the class Node . In the example nodes are specified in source code. But how do I do it if the nodes are to be imported from a text file with content like this:
text file content
Any ideas?
I have tried the following.
    public MainWindowVM()
    {
        private ObservableCollection<Node> mRootNodes;
        public IEnumerable<Node> RootNodes { get { return mRootNodes; } }
        List<string[]> TreeNodes = new List<string[]>();

        string[] lines = null;
        try
        {
            lines = System.IO.File.ReadAllLines(MainWindow.TextFilePath , System.Text.Encoding.Default);
        }
        catch (IOException ex)
        {
            MessageBox.Show(ex.Message);
            Environment.Exit(0);
        }
        if (lines == null || lines.Length == 0)
        {
            MessageBox.Show("Text file has no content!");
            Environment.Exit(0);
        }

        foreach (var line in lines)
        {
            TreeNodes.Add(line.Split('|'));
        }

        Node newNode = null;
        Node childNode = null;
        Node root = new Node() { Name = TreeNodes[0][0] };
        if (TreeNodes[0].Length > 1)
        {
            newNode = new Node() { Name = TreeNodes[0][1] };
            root.Children.Add(newNode);
        }
        for (int s = 2; s < TreeNodes[0].Length; s++)
        {
            childNode = new Node() { Name = TreeNodes[0][s] };
            newNode.Children.Add(childNode);
            newNode = childNode;
        }
    }

but I get only the first two nodes. I do not know how to build the whole TreeView with a loop.
TreeView

A: input example
Root|A
Root|B|C
Root|B|D
Root|E

the problem with your code is that you only process TreeNodes[0] element. to process a collection of elements you need a loop
 public MainWindowVM()
{
    private ObservableCollection<Node> mRootNodes;
    public IEnumerable<Node> RootNodes { get { return mRootNodes; } }

    string[] lines = null;
    try
    {
        lines = System.IO.File.ReadAllLines(MainWindow.TextFilePath , System.Text.Encoding.Default);
    }
    catch (IOException ex)
    {
        MessageBox.Show(ex.Message);
        Environment.Exit(0);
    }
    if (lines == null || lines.Length == 0)
    {
        MessageBox.Show("Text file has no content!");
        Environment.Exit(0);
    }

    Dictionary<string, Node> nodeCache = new Dictionary<string, Node>();
    // processing each line
    foreach (var line in lines)
    {
        Node parentNode = null;
        string key = null;
        // in each line there are one or more node names, separated by | char
        foreach (string childNodeName in line.Split('|'))
        {
            Node childNode;
            // names are not unique, we need a composite key (full node path)
            key += "|" + childNodeName;
            // each node has unique key
            // if key doesn't exists in cache, we need to create new child node
            if (false == nodeCache.TryGetValue(key, out childNode))
            {
                childNode = new Node { Name = childNodeName };
                nodeCache.Add(key, childNode);

                if (parentNode != null)
                    // each node (exept root) has a parent
                    // we need to add a child node to parent ChildRen collection
                    parentNode.Children.Add(childNode);
                else
                    // root nodes are stored in a separate collection
                    mRootNodes.Add(childNode);
            }

            // saving current node for next iteration
            parentNode = childNode;
        }
    }
}


text:
Q: Smoothing function for battery voltage display to reduce spikes in embedded system Reading a battery voltage in an embedded device.  However, the actual voltage varies greatly depending upon system load.  We need a method to reduce the fluctuation of the voltage to display the best value.
Currently, we're using a rolling/moving average.  However, over the last 15 readings, the result still fluctuates too much.
In reading about smoothing algorithms, it appears that b-splines, kernel filters, or some other smoothing algorithms would be ideal.  However, I can't find a simple example that doesn't use numpy or intrinsic functions within mathcad or some such.
Anybody know of a simple-to-implement function that could help with this?  This is a C++ project (using Qt 4.5) with just the bar minimum of libraries.  I'd prefer to stay in the integer domain (showing the voltage in millivolts from 3300-4200).
TIA
Mike

A: Well, it's a bit tough to tell what you need without specifics on your situation.  For example, what is your sensor sampling rate, and how is the sensor fluctuation and noise that you're trying to remove characterized?
However, if you already have moving average implemented, I might recommend trying a moving median instead.  (Median of the last n samples, rather than average.)  This will tend to reduce the impact of large short-term aberrations from normal from your output.
If you can find parameters that work, it would be preferrable for CPU and memory requirements to use some form of a discrete-time low-pass filter.  These are quite easy to implement, and only require knowledge of the previous output value and the current input to compute the current output.  For example:
Y = Y[n-1] + A * (X - Y[n-1])

(Where Y is the current output, Y[n-1] is the last computed output, and X is your latest sensor reading.)
A is effectively the time constant of the low pass filter, but it's discrete time, so it depends on the sampling rate.  Specifically, A = dt / tau, where dt is your sampling period in seconds, and tau is roughly analagous to the continuous-time time constant.

A: you can find explanations and source code in classical NR book:
http://apps.nrbook.com/c/index.html,
namely chapter 3:
http://www.arcetri.astro.it/irlab/library/recipes/bookcpdf/c3-3.pdf

A: Have you considered simply applying a skew limit to the value?
new_val = Read_From_HW();
diff = new_val - prev_val;

if (diff > SKEW_LIMIT)
    diff = SKEW_LIMIT;
else if (diff < -SKEW_LIMIT)
    diff = -SKEW_LIMIT;

reported_val = prev_val + diff;
prev_val = reported_val;

A: It would be possible to get very deep into signal processing techniques and complex math, but you have to ask yourself if it is really necessary?
If this display is a simple instantaneous numeric output, used for "indication only" rather than say a continuous graph or data log (i.e. you do not need to reconstruct the signal), then it would often be perfectly acceptable, to simply take a periodic average rather than a moving average.  Since that requires no history storage, you can average over as many samples as you wish, and this would be determined by the required frequency of display update.
It is not clever, but it is often adequate for the task.  Here's an example and a test simulation of its use.
class cPeriodicMean
{
    public :
        cPeriodicMean( int period ) : m_mean(0),
                                      m_period(period),
                                      m_count(0),
                                      m_sum(0)
        {
            // empty
        }

        void addSample( int sample )
        {
            m_sum += sample ;
            m_count++ ;
            if( m_count == m_period )
            {
                m_mean = m_sum / m_period ;
                m_count = 0 ;
                m_sum = 0 ;
            }
        }

        int getMean()
        {
            return m_mean ;
        }

    private :
        int m_mean ;
        int m_period ;
        int m_count ;
        int m_sum ;
} ;

// Test Simulation
#include <cstdlib>
#include <cstdio>
#include <windows.h>  // for Sleep to simulate sample rate
int main()
{
    // Average over 100 samples
    cPeriodicMean voltage_monitor( 100 ) ;

    for(;;)
    {
        // Simulate 4000mV +/- 50mV input
        int sample = 4000 + (std::rand() % 100) - 50 ;
        voltage_monitor.addSample( sample ) ;

        // Simulate 100Hz sample rate
        Sleep(10) ;

        // Current output
        int millivolts = voltage_monitor.getMean() ;
        printf( "\r%d millivolts    ", millivolts ) ;
    }
}

A refinement of this technique that will produce even smoother output but generate results at the same frequency would be use the periodic mean output as input to your moving average filter.  If you were to use my 100 samples per second example with the 100 sample period, and then put it through your 15 sample moving average, you will have used 15 seconds worth of sampling data while still getting a result every second, with little additional memory usage.
Obviously you can change the period, the moving average length, and the sampling rate to get the results you need at the update frequency you need.  I suggest that you take as many samples as you can for the period for which you need an update, then make the moving average as long as you wish to afford.

A: I know this doesn't directly answer your question, but would average bars help? In other words, show min/max/mean/median over say 15 second windows instead of just a mean.

A: This really sounds like a hardware problem to me. Is it a Li-Io or NiMH battery? What does the discharge curve look like? What components are there between the battery cells and your ADC? You need to know these things before running off to implement various digital filters.

A: If you don't have your answer this is a good way to print out something
on a robot such as a pololu 3pi.
{
    int bat = read_battery_millivolts();

    clear();
    print_long(bat);
    print("mV");
    lcd_goto_xy(0,1);
    print("Press B");

    delay_ms(100);
}


text:
Q: Masonry layout with "almost" equal columns using flexbox I have implemented layout calculation with the help of JS, that calculates each column and fills in each column with elements.
The basic idea is following:

*

*calculate total height of all elements

*split items into equal columns according to the height of each element (columns count depends on screen width)

*items order does matter

"equal columns" means not exactly equal but approximately.
JS layout
I know that flexbox can fill in each column until flexbox reaches height limit for column, then flexbox starts filling in next column...
But I want "equal columns"...
My question is not about Why is the two p-tags not beside each other when the screen is wide? or Horizontal masonry layout with flexbox CSS only [duplicate], maybe something like How to split a nested navigation into columns with almost equal heights but without JS and without "column fill in limitation".
Is it possible to implement such behavior with flexbox and without JavaScript?


text:
Q: PHP/HTML: How to sort an array by clicking on the headers of a table? I have a PHP file where I am populating a table from MySQL data, using array format to gather the information. I have headers on my table, and I would like to sort the table after clicking a specific header. How can I do that?
This is my running the query and getting the data into an array.
$results=$db_link->query($query);

 while($row = $results->fetch_assoc()) {
    $project_data[$row[id]][id] = $row[id];
    $project_data[$row[id]][billable] = $row[billable];
    $project_data[$row[id]][pugh_project] = $row[pugh_project];
    $project_data[$row[id]][name] = $row[address2]." ".$row[name];
    $project_data[$row[id]][project_num] = $row[project_num];
    $project_data[$row[id]][budget] = $row[budget_hours_pm] + $row[budget_hours_eng] + $row[budget_hours_des] + $row[budget_hours_cad] + $row[budget_hours_tech];
 }

This is the way I have my headers using HTML.

        Project #
        Project Name
        Budget Hours
        Actual Hours
        Estimate to Complete
        Budget at Completion
        Performance (%)

How can I make it so that I can click on a header (eg. Project Name), and refresh the page with the proper sorting??

A: If you want to do this all in PHP, the first step would be to convert the text in the column headers to links, specifying the column in a query string.

    Project Name

Then in your controller, (or whatever script you have that generates the table), you'll have access to the column you clicked in $_GET['sort'], and you can use that in an ORDER BY clause in your query.
You won't be able to pass a column name as a parameter to a prepared statement, so you'll have to add that dynamically to your SQL. It's a potential SQL injection vulnerability, so be sure you verify that $_GET['sort'] contains a valid column name before just using it in the query.


text:
Q: Area of triangles inside quadrilateral.
It seems to wrong statement but how can we prove it? Any hint will be appreciated.

A: We can-not prove it because it's wrong in the general.
But we can get any quadrilaterals with this property.
Indeed, let $S_{\Delta AOB}=a,$ $S_{\Delta COB}=b,$ $S_{\Delta COD}=c$ and $S_{\Delta AOd}=d,$
Thus, $$\frac{d}{a}=\frac{DO}{BO}=\frac{c}{b},$$ which gives
$$ac=bd.$$
Now, let $a>d$.
Thus, $b>c$ and
$$(a+c)^2=(b+d)^2$$ or
$$a^2+2ac+c^2=b^2+2bd+d^2$$ or
$$a^2-2ac+c^2=b^2-2bd+d^2$$ or
$$(a-c)^2=(b-d)^2$$ or
$$(a-c+b-d)(a-c-b+d)=0$$ or
$$a-c=b-d$$ and since $$a+c=b+d,$$ we obtain:
$$a=b$$ and $$c=d.$$
Id est, in our quadrilateral $O$ is a mid-point of $AC$
or by the same way we can show that $O$ is a mid-point of $BD$ (if $a>b$, for example).


text:
Q: When app switcher appears execute a command Xcode swift I was wondering if anyone knew how to execute a command when the user double presses the home button and/or when the just press it to go to the home screen. Snapchat does this as it blurs out the background when double tapped or dismisses a view controller if you go out and back in.
Using Xcode 7.3.1 and if possible could the code be Swift 2.2 or 2.3
Thanks
Regards,

A: In your Appdelegate.swift file you will find two methods that allow you to execute code when your app changes from the foreground state to the background - like pressing the home button.
func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state.
    //This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

    func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

A: plz use your AppDelegate methods
  func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }


text:
Q: Is it possible to re-direct a URL when other site's code is in root directory I have a web site I'm re-building that has it's code in the root of the domain; I also have the existing (original) website in the same domain in the folder QnE.
Is there a way that when the user enters xyz.com that I can somehow point it to xyz.com/qne (original code), leaving the new code in the root of the domain?  I understand what I'm asking (that both should be in separate directories for this to work) but I thought I'd ask anyway just in case there is a way to do it.

A: If you are on apache you could use .htaccess, take a look at this post on how to rewrite a folder name using .htaccess


text:
Q: Count particular characters within a column using Spark Dataframe API I have a column with bits in a Spark Dataframe df. The columns are strings of format:
10001010000000100000000000000000
10001010000000100000000100000000

Is there a simple and effective way to create a new column "no_of_ones" and count the frequency of ones using a Dataframe? Using RDDs I can map(lambda x:x.count('1')) (pyspark).
Additionally, how can I retrieve a list with the position of the ones?

A: In general, when you cannot find what you need in the predefined function of (py)spark SQL, you can write a user defined function (UDF) that does whatever you want (see UDF).
Note that in your case, a well coded udf would probably be faster than the regex solution in scala or java because you would not need to instantiate a new string and compile a regex (a for loop would do). However it would probably be much slower in pyspark because executing python code on an executor always severely damages the performance.

A: Since it is binary(0/1) the above answer will work. Appreciate Oli's Answer.
but just in case you need to find number of occurrence of a character/number/symbols in a string which has .
Eg:
Find '~' in a string "ABCDE~FGH~IJAK~123~$$$"

Go for the following solution.
df.withColumn("no_of_ones" , length($"bytestring") - length(regexp_replace($"bytestring", "~", "")) ).show

A: One way I can think of is to remove all zeroes and then count the length of the field.
df.show
+--------------------+
|          bytestring|
+--------------------+
|10001010000000100...|
|10001010000000100...|
+--------------------+

df.withColumn("no_of_ones" , length(regexp_replace($"bytestring", "0", "")) ).show
+--------------------+----------+
|          bytestring|no_of_ones|
+--------------------+----------+
|10001010000000100...|         4|
|10001010000000100...|         5|
+--------------------+----------+


text:
Q: eslint not found in TravisCI Deploy I am trying to get a site to deploy to Firebase using TravisCI. I keep running into an issue when the functions deploy and try to run lint. eslint doesn't seem to be there, even though I added a command to cd and npm install. I'm sure this is some kind of no-brainer. What am I missing?
Here's my .travis.yml:
language: node_js
node_js:
  - 12
deploy:
  provider: firebase
  project: "*****"
  message: "Deployed from Github by TravisCI"
  token:
    secure:
       *******
env:
  global:
    secure:
       *****
branches:
  only:
    - master
before_deploy:
  - npm install -g gatsby-cli
  - rm -rf node_modules/*/.git/
  - npm install
  - gatsby build
  - cd functions && npm install --dev && cd ..

Here's the error in the Travis log:
Installing deploy dependencies
dpl.2
Preparing deploy
dpl.3
Deploying application
=== Deploying to 'covid19-reports'...
i  deploying storage, firestore, functions, hosting
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions@ lint /home/travis/build/amygroshek/covid19reports/functions
> eslint .
sh: 1: eslint: not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! functions@ lint: `eslint .`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/travis/.npm/_logs/2020-03-23T00_34_17_951Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1


text:
Q: Calculate the order of a matrix. The matrix is composed only of $+\frac{1}4$ and $-\frac14$, and it is an orthogonal matrix, which means $$A A^{T} = I$$
And I want to know the order of such matrix.
If I want get the identity matrix, there would be some equations of $A$'s elements, but the order is unknown, which is confusing.

A: Let $A = [a_{ij}]_{(n\times n)}$. Then $(AA^T)_{11} = \sum_{j=1}^n a_{1j}^2 = (I)_{11} = 1$. Try to get the answer now. Or read further.
As each $a_{ij} = \pm \dfrac{1}{4}$, each $a_{1j}^2 = \dfrac{1}{16}$, so $\sum_{j=1}^n a_{1j}^2 = \dfrac{n}{16}$. Then what is $n$ (considering our first observation)?
$\dfrac{n}{16} = 1$, so $n = 16$ is the order of $A$ (if such a matrix exists at all).
Now actually construct $A$ by figuring out the distibution of $+$s and $-$s (it might be easier to consider a matrix of $\pm 1$s and then replace the $1$s with $\frac{1}{4}$s to get $A$).


text:
Q: How to create this schema like model in c#? I want to create a schema output using the c# model.
Example Schema

Food:[["burger", "french fries", "nuggets"], "status": "delivered"]

Model:

Public class Food
{
public List<item> items {get; set;}
}

public class item
{
public List<string> food_item {get; set;}

public string status {get; set;}
}

A: The proper json should look like below
"Food":[{"food_item":["burger", "french fries", "nuggets"], "status": "delivered"}]

And the model (use https://json2csharp.com/ to validate and convert your json to model)
public class Food
{
    public List<string> food_item { get; set; }
    public string status { get; set; }
}

public class Root
{
    public List<Food> Food { get; set; }
}

Deserialize using below code
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);


text:
Q: NGINX/Gunicorn/Django-RQ : How to log each rq-worker to a different file We are using the architecture of NGINX + Gunicorn + Django + RQ, with several rq-workers.
We use the basic Django logging setting (follows), with rollover and max-file-size, BUT:

*

*The created files are sometimes very small - a few bytes instead of the defined 2MB.

*The number rollover files is different than what was defined.

Questions:
a. Any idea why the actual file creation number and size are different then defined?
b. Is it possible to have each django rq-worker log to a different file, with rollover and max-file-size policy?
our logging settings:
LOG_FILE_MAX_SIZE_MB = int(os.environ.get('log_file_max_size_mb', 1))
LOG_FILES_ROTATE_NUM = int(os.environ.get('log_files_rotate_num', 8))

log_file_dir = os.path.dirname(LOG_FILE_FULL_PATH)
if not os.path.exists(log_file_dir):
    os.makedirs(log_file_dir, 0777)

DATE_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
VERBOSE_LINE_FORMAT = '%(asctime)s - %(levelname)s - %(process)d - %(thread)d     - %(filename)s - %(message)s'
SIMPLE_LINE_FORMAT = '[%(levelname)-7s] %(asctime)s - %(message)s'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
'formatters': {
    'verbose': {
        'format': VERBOSE_LINE_FORMAT,
        'datefmt': DATE_TIME_FORMAT
    },
    'simple': {
        'format': SIMPLE_LINE_FORMAT,
        'datefmt': DATE_TIME_FORMAT
    },
},
'handlers': {
    'console': {
        'level': 'DEBUG',
        'class': 'logging.StreamHandler',
        'formatter': 'verbose'
    },
    'fat_app_logfile': {
        'level': 'DEBUG',
        'class': 'logging.handlers.RotatingFileHandler',
        'maxBytes': 1024*1024*LOG_FILE_MAX_SIZE_MB,
        'backupCount': LOG_FILES_ROTATE_NUM,
        'filename': LOG_FILE_FULL_PATH,
        'formatter': 'verbose'
    },
    'rq_app_logfile': {
        'level': 'DEBUG',
        'class': 'logging.handlers.RotatingFileHandler',
        'maxBytes': 1024*1024*LOG_FILE_MAX_SIZE_MB,
        'backupCount': LOG_FILES_ROTATE_NUM,
        'filename': LOG_FILE_FULL_PATH,
        'formatter': 'verbose'
    },
},
'loggers': {
    'MainLogger': {
        'handlers': ['console', 'fat_app_logfile'],
        'propagate': True,
        'level': 'DEBUG',
    },
    'rq_scheduler': {
        'handlers': ['console'],
        'level': 'DEBUG',
        'propagate': True,
    },
}

Thank you

A: The issue emerges from multi-processes trying to use the standard logging (logging.handlers.RotatingFileHandler) not supporting concurrent write, instead using cloghandler.ConcurrentRotatingFileHandler solves the issue.
For example in django setting.py:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
# 'filters': {
#     'require_debug_false': {
#         '()': 'django.utils.log.RequireDebugFalse'
#     }
# },
'formatters': {
    'verbose': {
        'format': VERBOSE_LINE_FORMAT,
        'datefmt': DATE_TIME_FORMAT
    },
    'simple': {
        'format': SIMPLE_LINE_FORMAT,
        'datefmt': DATE_TIME_FORMAT
    },
},
'handlers': {
        'fat_app_logfile': {
        'level': 'DEBUG',
        'class': 'cloghandler.ConcurrentRotatingFileHandler',
        'maxBytes': 1024 * 1024 * LOG_FILE_MAX_SIZE_MB,
        'backupCount': LOG_FILES_ROTATE_NUM,
        'filename': LOG_FILE_FULL_PATH,
        'formatter': 'verbose'
    },

Related link: here


text:
Q: Asp.net & files modifications? We are changing a file and uploading it into the web server.
Once and for all , I would like to know how changing files will affect iis's Appdomain
I currently use website - So i've written from my knowledge.
what will be the values in web Application ?( how does modified files in X will affect Appdomain in iis ? )
______________________________|_ Web Application _|___ Web Site _____________

changed Global.asax           |                   |     restarted
                              |                   |
                              |                   |
changed web.config            |                   |     restarted
                              |                   |
                              |                   |
changed CS file               |                   |      nothing
                              |                   |
                              |                   |
changed Aspx file             |                   |      nothing
                              |                   |
                              |                   |
changed App_code(folder) file |                   |     restarted
                              |                   |
                              |                   |
changed BIN(folder) dll file  |                   |     restarted

A: The app pool is recycled when any of the following items are modified:

*

*web.config

*machine.config

*global.asax

*bin directory

*app_code directory

The app pool may be recycled for other reasons, e.g., by explicitly configuring it to recycle at a specific time or after a certain amount of time.
Modifying static files (.js, .css, .html, .jpg, etc.) will not trigger a recycle unless those files are written to one of the directories mentioned above.


text:
Q: Why wire filament shakes inside a light bulb? My light bulb cast a clear light toward adjacent wall and I can clearly see, that wire filament inside bulb shakes, though lamp itself does not moves even an inch
What is causing this? Is it a permanent effect, happening all the time? Or is it a syndrome of near end of life of this current light bulb?

A: This really depends on the design of the bulb in question. High-power or hard use bulbs have filaments under some tension and strong supports. Other (mainly decorative) bulbs have very wispy support wires and straight, loose filaments. In this case, the wire can be very sensitive to mechanical vibration through the floor. The bulb and lamp ( a bulb will be mechanically the same as the lamp when screwed into the socket ) have mass thousands of times heaver than the filament, and the resonant frequency will be much lower.

A: Assuming that the bulb is powered by some variation of alternating current, and that there is a static magnetic field present in the environment, the vibration could be caused by the interaction of the fixed external magnetic field, and the alternating magnetic field caused by the AC flow through the filament.  Bulb filaments are often in the form of a tightly coiled helix, to increase the surface area and allow for thermal expansion.  This can complicate the AC field generated...

A: *

*Is the shaking immediate upon turning the bulb on or after a while? This could mean heating causes

*Is this the only bulb doing this or is it same with other (of same type)? This could mean bulb towards end of its life or bulbs of this type do that due to construction of filaments

*Is this the only bulb doing this or is it same with any other? This could mean sth else might affect the bulbs, like motion or magnetic fields

*Does this happen on this bulb on one place or in other places as well? This could mean the specific place interfers with the bulb

*Does this happen on this bulb on a specific time/day? This could mean sth interferes on specific times, sth enviromental, like TV or cable-voltages
Hope the above provided a procedure to assess your light bulbs :)

A: It's quite common for ac-powered electrical devices which are designed without moving parts to "hum," usually with an audible frequency of 60 Hz, 120 Hz, 180 Hz, or other 60 Hz harmonics.  (In other parts of the world, where the power distribution system frequency is 50 Hz, you'd obviously get harmonics of that frequency instead.) For instance, when I'm baking or cooking, I can hear when the heating elements in my electric stove cycle on and off. Audible sounds are produced by mechanical oscillations of some object in contact with the air, so a vibrating resistive load is not uncommon at all. I suppose the motion must be magnetically actuated, but I've never really thought about details.
Different bulbs will have different filament mass densities and different lengths of filament between the supports, and so like different guitar strings they'll have different mechanical resonance frequencies. I'd imagine that vibration would make the filament more likely to break sooner, and so a good bulb (in the US) would be designed to be quiet at the 60 Hz harmonics. A bulb designed for a 50 Hz market (note that China, which does lots of manufacturing for the US, has 50 Hz power) might vibrate more than the designer intended when powered at 60 Hz. And of course a cheap light bulb might have been put together with no consideration of this effect at all. (You probably know the joke: "I'm returning these light bulbs, they don't seem to last very long at all." "They can't be defective, sir, they're our best sellers!")
If you had strobe lamp or camera with variable frequency you might be able to determine whether its 60 Hz harmonic oscillation or something else. I think that fluorescent coatings have advanced enough that you can't just use a CFL bulb as a powerline-frequency strobe. My DSLR camera has an option called "flicker reduction" that can be set to 50 Hz or 60 Hz; if you have the same thing you might try to video the effect on both settings and see if one or the other "freezes" the vibration.


text:
Q: Weird IFRAME issue, page blocks itself from loading This is a weird one. I'm using the URL "http://www.craigslist.org/about/" as an example here.
I load up that page in my browser and modify it with Firebug. I add the following line right after the body tag:
<iframe src="http://www.craigslist.org/about/" id="frame1" name="frame1" width="100%;" height="200"></iframe>

The IFRAME shows as blank! Now when I load https instead of http in the IFRAME it works. At first I thought maybe craigslist doesn't allow itself to be embedded in an IFRAME at all. Then I tried embedding that same IFRAME code on my website and the frame loads as expected.
It's as if they are blocking you from loading the same page within itself!? Anyone ever seen this behavior before?
UPDATE:
This problem appears to be related to my browser. (Firefox 21) When I try to load any IFRAME that has the same exact URL as the parent frame it fails??


text:
Q: MVC4 scaffolding of database-first Entity Framework model in Visual Studio 2012 I'm having problems with Visual Studio 2012, trying to add an MVC4 Controller with scaffolding. Ideally I would like to have an Entity Framework model (edmx file, etc) generated from a database using Add New Item - ADO.NET Entity Data Model (i.e. not Code First) in a separate assembly from my web application. However, when I set this up and use Add Controller, specifying "MVC controller with read/write actions and views, using Entity Framework" and choosing a Model class and Data context class from my DatabaseModel assembly the following alert message pops up.

'Ifl.Payforit4.DatabaseModel.Mno' is not part of the specified
  'Ifl.Payforit4.DatabaseModel.Payforit4Entities' class, and the
  'Ifl.Payforit4.DatabaseModel.Payforit4Entities' class could not be
  modified to add a 'DbSet' property to
  it. (For example, the 'Ifl.Payforit4.DatabaseModel.Payforit4Entities'
  class might be in a compiled assembly.)

Not being able to modify the class makes sense since it is in another assembly, although in the same solution, and auto-generated via T4 but looking at the auto-generated code for Payforit4Entities the 'DbSet' property is quite clearly there already.

    public DbSet<Mno> Mnoes { get; set; }

I've tried a number of other things.

*

*putting the data model directly in the web application

*changing the model class to a variety of other tables in the database in case there is a problem with the Mno class

*reducing the data model to just a single, simple table

*using the Entity Framework Power Tools Beta 2 to reverse engineer a Code First model. This generated a new set of errors. I can see why it is a beta.

*changing the ADO.NET Data Model Code Generation Strategy from None to Default to create a data model based on ObjectContext rather than DbContext

*Turning off pluralisation so the property name is Mno instead of Mnoes

None of them worked. The only thing that did work was writing a Code First DbContext-derived class and POCO by hand. Coincidentally every example I've found that demonstrates MVC4 scaffolding uses this sort of data model. Is there something somewhere that says Code First is the only sort of data model that works with MVC4 scaffolding? Has anyone managed to scaffold a database first (.edmx) data model in Visual Studio 2012? The database is complex enough that I'd rather stick with a database first strategy.
I can see that there would have to be some differences in the scaffolding of Code First versus Database First models. For example, the former has the POCO property holding the key indicated by a KeyAttribute whereas the latter holds that information in the edmx model files. Is this the rationale for the reverse engineer feature in Entity Framework Power Tools? Are we expected to move away from edmx files to reverse engineered Code First models in order to use MVC4 scaffolding? If so, are we expected to carry on using Dynamic Data projects until the Entity Framework Power Tools are finished?

A: The trick is to first compile your solution and then type in the context class manually. Don't choose it from the Dropdown list, just type in the class name by yourself and it will magically work ;-)
See here: ASP.NET MVC4– How to use a Database First EF in a MVC controller

A: I don't think we can scaffold from edmx files with Entity Framework 5.
I've tried a similar set of things and am still hitting errors.
There are a couple of suggestions that maybe just deleting a bad edmx and starting again could generate the correct .tt files to allow the scaffolding to work correctly, but I've not yet seen this.
I'm going to try some more to get it working, as I prefer DB first approaches. I will update this answer if I get any further.

A: The edmx code generator in Entity Frameork 5/VS 2012 is buggy.  It creates code that is full of compiler errors.  I'm guessing it wasn't ready for shipping when vs2012 was released, which is why they set the default code generation flag to none.
The only question for Microsoft is: when can we expect an update that fixes this?

A: It's truth!
The trick is to first compile your solution and then type in the context class manually. Don't choose it from the Dropdown list, just type in the class name by yourself and it will magically work ;-)
thank!!  Marcus!


text:
Q: SCSS Typography best practice? I'm not sure which route to go down and which is considered 'best practice' here.
Goal: have a selector that removes the global standard margin I've set of 20px on typography elements.
Option 1:
Have a global selector class that can be applied anywhere in the dom for the desired effect:
SCSS
html {margin: 20px 0;}
.no-margin {margin: 0;}

HTML

Title here

Text here

Option 2:
Use specificity on a granular level to set these values in the SCSS
SCSS
html {margin: 20px 0;}
.box {
 h1, p {
  margin: 0;
 }
}

HTML

Title here

Text here

So basically my question is: Is it better to have a more crowded SCSS file and a cleaner HTML DOM structure without multiple uses of the same class.
OR
Only have the SCSS specified once at the expense of a messy DOM?

A: If you want to implement same style on all elements then you can use ***** for all selector selection
Example:

*{
margin:0;
padding:0;
}

Hello World

This is a 6th level heading with small size.

this paragrah has same padding and margin as h1 and h6

<button>Click</button>

*

*can use to implement same style on all elements


text:
Q: Unable to cast object of type 'ModelDetailView' to type 'DevExpress.ExpressApp.ViewVariantsModule.IModelViewVariants' I installed the View Variants module to my XAF winforms 21.2.7 project and it "works on my machine"
When I deploy and run I get an error with the following call stack logged in eXpressAppFramework.Log
    Type:       InvalidCastException
    Message:    Unable to cast object of type 'ModelDetailView' to type 'DevExpress.ExpressApp.ViewVariantsModule.IModelViewVariants'.
    Data:       0 entries
    Stack trace:
   at DevExpress.ExpressApp.ViewVariantsModule.ModelVariantsProvider.GetVariants(String rootVariantViewId)
   at

DevExpress.ExpressApp.ViewVariantsModule.ReplaceViewIdHelper.factoryEvents_ViewCreating(Object sender, ViewCreatingEventArgs e)
       at DevExpress.ExpressApp.ViewVariantsModule.XafApplicationViewsFactory.application_ViewCreating(Object sender, ViewCreatingEventArgs e)
       at DevExpress.ExpressApp.XafApplication.OnViewCreating(ViewCreatingEventArgs args)
       at DevExpress.ExpressApp.XafApplication.PrepareDetailViewCreatingEventArgs(IObjectSpace objectSpace, String detailViewID, Boolean isRoot, Object obj, Boolean isDelayedObjectLoading)
       at DevExpress.ExpressApp.XafApplication.CreateDetailViewCore(IObjectSpace objectSpace, String detailViewID, Boolean isRoot, Object obj, Type objectType, Object objectKey, Boolean isDelayedObjectLoading, IEnumerable objectsToPrefetch)
       at DevExpress.ExpressApp.XafApplication.CreateDetailView(IObjectSpace objectSpace, String detailViewID, Boolean isRoot, Object obj, Boolean isDelayedObjectLoading, IEnumerable objectsToPrefetch)
       at DevExpress.ExpressApp.XafApplication.CreateDetailView(IObjectSpace objectSpace, String detailViewID, Boolean isRoot, Object obj)
       at DevExpress.ExpressApp.XafApplication.CreateDetailView(IObjectSpace objectSpace, Object obj, View sourceView)
       at DevExpress.ExpressApp.XafApplication.showLogonAction_OnCustomizePopupWindowParams(Object sender, CustomizePopupWindowParamsEventArgs args)
       at DevExpress.ExpressApp.Actions.PopupWindowShowAction.GetPopupWindowParams()
       at DevExpress.ExpressApp.Win.PopupWindowShowActionHelper.CreatePopupWindow(Boolean createAllControllers)
       at DevExpress.ExpressApp.Win.WinApplication.DoLogon()
       at DevExpress.ExpressApp.Win.WinApplication.Start()
        InnerException is null

I can work around the issue by opening a pre-viewvariants copy of the application and logging in.
After that I can use the application successfully.
Alternatively I can delete the file ModulesVersionInfo from the Users Roaming Application folder to get the app opening successfully
Deleting modelassembly.dll from the application folder also solves the issue.

A: Removing ModelAssembly.Dll from deployment solved the issue.
The dll then gets created correctly by the app when it opens.


text:
Q: Build-Error when using SignFile with dotnet build I added the following code to my CSPROJ-File:
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
   <SignFile CertificateThumbprint="{some-sha-code}" SigningTarget="$(TargetPath)" />
</Target>

It works if I build directly in Visual Studio 2019. If I try to build it via "dotnet build" I get the following error:
error MSB4062: Die Microsoft.Build.Tasks.SignFile-Aufgabe konnte nicht aus der Microsoft.Build.Tasks.Core, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a-Assembly geladen werden.  Stellen Sie sicher, dass die <UsingTask>-Deklaration korrekt ist, die Assembly und alle zugeh"rigen Abh"ngigkeiten verfgbar sind und die Aufgabe eine "ffentliche Klasse enth"lt, die Microsoft.Build.Framework.ITask implementiert.
Unfortunatly the software gives me the error message in German, I didn't know how to change it. It explicitly using wrong German (meaning the wrong encoding for the Umlaute!) It says something like this:
"The […]SignFile-Task could not be loaded from assembly […]Tasks.Core, Version=15.1.0.0. Check if <UsingTask> declaration is correct and all dependencies are availabe and it should contain a task that implements […]ITask."
I didn't have a <UsingTask>-Section. The "SignFile" documentation doesn't say anyting about the UsingTask-Section either.
Has anyone got an idea how I get this to work?
PS: The reason I try to get this to work is, that our TFS is configures to use "dotnet build" and "dotnet pack" for building and deploying the dlls. I had problems on the TFS with the "pack" if I didn't use "dotnet" but "VSBUILD". It's very annoying that there isn't a build tool that just works.


text:
Q: What are the best use cases for aws glue python shell jobs vs. spark jobs? Have been using aws glue python shell jobs to build simple data etl jobs, for spark job, only have used once or twice for converting to orc format or executing spark sql on JDBC data. So wondering which are the best/typical use cases for each of them?
Some document says python shell job is suitable for simple jobs whereas spark for more complicated jobs, is that correct? Could you please share more experience on this?
Many thanks

A: Use AWS Glue Python shell when you do not need too much of a compute power to run light ETL workloads. Use AWS Glue with Spark when you must scale either horizontally, vertically, or both.
Source: What are the best use cases for aws glue python shell jobs vs. spark jobs?

A:
which are the best/typical use cases for each of them? Some document
  says python shell job is suitable for simple jobs whereas spark for
  more complicated jobs, is that correct?

AWS Glue is quick development facility/service for ETL jobs, given by AWS.
IMHO it is very quick development if you know what needs to be done in your etl pipeline.

*

*Glue has components like Discover, Develop, Deploy.
In Discover... automatic crawling (run or schedule a crawler multiple times) is the important feature which differentiates with other tools I observed.

*Glue has seems like integration feature to connect to AWS eco system services (where as spark you need to do it)
Typical use case of AWS Glue could be...
1) Load data from Dataware houses.
2) Build a data lake on amazon s3 .
See this presentation of AWS for more insight.
Custom Spark Job also can do the same thing, but it needs to be developed from the scratch. and it doesnt have in built automatic crawling kind of feature.
But if you develop a spark job for etl you have fine grained control to implement complicated jobs.
Both glue, spark has same goal for ETL. AFAIK, Glue is for simple jobs such as loading from source to destination. Where as Spark job can do wide variety of transformations in a controlled way.

Conclusion :  For simple use cases of ETL (which can be done with out much development experience ) go with Glue. For customized ETL
  which has many dependencies/transformations go with spark job.


text:
Q: Is it possible to titleize in IRB? I tried this :
User.find(1).update_attribute('first_name', '#{first.name.titleize}')

=> /#{first.name.titleize}

I am not sure any other way to do this.
Many thanks

A: First, You need to use double quotes, ruby does not interpolate the embedded variable in single quotes.
Second, you need to bind the user to a variable in order to access the first_name attribute.
This should work:
u = User.find(1)
u.update_attribute(:first_name, u.first_name.titleize)


text:
Q: How to implement Duda White Label API into an HTML site? I am trying to implement the Duda White Label API into a .html page so that it utilizes my custom CSS.
I am following the instructions here: https://support.dudamobile.com/API/API-Use-Cases/Multiscreen-White-Label-Setup
I have inserted my API and Password, as well as my custom url into the example php code and uploaded it as "dynamic.php" to my web server.
On my page I have the following as the body code:

    <?php require 'dynamic.php';?>

I have also tried include instead of require.  Both display nothing. I am mainly a front end designer so this is quite challenging. I feel like I am missing something huge. Can anyone point me in the right direction?

A: I just went with an iframe and that worked.
I'll leave this up for anyone else struggling with the Duda API.


text:
Q: Update Random Number in css href I am having a css link tag in my html like this
<link rel="stylesheet" href="skin.css">

I want to add a random number saved in local storage to href like below
<link rel="stylesheet" href="skin.css?cb=sessionStorage.cbVersion">

I know that we can assign an id to this and later change the href attribute value but I am trying to find is there any way to implement the same thing without writing any extra logic.

A: CSS is static. As in: it will always parse the value of an href attribute as a string. So, given the above, it will try to access {your-domain}/skin.css?cb=sessionStorage.cbVersion.
If you need it to be variable, you have two options:

*

*use whatever logic you need at the time you're creating the HTML of your page on server side using the language you use on server side (php, Java, etc...)

*use JavaScript on client side (when the page was loaded in the browser).

In the second case, you don't have to use an id, although it's a common (and recommended) method for targeting elements. But you need a way in which to uniquely identify your element so you can change its href.
Simple example:

<link rel="stylesheet" data-href="dynamic-stylesheet">
<script>
  const link = document.querySelector('link[data-href="dynamic-stylesheet"]');
  link.href = `skin.css?cb=${sessionStorage.cbVersion || 'defaultValue'}`;
</script>

Note this won't work on StackOverflow as snippets are sandboxed and not allowed to access sessionStorage.
Also note I removed the href altogether as, if present and invalid, it will result in a 404 error, as it will be parsed at the moment the <link> is parsed, which has to be before you run your script. Or, as an alternative, you could not have the <link> at all and create it using JavaScript, with the desired href value.
Last, but not least, you should always provide a defaultValue for when cbVersion is not found on sessionStorage. An improved version of the above script would use a try/catch for retrieving the sessionStorage value and provide the defaultValue if the resulting value is still falsy:

<link rel="stylesheet" data-href="dynamic-stylesheet">
<script>
  const link = document.querySelector('link[data-href="dynamic-stylesheet"]');
  let cbVersion;
  try {
    cbVersion = sessionStorage.cbVersion;
  } catch(err) {
    //console.log(err)
  }
  link.href = `skin.css?cb=${cbVersion || 'defaultValue'}`;
</script>

As you can see, the above tries to load https://stacksnippets.net/skin.css?cb=defaultValue (which doesn't exist), and does not output an error about not being able to access sessionStorage on SO.


text:
Q: Cómo hacer que muestre un 404 si la ruta o vista no existe ¿Qué tengo que modificar o agregar en RouteConfig para que si en la url digito o trato de navegar a una vista o ruta que no exista me muestre una vista 404 (añadida al proyecto)?
Archivo de rutas:
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

A: Lo logre añadiendo en el Web.Config la siguiente linea dentro de <system.web></system.web>
<customErrors mode="On">
       <error statusCode="404" redirect="NF/NF"/>
</customErrors>

La cual va rediriga a una vista con el error

A: También podrias manejar el error NOT FOUND en Global.asax.cs como se muestra a continuación:
protected void Application_Error(object sender, EventArgs e)
{
    Exception lastErrorInfo = Server.GetLastError();
    Exception errorInfo = null;

    bool isNotFound = false;
    if (lastErrorInfo != null)
    {
        errorInfo = lastErrorInfo.GetBaseException();
        var error = errorInfo as HttpException;
        if (error != null)
            isNotFound = error.GetHttpCode() == (int)HttpStatusCode.NotFound;
    }
    if (isNotFound)
    {
        Server.ClearError();
        Response.Redirect("~/Error/NotFound");//lo que necesites
    }
}

espero te pueda ayudar


text:
Q: Java Data-Entity model: Constructing general types I have had some trouble with using a general type in a static method.
All comments on the source code are welcome, especially ones that significantly improve the code. I am also currently not planning on using any external framework, apart from JDBC, to keep it still simple, please do not put too much emphasis on that.
My view on not using external frameworks is also supported by the fact that the operations I will be using on the database are very minimal:

*

*Inserting data

*Updating data

*Retrieving all fields. (And simply by putting in a different SQL Query you could already select what fields to retrieve

I do not plan on making a full framework, so I know that it will not be supporting everything. The speed of retrieving all fields is neither a real issue, as this will be pretty much only done on server bootup, and if used at any other time it will be done in a background task for which I do not really care when it is finished.
Entity.java:
abstract public class Entity<KeyType, DataType> {
    protected KeyType key;
    protected List<Object> data;

    public Entity() {
        data = new ArrayList<>();
    }

    //abstract public static Map<KeyType, DataType> getAll();

    protected List<Object> createData(final DataAction dataAction) {
        List<Object> list = new ArrayList<>();
        if (dataAction == DataAction.INSERT) {
            list.add(key);
        }

        list.addAll(data);

        if (dataAction == DataAction.UPDATE) {
            list.add(key);
        }
        return list;
    }

    abstract public void insert();

    abstract public void update();

    protected static <KeyType, DataType> Map<KeyType, DataType> getData(final Class<DataType> dataTypeClass, final String query) {
        Map<KeyType, DataType> map = new HashMap<>();
        try {
            PreparedStatement preparedStatement = DatabaseConnection.getConnection().prepareStatement(query);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                KeyType key = (KeyType)resultSet.getObject(1);
                int index = 2;
                List<Object> dataList = new ArrayList<>();
                while (resultSet.getObject(index) != null) {
                    dataList.add(resultSet.getObject(index));
                    index++;
                }
                DataType dataObject = null;
                try {
                    dataObject = dataTypeClass.getConstructor(List.class).newInstance(dataList);
                } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
                    Logger.getLogger(Entity.class.getName()).log(Level.SEVERE, null, ex);
                }
                map.put(key, dataObject);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Entity.class.getName()).log(Level.SEVERE, null, ex);
        }
        return map;
    }

    protected void executeQuery(final String query, final List<Object> data) {
        try {
            PreparedStatement preparedStatement = DatabaseConnection.getConnection().prepareStatement(query);
            int dataIndex = 0;
            for (Object dataObject : data) {
                preparedStatement.setObject(dataIndex, dataObject);
                dataIndex++;
            }
            preparedStatement.execute();
            preparedStatement.close();
        } catch (SQLException ex) {
            Logger.getLogger(Entity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

A concrete implementation, Account.java:
public class Account extends Entity<String, Account> {
    private final static String SELECT_ALL_QUERY = "SELECT * FROM accounts";
    private final static String INSERT_QUERY = "INSERT INTO accounts (username, password) VALUES(?, ?)";
    private final static String UPDATE_QUERY = "UPDATE accounts SET password=? WHERE username=?";

    private String username;
    private String password;

    public Account(final String username, final String password) {
        this.username = username;
        this.password = password;

        key = username;
        data.add(password);
    }

    public Account(final List<Object> data) {
        this((String)data.get(0), (String)data.get(1));
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(final String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(final String password) {
        this.password = password;
    }

    public static Map<String, Account> selectAll() {
        return getData(Account.class, SELECT_ALL_QUERY);
    }

    @Override
    public void insert() {
        executeQuery(INSERT_QUERY, createData(DataAction.INSERT));
    }

    @Override
    public void update() {
        executeQuery(UPDATE_QUERY, createData(DataAction.UPDATE));
    }
}

I am generally happy about the concrete implementation, it seems like I have managed to bring it down to a bare minimum, except public Account(final List<Object> data) does not seem that nice, but I can live with it.
However, as guessed, the getData() from Entity is definately not nice, and I would like to improve it if possible.
What I would like to use is something like DataType dataObject = new DataType(dataList), but it seems like Generic Type Arguments cannot be instantiated.
So are there any ways of optimizing my current code in my current view? And is it possible to decouple the concrete classes and abstract classes even more?
EDIT:
Added a relevant question (I don't think I should make a fully new question for this thing, right?):
Is there a way to move the static Strings (SQL Queries) and the insert() and update() out of the Account class, into the Entity class?

A: To avoid the use of reflection in your getData method you should accept a factory that given a ResultSet creates instances of the specific type.  Your selectAll method would then be something like:
public static Map<String, Account> selectAll()
{
  return getData(
    new EntityFactory<Account>()
    {
      public Account newInstance(ResultSet resultSet) throws SQLException
      {
        return new Account(resultSet.getString(0), resultSet.getString(1));
      }
    },
    SELECT_ALL_QUERY
  );
}

The getData method then ends up something like:
protected static <K, T extends Entity<K>> Map<K, T> getData(EntityFactory<T> entityFactory, String query)
{
  Connection connection = null;
  PreparedStatement preparedStatement = null;
  ResultSet resultSet = null;

  try
  {
    connection = dataSource.getConnection();

    preparedStatement = connection.prepareStatement(query);

    resultSet = preparedStatement.executeQuery();

    Map<K, T> entities = new HashMap<>();

    while (resultSet.next())
    {
      Entity<K> entity = entityFactory.newInstance(resultSet);
      entities.put(entity.getKey(), entity);
    }

    return entities;
  }
  finally
  {
    closeQuietly(resultSet);
    closeQuietly(prepareStatement);
    closeQuietly(connection);
  }
}

And assumes the Entity looks like:
public interface Entity<K>
{
  public K getKey();
}

This allows you to remove the reflection and keeps the code that understands the database structure in one place.  You should also use a similar template pattern to map from the domain object to the prepared statement when doing inserts and updates.
Now you've asked for comments on the code in general.
First off, code like this violates the Single Responsibility Principal and Seperation Of Concerns.  A domain class should be a domain class and not contain persistance logic.  Look at patterns like the Data Access Object for how this should be done.
Second, while I'm all for keeping it simple, Hibernate solved this problem a long time ago and JPA standardized it - you need a very good reason not to use one or both of these APIs.
Finally, your use of database resources - if you are going to use JDBC directly you have to clean up properly.  Database connections are expensive resources and should be handled as such, the basic template for any JDBC call should be:
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

try
{
  connection = //get connection from pool or single instance.

  preparedStatement = connection.prepareStatement("SELECT * FROM table WHERE column = ?");
  preparedStatement.setString(1, "some string");

  resultSet = preparedStatement.executeQuery();

  while (resultSet.next())
  {
    //logic goes here.
  }
}
catch (SQLException e)
{
  //Handle exceptions.
}
finally
{
  closeQuietly(resultSet);
  closeQuietly(prepareStatement);
  closeQuietly(connection);
}

The closeQuietly method has to be overloaded but should take the general form:
try
{
  if (resultSet != null)
  {
    resultSet.close();
  }
}
catch (SQLException e)
{
  //Log exceptions but don't re-throw.
}

A: Well, as Darwind and Nick Holt told you, in a normal situation, you should use JPA, which is the Java standard specification for object-relational mapping. You can use Hibernate, EclipseLink or any other framework behind. Their design is  can manage connections, transactions. In addition, using standards rather than exotic frameworks means that you can get help more easily for the community.
 Another option is using Spring JDBC, which is quite light and facilitates many things.
Anyway, I suppose you did this for learning purpose so let's try to go further.
First, I think you should separate the classes in charge or retrieving the data (call it manager or Data Access Object -DAO-) and the entites representing the data themselves.
For me, using the class to get all the data as you did isn't a problem in itself. The problem is the position of the key is hardcoded. This should not be determined directly a generic (I mean the same for all the Entity implementation). This makes queries subjects to bugs when the first field is not the key (are you sure a select * from... will ALWAYS return the key in the first position? ) or with a composite key.
I think a better solution is to crate a Mapper interface and to implement it for each entity.
public interface RecordMapper<KeyType, DataType extends Entity> {
    public void appendToMap(ResultSet resultSet, Map<KeyType, DataType>) throws SQLException;
}

The implementation of the mapper should be in charge of instanciating your entity, retrieving the key from the resultset, populating your entity and putting it in the map you expect.
public class AccountMapper implement RecordMapper<String, Account>{
    public void appendToMap(ResultSet resultSet, Map<String, Account> accounts) throws SQLException {
        String user= resultSet.getString("userName");
        String pwd= resultSet.getString("passWord");
        Account account = new Account(user, pwd);
        accounts.put(user, account);
    }
}

As I told you should move your data access methods in a DAO:
    public class DAO{
    public <KeyType, DataType> Map<KeyType, DataType> getData(final RecordMapper<KeyType, DataType> mapper, final String query) {
        Map<KeyType, DataType> map = new HashMap<>();
        try {
            PreparedStatement preparedStatement = DatabaseConnection.getConnection().prepareStatement(query);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                mapper.appendToMap(resultSet, map);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Entity.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(resultSet != null){
                try{resultSet.close();} catch (Exception e){}
            }
            if(preparedStatement!= null){
                try{preparedStatement.close();} catch (Exception e){}
            }
        }
        return map;
    }

    public void executeQuery(final String query, final List<Object> data) {
        try {
            PreparedStatement preparedStatement = DatabaseConnection.getConnection().prepareStatement(query);
            int dataIndex = 0;
            for (Object dataObject : data) {
                preparedStatement.setObject(dataIndex, dataObject);
                dataIndex++;
            }
            preparedStatement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(Entity.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(resultSet != null){
                try{resultSet.close();} catch (Exception e){}
            }
            if(preparedStatement!= null){
                try{preparedStatement.close();} catch (Exception e){}
            }
        }
    }
}

To answer your second quenstion, I think that putting your request string in the abstract parent instead of is certainly not a good idea. Each time you create new entity, you have to create a new query in the parent. Weird...unless I haven't understood properly your question.
Personnaly I think that the queries should be build dynamically and you should use reflection and annotations but the answer should be a bit long. Once again, you can get a look at JPA to see how creating an entity should look like. By the way, it should be even better if the entities didn't have to extend a parent Entity class.