text:
Q: Retrieving data from PostgresQL database with millions of rows takes very long I've been working on a system where users can register as an user, create a book club and invite other people (members) to join. The user and member can all add books to the club, and also vote for books that other members have added. I recently tried to add a lot of data to check if the database is performing well, after which I found out that it takes a lot of time to actually get the data I like. I would like to get all books in a club, including their votes and the name of the members that have voted for it.
My database diagram (created via dbdiagram.io, check it out)

In order to freely query the database without too much hassle, I decided to use Hasura, an open source service that can create a GraphQL backend by just looking at the data structure (I am using PostgresQL). I Use the following query to get the data I want:
query GetBooksOfClubIncludingVotesAndMemberName {
  books(
    where: {
      club_id: {_eq: "3"},
      state:{_eq: 0 }
    },
    order_by: [
      { fallback : asc },
      { id: asc }
    ]
  ) {
    id
    isbn
    state
    votes {
      member {
        id
        name
      }
    }
  }
}

This query of course gets converted to a SQL statement
SELECT
  coalesce(
    json_agg(
      "root"
      ORDER BY
        "root.pg.fallback" ASC NULLS LAST,
        "root.pg.id" ASC NULLS LAST
    ),
    '[]'
  ) AS "root"
FROM
  (
    SELECT
      row_to_json(
        (
          SELECT
            "_8_e"
          FROM
            (
              SELECT
                "_0_root.base"."id" AS "id",
                "_0_root.base"."isbn" AS "isbn",
                "_7_root.ar.root.votes"."votes" AS "votes"
            ) AS "_8_e"
        )
      ) AS "root",
      "_0_root.base"."id" AS "root.pg.id",
      "_0_root.base"."fallback" AS "root.pg.fallback"
    FROM
      (
        SELECT
          *
        FROM
          "public"."books"
        WHERE
          (
            (("public"."books"."club_id") = (('3') :: bigint))
            AND (("public"."books"."state") = (('0') :: smallint))
          )
      ) AS "_0_root.base"
      LEFT OUTER JOIN LATERAL (
        SELECT
          coalesce(json_agg("votes"), '[]') AS "votes"
        FROM
          (
            SELECT
              row_to_json(
                (
                  SELECT
                    "_5_e"
                  FROM
                    (
                      SELECT
                        "_4_root.ar.root.votes.or.member"."member" AS "member"
                    ) AS "_5_e"
                )
              ) AS "votes"
            FROM
              (
                SELECT
                  *
                FROM
                  "public"."votes"
                WHERE
                  (("_0_root.base"."id") = ("book_id"))
              ) AS "_1_root.ar.root.votes.base"
              LEFT OUTER JOIN LATERAL (
                SELECT
                  row_to_json(
                    (
                      SELECT
                        "_3_e"
                      FROM
                        (
                          SELECT
                            "_2_root.ar.root.votes.or.member.base"."id" AS "id",
                            "_2_root.ar.root.votes.or.member.base"."name" AS "name"
                        ) AS "_3_e"
                    )
                  ) AS "member"
                FROM
                  (
                    SELECT
                      *
                    FROM
                      "public"."members"
                    WHERE
                      (
                        ("_1_root.ar.root.votes.base"."member_id") = ("id")
                      )
                  ) AS "_2_root.ar.root.votes.or.member.base"
              ) AS "_4_root.ar.root.votes.or.member" ON ('true')
          ) AS "_6_root.ar.root.votes"
      ) AS "_7_root.ar.root.votes" ON ('true')
    ORDER BY
      "root.pg.fallback" ASC NULLS LAST,
      "root.pg.id" ASC NULLS LAST
  ) AS "_9_root";

When executing this statement using EXPLAIN ANALYZE in front of it, it tells me that it took approximately 9217 milliseconds to finish, check the analyze response below
                                                                         QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=12057321.11..12057321.15 rows=1 width=32) (actual time=9151.967..9151.967 rows=1 loops=1)
   ->  Sort  (cost=12057312.92..12057313.38 rows=182 width=37) (actual time=9151.856..9151.865 rows=180 loops=1)
         Sort Key: books.fallback, books.id
         Sort Method: quicksort  Memory: 72kB
         ->  Nested Loop Left Join  (cost=66041.02..12057306.09 rows=182 width=37) (actual time=301.721..9151.490 rows=180 loops=1)
               ->  Index Scan using book_club on books  (cost=0.43..37888.11 rows=182 width=42) (actual time=249.506..304.469 rows=180 loops=1)
                     Index Cond: (club_id = '3'::bigint)
                     Filter: (state = '0'::smallint)
               ->  Aggregate  (cost=66040.60..66040.64 rows=1 width=32) (actual time=49.134..49.134 rows=1 loops=180)
                     ->  Nested Loop Left Join  (cost=0.72..66040.46 rows=3 width=32) (actual time=0.037..49.124 rows=3 loops=180)
                           ->  Index Only Scan using member_book on votes  (cost=0.43..66021.32 rows=3 width=8) (actual time=0.024..49.104 rows=3 loops=180)
                                 Index Cond: (book_id = books.id)
                                 Heap Fetches: 540
                           ->  Index Scan using members_pkey on members  (cost=0.29..6.38 rows=1 width=36) (actual time=0.005..0.005 rows=1 loops=540)
                                 Index Cond: (id = votes.member_id)
                                 SubPlan 2
                                   ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)
                     SubPlan 3
                       ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)
               SubPlan 1
                 ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.001..0.002 rows=1 loops=180)
 Planning Time: 0.788 ms
 JIT:
   Functions: 32
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 4.614 ms, Inlining 52.818 ms, Optimization 113.442 ms, Emission 81.939 ms, Total 252.813 ms
 Execution Time: 9217.899 ms
(27 rows)

With table sizes of:
   relname    | rowcount
--------------+----------
 books        |  1153800
 members      |    19230
 votes        |  3461400
 clubs        |     6410
 users        |        3

This takes way too long. In my previous design, I did not have any indexes, which caused it to be even slower. I have added indexes, but I'm still not quite happy about the fact that I'll have to wait that long. Is there anything that I can improve concerning the data structure or anything?
EDIT
Same select statement, but now using EXPLAIN (ANALYZE, BUFFERS) as suggested:
                                                                         QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=12057321.11..12057321.15 rows=1 width=32) (actual time=8896.202..8896.202 rows=1 loops=1)
   Buffers: shared hit=2392279 read=9470
   ->  Sort  (cost=12057312.92..12057313.38 rows=182 width=37) (actual time=8896.097..8896.106 rows=180 loops=1)
         Sort Key: books.fallback, books.id
         Sort Method: quicksort  Memory: 72kB
         Buffers: shared hit=2392279 read=9470
         ->  Nested Loop Left Join  (cost=66041.02..12057306.09 rows=182 width=37) (actual time=222.978..8895.801 rows=180 loops=1)
               Buffers: shared hit=2392279 read=9470
               ->  Index Scan using book_club on books  (cost=0.43..37888.11 rows=182 width=42) (actual time=174.471..214.000 rows=180 loops=1)
                     Index Cond: (club_id = '3'::bigint)
                     Filter: (state = '0'::smallint)
                     Buffers: shared hit=113 read=9470
               ->  Aggregate  (cost=66040.60..66040.64 rows=1 width=32) (actual time=48.211..48.211 rows=1 loops=180)
                     Buffers: shared hit=2392166
                     ->  Nested Loop Left Join  (cost=0.72..66040.46 rows=3 width=32) (actual time=0.028..48.202 rows=3 loops=180)
                           Buffers: shared hit=2392166
                           ->  Index Only Scan using member_book on votes  (cost=0.43..66021.32 rows=3 width=8) (actual time=0.018..48.187 rows=3 loops=180)
                                 Index Cond: (book_id = books.id)
                                 Heap Fetches: 540
                                 Buffers: shared hit=2390546
                           ->  Index Scan using members_pkey on members  (cost=0.29..6.38 rows=1 width=36) (actual time=0.004..0.004 rows=1 loops=540)
                                 Index Cond: (id = votes.member_id)
                                 Buffers: shared hit=1620
                                 SubPlan 2
                                   ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)
                     SubPlan 3
                       ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)
               SubPlan 1
                 ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.008..0.008 rows=1 loops=180)
 Planning Time: 0.400 ms
 JIT:
   Functions: 32
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 2.060 ms, Inlining 9.923 ms, Optimization 94.927 ms, Emission 68.793 ms, Total 175.702 ms
 Execution Time: 8898.360 ms
(35 rows)

EDIT 2:
Using select * from pg_prepared_xacts; and select * from pg_stat_activity; as suggested in an answer. The first statement does not show any rows, and for the second one I did not notice any old xact_start times, and this was done after previously (yesterday) running VACUUM FULL votes. Running VACUUM FULL votes unfortunately does not fix the problem.
Output of statements:
booky=# select * from pg_prepared_xacts;
 transaction | gid | prepared | owner | database
-------------+-----+----------+-------+----------
(0 rows)

booky=# select * from pg_stat_activity;
 datid  | datname | pid | usesysid | usename  | application_name | client_addr | client_hostname | client_port |         backend_start         |          xact_start           |          query_start          |         state_change          | wait_event_type |     wait_event      | state  | backend_xid | backend_xmin |              query              |         backend_type
--------+---------+-----+----------+----------+------------------+-------------+-----------------+-------------+-------------------------------+-------------------------------+-------------------------------+-------------------------------+-----------------+---------------------+--------+-------------+--------------+---------------------------------+------------------------------
        |         |  31 |          |          |                  |             |                 |             | 2020-04-05 08:41:47.959657+00 |                               |                               |                               | Activity        | AutoVacuumMain      |        |             |              |                                 | autovacuum launcher
        |         |  33 |       10 | postgres |                  |             |                 |             | 2020-04-05 08:41:47.959964+00 |                               |                               |                               | Activity        | LogicalLauncherMain |        |             |              |                                 | logical replication launcher
 169575 | booky   |  48 |       10 | postgres | psql             |             |                 |          -1 | 2020-04-05 10:05:20.847798+00 | 2020-04-05 10:07:47.534381+00 | 2020-04-05 10:07:47.534381+00 | 2020-04-05 10:07:47.534382+00 |                 |                     | active |             |     15265333 | select * from pg_stat_activity; | client backend
        |         |  29 |          |          |                  |             |                 |             | 2020-04-05 08:41:47.959346+00 |                               |                               |                               | Activity        | BgWriterHibernate   |        |             |              |                                 | background writer
        |         |  28 |          |          |                  |             |                 |             | 2020-04-05 08:41:47.959688+00 |                               |                               |                               | Activity        | CheckpointerMain    |        |             |              |                                 | checkpointer
        |         |  30 |          |          |                  |             |                 |             | 2020-04-05 08:41:47.959501+00 |                               |                               |                               | Activity        | WalWriterMain       |        |             |              |                                 | walwriter
(6 rows)

A:   ->  Index Only Scan using member_book on votes  (cost=0.43..66021.32 rows=3 width=8) (actual time=0.024..49.104 rows=3 loops=180)
         Index Cond: (book_id = books.id)
         Heap Fetches: 540

49.104 * 180 = 8839, which is substantially all of your time.  Most likely most of this time is going to IO to read random pages from the table (if you turn on track_io_timings and then do EXPLAIN (ANALYZE, BUFFERS) we would have a definitive answer to that).
If you vacuum "votes", and so get rid of the heap fetches, it would almost surely solve the problem.
   ->  Index Only Scan using member_book on votes  (cost=0.43..66021.32 rows=3 width=8) (actual time=0.018..48.187 rows=3 loops=180)
           Index Cond: (book_id = books.id)
           Heap Fetches: 540
           Buffers: shared hit=2390546

If this was done after the VACUUM was done, then you probably have some kind of long-running transaction being held open, which is preventing VACUUM from doing its job effectively.  Also, hitting 2,390,546 buffers to get 540 row seems incredibly outlandish.  Again, that could be due to some long-open transaction causing massive bloat in your index and/or table.
Does select * from pg_prepared_xacts; show any rows?  Does select * from pg_stat_activity show any old times for xact_start?  If neither of those, then can you do a VACUUM FULL votes and see if that fixes the problem?

A: Thanks to @Lennart, I've added an INDEX which seems to have fixed the issue. It went from around 8900 milliseconds all the way to 35 milliseconds, which is awesome
Index to be created:
CREATE INDEX IX1_VOTES ON VOTES (book_id, member_id)


text:
Q: How to create a TS Type based on an object property and ensure type and property checking? Let's say I have this array of objects:
const formTest = [
   { label: "test", name: "grossSalary" },
   { label: "test", name: "privatePension" },
];

I'd like to build a type based on all name properties. So that formTest array would get me this type:
type FormValues = {
  grossSalary: string;
  privatePension: string;
}

Is there a way to do that and ensure type and properties checking?
For example, this should throw a TS error since invalidProperty doesn't exist on FormValues:
const initialValues: FormValues = {
   grossSalary: "",
   invalidProperty: "",
}

I've tried to use mapped type:
type FormValues = {
   [K in typeof formTest[number]["name"]]: string;
}

but the outcome only checks type, not properties, which doesn't throw an error in the example above.
Is there a way to do that?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Share EntityManagerFactory between webapps? I have two different web applications running on my jetty server, both webapps depend on a jar file which includes my jpa files (like persistence.xml). When i start my server i see both webapps creating an EntityManagerFactory:
13:08:44.191 [main] INFO  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'mypersunit'

and
13:09:05.063 [main] INFO  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'mypersunit'

After the EntityManagerFactory is created it will create the c3p0 connection pool:
Aug 27, 2014 1:08:44 PM org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure

and
Aug 27, 2014 1:09:06 PM org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure

I'm using spring data jpa.
Is it possible to share the EntityManagerFactory related resources like the connection pool between the 2 web applications?
Cause now two EntityManagerFactory and connection pools are created.
Cheers!


text:
Q: Parsing just the content in HTML nodes via Nokogiri in Ruby Suppose I have parsed a line of HTML that is the following...

Go to google!

This is just an example...but how would I go about stripping everything EXCEPT the following:
http://www.google.com
logo.png
Go to google!

Also, is it possible to search for wildcards?

A: If you could make use of some gems it will be a very simple job. I would recommend you Mechanize gem. Reference: http://mechanize.rubyforge.org/Mechanize.html

A: Maybe like this:
doc = Nokogiri::HTML '
Go to google!'
doc.xpath('//*/@href|//*/@src|//*/text()').map(&:to_s)


text:
Q: FBML Subscribe form I'm trying to create a simple subscription form to a Newsletter, but when I try to submit I get this message: Unfortunately, your request could not be processed.
I'm using "FBML Static" app.
Can anyone help me? Here is my code:
{
Subscribe our Newsletter:

<form action="mailto:myemail@mail.com" method="post" enctype="text/plain">

Name:

<input type="text" name="name" value="Your name" />

E-mail:

<input type="text" name="mail" value="Your email" />

<input type="submit" value="Submit">
<input type="reset" value="Reset">

</form> }

A: Taken from the facebook FBML documentation

We are deprecating FBML. On Jan 1, 2012: FBML will no longer be
  supported on Platform. June 1, 2012: FBML apps will no longer work.
  All FBML endpoints are removed. If you are building a new application
  on Facebook.com, please implement your application using HTML,
  JavaScript and CSS. You can use our JavaScript SDK and Social Plugins
  to embedded many of the same social features available in FBML.

As you can see facebook will no longer be supporting FBML.  Further more your problem is to do with the application "Static FBML" - I do not believe this is a facebook issue.


text:
Q: Merge object to a multidimensional array based on a common value I'm looking for a way to merge an object into an array based on a common value. My solution should be dynmic, which causes me a lot of troubles.
Here is an example:
I have a multidimensional array (see codebelow). It contains a column called "Währung", which has numeric values.
0: {AGIMENDO Info Objekt 1: "00000000", Beschreibung Kurz: "Test0", Währung: "200.00", __rowNum__: 1}
1: {AGIMENDO Info Objekt 1: "00000001", Beschreibung Kurz: "Update1", Währung: "456.00", __rowNum__: 2}
2: {AGIMENDO Info Objekt 1: "00000002", Beschreibung Kurz: "Test2", Währung: "12.00", __rowNum__: 3}
3: {AGIMENDO Info Objekt 1: "00000003", Beschreibung Kurz: "Test3", Währung: "549153.00", __rowNum__: 4}
4: {AGIMENDO Info Objekt 1: "00000004", Beschreibung Kurz: "Text", Währung: "1.05", __rowNum__: 5}
5: {AGIMENDO Info Objekt 1: "00000005", Beschreibung Kurz: "13.08.11", Währung: "465.00", __rowNum__: 6}
6: {AGIMENDO Info Objekt 1: "00000006", Beschreibung Kurz: "Test21", Währung: "4594.00", __rowNum__: 7}

For each row, I iterated through each cell and assigned a "type" to each cell that contains a numeric/date value. The codebelow shows that array. Now I want to merge these two arrays based on the common value (for the first array it's "währung" and the second array it's "value). I tried using lodash _.map, _.assign etc. but I don't get the output I want.
0: {type: "number", value: "200.00"}
1: {type: "number", value: "456.00"}
2: {type: "number", value: "12.00"}
3: {type: "number", value: "549153.00"}
4: {type: "number", value: "1.05"}
5: {type: "date", value: "13.08.11"}
6: {type: "number", value: "465.00"}

My target output would look like this (for the first row):
> 0:
>   AGIMENDO Info Objekt1: "00000000"
>   Beschreibung Kurz: "Test0"
>   Währung:
>     Value : "200.00"
>     Type: "number"

How do I achieve this?

A: I am not sure if you want __rowNum__ to be in the out put or not

var arrA = [{'AGIMENDO Info Objekt 1': "00000000", 'Beschreibung Kurz': "Test0", 'Währung': "200.00", '__rowNum__': 1}, {'AGIMENDO Info Objekt 1': "00000001", 'Beschreibung Kurz': "Update1", 'Währung': "456.00", '__rowNum__': 2}];

var arrB = [{type: "number", value: "200.00"}, {type: "number", value: "456.00"}];

var resultat = arrA.map((obj, index)=>(    Object.assign(obj, {'Währung': {
     'Value': arrB[index].value,
     'Type': arrB[index].type
  }})
));

console.log(resultat);

A: You have to loop through all properties and replace value if second array contains object with the same value.

var arr1, arr2, result;

arr1 = [
  {"AGIMENDO Info Objekt 1": "00000000", "Beschreibung Kurz": "Test0", Währung: "200.00", __rowNum__: 1},
  {"AGIMENDO Info Objekt 1": "00000001", "Beschreibung Kurz": "Update1", Währung: "456.00", __rowNum__: 2},
  {"AGIMENDO Info Objekt 1": "00000002", "Beschreibung Kurz": "Test2", Währung: "12.00", __rowNum__: 3},
  {"AGIMENDO Info Objekt 1": "00000003", "Beschreibung Kurz": "Test3", Währung: "549153.00", __rowNum__: 4},
  {"AGIMENDO Info Objekt 1": "00000004", "Beschreibung Kurz": "Text", Währung: "1.05", __rowNum__: 5},
  {"AGIMENDO Info Objekt 1": "00000005", "Beschreibung Kurz": "13.08.11", Währung: "465.00", __rowNum__: 6},
  {"AGIMENDO Info Objekt 1": "00000006", "Beschreibung Kurz": "Test21", Währung: "4594.00", __rowNum__: 7}
];

arr2 = [
  {type: "number", value: "200.00"},
  {type: "number", value: "456.00"},
  {type: "number", value: "12.00"},
  {type: "number", value: "549153.00"},
  {type: "number", value: "1.05"},
  {type: "date", value: "13.08.11"},
  {type: "number", value: "465.00"}
       ]

result = arr1.map(obj=>{
  let copy = Object.assign({}, obj);
  Object.entries(obj).forEach(([key, val])=>{
    let type = arr2.find(el=>el.value === val);
    if (type){
      copy[key] = type;
    }
  })
  return copy;
})

console.log(result)

A: This should work as you could update the json array directly
json_arr = [{"AGIMENDO Info Objekt 1": "00000000", "Beschreibung Kurz": "Test0", "Währung": "200.00", "__rowNum__": 1},
 {"AGIMENDO Info Objekt 1": "00000001", "Beschreibung Kurz": "Update1", "Währung": "456.00", "__rowNum__": 2}]

function update_type(json_arr, column_name) {
    for(var i=0; i<json_arr.length; i++){
        element = json_arr[i][column_name];
        json_arr[i][column_name] = {};
        json_arr[i][column_name]['value'] = element;
        json_arr[i][column_name]['type'] = get_type(json_arr[i][column_name]); /* Here comes your type checking function */
   }
   return json_arr
}
console.log(update_type(json_arr, "Währung"))


text:
Q: How to write double summation in Python I am new to programming and want to write the following equation in Python.

A: basically, it's just a double for loop (nested loop), a for loop within a for loop
def tau(i, J, K):
  total = 0
  for j in J:
    for k in K:
      total += y(i, j)*t(j,k)*x(i,k)
  return total

of course, you can collapse this to a few lines by using reduce and list comprehension. You might want to look those up if this is the first time you're hearing about them
BTW, I'm assuming you want vanilla python. If you're dealing with matrices, please look at the numpy library


text:
Q: PHP - mySQL: Adding Delete, Edit buttons to Table I am having issues adding a Delete and Edit button in two separate columns  on the end of the table.
Here is the code I am currently using to pull the information from the database.
        <?php
        echo "
";
        echo "
Asset ID	Device	Brand	Model	CPU	RAM	Storage	Screen Size	Serial Number	Price	Last Image	Comment	Action
";

        class TableRows extends RecursiveIteratorIterator {
            function __construct($it) {
                parent::__construct($it, self::LEAVES_ONLY);
            }

            function current() {
                return "" . parent::current(). "	";
            }

            function beginChildren() {
                echo "
";
            }

            function endChildren() {
                echo "
" . "\n";
            }
        }

        $servername = "localhost";
        $username = "";
        $password = "";
        $dbname = "laptoplease";

        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $stmt = $conn->prepare("SELECT * FROM laptoplist");
            $stmt->execute();

            // set the resulting array to associative
            $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
            foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
                echo $v;
            }
        }
        catch(PDOException $e) {
            echo "Error: " . $e->getMessage();
        }
        $conn = null;
        echo "
";
        ?>

A: Keep things simple.
<?php
$servername = "localhost";
$username = "hsfcadmin";
$password = "G7qMtJats6bQsRLp";
$dbname = "laptoplease";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->query("SELECT * FROM laptoplist"); // no need to use prepare statement
    $laptops = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

        Asset ID
        Device
        Brand
        Model
        CPU
        RAM
        Storage
        Screen Size
        Serial Number
        Price
        Last Image
        Comment
        Action

<?php if ($laptops) : foreach ($laptops as $laptop) : ?>

        <?= $laptop['asset_id'] ?>
        <?= $laptop['device'] ?>
        <?= $laptop['brand'] ?>
        <?= $laptop['model'] ?>
        <?= $laptop['cpu'] ?>
        <?= $laptop['ram'] ?>
        <?= $laptop['storage'] ?>
        <?= $laptop['screen_size'] ?>
        <?= $laptop['serial_number'] ?>
        <?= $laptop['price'] ?>
        <?= $laptop['last_image'] ?>
        <?= $laptop['comment'] ?>

            <button>Delete</button>
            <button>Edit</button>

<?php endforeach; endif ?>

I am only guessing the name of the columns in your table based off the headers.
Instead of using inline styles, it's better to just use an external stylesheet.


text:
Q: $\mathbb{C}_{\exp}$ is not model complete. I am trying to understand the following proof (Proposition 1.1 here):

Proposition: $\mathbb{C}_{\exp}$ is not model complete.
Proof: If $\mathbb{C}_{\exp}$ is model complete, then every definable set is a projection of
a closed set. Since $\mathbb{C}$ is locally compact, every definable set is $F_σ$. The same is true for the complement, so every definable set is also $G_δ$. But, since $\mathbb{Z}$
is definable, $\mathbb{Q}$ is definable and a standard corollary of the Baire Category Theorem tells us that $\mathbb{Q}$ is not $G_δ$.

How can we say that every definable set is $F_σ$?
Here, $\mathbb{C}_{\exp}$ is the field of complex numbers defined in the language of rings with an additional function for exponentiation.

A: Start with: every definable set is a projection of a closed set.  [This is given, and not proved here.]
In $\mathbb C$, every closed set is a union of countably many compact sets.  The projection of a compact set is compact.  A compact set is closed.
Thus: a projection of a closed set is a countable union of closed sets.
Conclusion: every definable set is an $F_\sigma$.


text:
Q: Load cell amplifier circuit I'm designing a circuit to take two load cells as inputs, and make their sum.
I'd like to know your opinion about the design.
Each cell is connected to one instrumentation amplifier (INA122P).
The supply will be a car battery, so I think there shouldn't be a lot of disturbance.
Please consider that the output will be connected to an ADC, but the cable will be long, so I don't know if I have to take into account some more issues.
It's not written, but the regolator is the 7805, so everything will work at 5 V.
For the summing part I found the AD8271 that seems interesting.
Any idea/correction/suggestion?
It's one of my first designs and I don't know if I miss something important..
Thank you

EDIT:
thank you all for your comments. Here is my updated schematic with your suggestions:
Some questions:
1.by connecting one output to the Vref of the second amplifier, I loose the adjustments (calibration) that I could do on the second load cell, don't I?

*should I take into account some filtering for the supply or it's ok as it is?

*why the ina122 is not a good amplifier? I could use it with the same configuration?
thanks

A: It can be simpler than this if you used a better Instrumentation amp\$^1\$ (IAMP). The 1st IAMP has the reference pin set to the value you need (maybe 2.5V) then, feed the output (pin 6) to the 2nd IAMP's reference input. The output from the 2nd INAMP will then be the sum of the two amplifier load cell signals. No need for the summing amplifier.
Here's the AD620 as an idea but it works with other inamps too: -

The reference pin can set the output to have a standing DC and feeding that pin from the output of the first amp (set to a fixed voltage on REF) produces a summing node.
Also, using pots like that on the INA122 is going to lead to noise issues. The INA122 has only 10mV adjustment\$^1\$ on the ref pin and that, as a fraction of the 5V supply is barely moving the pot wiper half an angstrom! Use a dropper resistor in series with the pot if you insist on using the INA122. The dropper resistor needs to be high enough to produce no more (or thereabouts) 10mV dc on the top connection of the pot.

\$^1\$ The data sheet doesn't seem to state what the REF input range is other than show a diagram that I construed to imply +/-10mV. This however, in retrospect seems unlikely. However, the main thrust of my answer remains the same - you don't need the op amp circuit to add the two signals.


text:
Q: How do I change the "Know More" text and link in Corporate Plus wordpress theme? I'm using a theme called "Corporate Plus" on WordPress.
The problem is, I want to edit a button in the front page which says "Know More", an  element with '#' as a link.
They give no option for editing this in the theme options, and I cannot find any instance of 'know more' in the entire theme folder.
If I open up the site and inspect element, the CSS for the item is shown to be on the file path 'index(72)' > 72nd line of the index file.
I then open up 'view source' and find that sure enough, on line 72, the CSS for the item is written there.
However, the text 'know more' is way further down the page file, and there is no file in the theme folder that seems to have a 'know more' text within it.
How does this happen?
How do I change the 'know more' text?
Note: Yes I'm using the free version, that's why I ask the question. So don't tell me to upgrade. Upgrading gives the option in the 'customize' section of the dashboard.

A: Depending on your theme customization, you could try to add this in function.php file located in your active child theme or theme:
function custom_excerpt_more($more) {
    global $post;
    return 'ID) . '">' . __("Your Read More Link Text", "your_theme_slug") . '';
}
add_filter( 'excerpt_more', 'custom_excerpt_more' );

WP codex: Customizing the Read More

A: Find corporate-plus/acmethemes/hooks/slider-selection.php. Go to about line 109 and change this code:
"Know More" - change to whatever you want.
Change a href="" to a href="your-link"


text:
Q: Setting MySQL unique key or checking for duplicate in application part? Which one is more reliable and has better performance? Setting MySQL unique key and using INSERT IGNORE or first checking if data exists on database and act according to the result?
If the answer is the second one, is there any way to make a single SQL query instead of two?
UPDATE: I ask because my colleagues in the company I work believe that deal with such issues should be done in application part which is more reliable according to them.

A: You application won't catch duplicates.
Two concurrent calls can insert the same data, because each process doesn't see the other while your application checks for uniqueness. Each process thinks it's OK to INSERT.
You can force some kind of serialisation but then you have a bottleneck and performance limit. And you will have other clients writing to the database, even if it is just a release script-
That is why there are such things as unique indexes and constraints generally. Foreign keys, triggers, check constraints, NULL/NIOT NULL, datatype constraints are all there to enforce data integrity
There is also the arrogance of some code monkey thinking they can do better.
See programmers.se: Constraints in a relational databases - Why not remove them completely? and this Enforcing Database Constraints In Application Code (SO)

A: Settings a unique key is better. It will reduce the amount of round-trips to mysql you'll have to do for a single operation, and item uniqueness is ensured, reducing errors caused by your own logic.

A: You definitely should set a unique key in your MySQL table, no matter what you decide.
As far as the other part of your question, definitely use insert ignore on duplicate key update if that is what you intend for your application.
I.e. if you're going to load a bunch of data and you don't care what the old data was, you just want the new data, that is the way to go.
On the other hand, if there is some sort of decision branch that is based on whether the change is an update or a new value, I think you would have to go with option 2.
I.e. If changes to the table are recorded in some other table (e.g. table: change_log with columns: id,table,column,old_val,new_val), then you couldn't just use INSERT IGNORE because you would never be able to tell which values were changed vs. which were newly inserted.


text:
Q: Login configuration in Vaadin/Spring application in JBoss AS 7 I am trying to configure authentication in my Vaadin/Spring application deployed in JBoss AS 7, but I cannot find any documentation on this. I've managed to configure the application so that only authenticated user can use it. Here is a part of my web.xml:
    <security-constraint>
    <display-name>SecureApplicationConstraint</display-name>
    <web-resource-collection>
        <web-resource-name>Vaadin application</web-resource-name>
        <description>The entire Vaadin application is protected</description>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <description>Only valid users are allowed</description>
        <role-name>ROLE_ADMIN</role-name>
        <role-name>ROLE_DOCTOR</role-name>
        <role-name>ROLE_PATIENT</role-name>
    </auth-constraint>
</security-constraint>
<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>file</realm-name>
    <form-login-config>
        <form-login-page>/login.jsp</form-login-page>
        <form-error-page>/loginError.jsp</form-error-page>
    </form-login-config>
</login-config>
<security-role>
    <description/>
    <role-name>ROLE_ADMIN</role-name>
</security-role>
<security-role>
    <description/>
    <role-name>ROLE_DOCTOR</role-name>
</security-role>
<security-role>
    <description/>
    <role-name>ROLE_PATIENT</role-name>
</security-role>

Now the application won't be displayed until the user is authenticated. What I expected was, that the user would be automatically redirected to the login form. I still have to configure the JBoss app server, but cannot find how. I used to work with JBoss 5, where this configuration was done in a login-config.xml file. Does anybody know hoe to configure the authentication REALM in JBoss 7 and make the Vaadin application redirect the user to the login form if he is not authenticated yet? Thanks for your help,
Bye,
Filip

A: First, a couple of questions -
(1)what is happening when you try to access a resource,
and  (2)the security constraint covers/protects anything in the domain.
But your login page is there too.
Would you try limiting the url-pattern to something that wouldn't include the login page, like /myprotectedfolder/* instead?

A: I've found that FORM-based login is tricky in Vaadin, as Vaadin servlet is by default mapped to /*, which means that your login.jsp will also be handled by it. I implemented my login programmatically with the LoginForm, which seems like a nicer integration. However, it's not really what your question is about...
In JBoss AS 7 the configs moved to {jboss}/standalone/configuration/standalone.xml or {jboss}/standalone/configuration/domain.xml, depending on your setup. In most common cases it's standalone.xml. Here's the sample of my database-driven security domain:
<subsystem xmlns="urn:jboss:domain:security:1.0">
        <security-domains>
            <security-domain name="MySecurityDomain">
                <authentication>
                    <login-module code="Database" flag="required">
                        <module-option name="dsJndiName" value="java:jboss/datasources/MyDS"/>
                        <module-option name="principalsQuery" value="SELECT PASSWORD FROM PRINCIPAL WHERE USERNAME=?"/>
                        <module-option name="rolesQuery" value="SELECT r.name, 'Roles' FROM role r, principal_role pr, principal p WHERE p.username=? AND p.user_id=pr.user_id AND pr.role_id=r.role_id"/>
                        <module-option name="hashAlgorithm" value="MD5"/>
                        <module-option name="hashEncoding" value="hex"/>
                    </login-module>
                </authentication>
            </security-domain>
        </security-domains>
    </subsystem>

I hope this helps.


text:
Q: Unable to download driver for RTL8125 2.5GbE 20.04 LTS I recently build my PC and install a fresh Ubuntu on it. The motherboard is:B550 Aorus Elite (no wifi). Unfortunately the internet does not work over ethernet which lead me to believe that it must not have the necessary drivers for the ethernet device.
lshw -C network

*-network UNCLAIMED
description: Ethernet controller
product: RTL8125 2.5GbE Controller
.
.
.
Others have ran into the same problem but they were able to solve it easily since they had access to wifi or tethering. I am actually not sure why my USB tethering does not work. Maybe its because I do not have libmobiledevice as mentioned in this post: https://wiki.archlinux.org/index.php/IPhone_tethering.
For the ethernet driver, I have tried downloading the driver from their website onto a usb drive and install thru: sudo ./autorun.sh but it fails because I need to install build-essential (which I can't do because I dont have internet and I dont know of a easy way to download the .deb files to usb including the dependencies).
Is there any solution to this???
Thanks

A: If you are struggling to get an internet connection, maybe an easier way would be to install a mainline 5.9+ kernel from
Ubuntu kernel PPA
It doesn't require build-essential or other drivers for your device.
Then you can install build-essential and revert to an Ubuntu kernel if you like.


text:
Q: Disabling Buttons after launching an application in Android I currently developing a Content Management app in Kiosk Mode. I pattern this in Surelock Kiosk Lockdown. There's an admin password in order to allow application to run inside the app. The buttons like Home, Back and Recent Task App are disabled in this app. However when I launch a certain app, Back button and Recent Task App are enabled again.
What I'd like to happen is that when the user launch an app, the Recent Task app button and Back button are disabled just like in Content Management App. I am stuck in searching and finding ways on how to do this. Please help me on how to do this. Thank you.
BTW, I'm using this code to disable Buttons:
// Disable Recent Task App
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);

    Log.d("Focus debug", "Focus changed!");

    if (!hasFocus) {
        Log.d("Focus debug", "Lost focus!");

        Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        closeDialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        sendBroadcast(closeDialog);
    }
}

// Disable Volume Buttons and Back Button
private final List hijackKeys = new ArrayList(Arrays.asList(
        KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_UP,
        KeyEvent.KEYCODE_BACK));

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (hijackKeys.contains(event.getKeyCode())) {
        return true;
    } else {
        return super.dispatchKeyEvent(event);
    }
}


text:
Q: Invertible functions on a proper variety It seems well-known that for a smooth proper geometrically integral variety $X$ over a number field $k$, the invertible functions on $\bar{X} := X \times _k \bar{k}$ are the nonzero constants, i.e., $\bar{k}[X]^* = \bar{k}^*$.
Does anyone have a proof or reference of this result? I've tried using the valuative criterion of properness but I couldn't get anywhere.
Furthermore, what can we say about the invertible rational functions $\bar{k}(X)^*$ in this case? Would it also be $\bar{k}^*$?

A: Here's a reference:

Lemma (Stacks 0BUG): Let $k$ be a field. Let $X$ be a proper scheme over $k$.

*

*$A=H^0(X,\mathcal{O}_X)$ is a finite-dimensional $k$-algebra.

*$A=\prod_{i=1,\cdots,n} A_i$ is a product of Artinian local $k$-algebras, one factor for each connected component of $X$.

*If $X$ is reduced, then $A=\prod_{i=1,\cdots,n} k_i$ is a product of fields, each a finite extension of $k$.

...

*If $X$ is geometrically integral, then $A=k$.

This gives that $k[X]=k$ and $\overline{k}[X]=\overline{k}$, and therefore $\overline{k}[X]^*=\overline{k}^*$.
The key facts for the proof are the fact that the pushforward of a coherent sheaf along a proper morphism is coherent (02I5) and the fact that cohomology commutes with flat base extension (02KE). With those in hand, we can play a few little games with $A$ to get the results.

As for your follow-up question regarding $k(X)^*$: no, that's not true. Try taking a look at $X=\Bbb P^n_k$, for instance - you shouldn't find it too hard to compute $k(X)^*$ in that case.


text:
Q: How to differentiate $\frac{\partial}{\partial t} \psi(\vec r-\vec a(t))$ using the chain rule? I am working on a homework problem that requires me to differentiate
$$\frac{\partial}{\partial t} \psi(\vec r-\vec a(t)),$$
where $\vec r$ is the position vector and  $\vec a$ is a vector that varies with time $t$.
I tried using the chain rule and arrived at
$$\frac{\partial}{\partial t} \psi(\vec r-\vec a(t)) = \frac{\partial \psi}{\partial (\vec r- \vec a(t))} \frac{\partial (\vec r- \vec a(t))}{\partial t}.$$
How do I continue?
The answer given was
$$\frac{\partial}{\partial t} \psi(\vec r-\vec a(t))=-\frac{\partial \vec a}{\partial t} \cdot\nabla \psi (\vec r-\vec a(t)).$$
I can't see how my attempt can match this answer. Perhaps I was wrong regarding how to use the chain rule for vector calculus?

A: $r$ is presumably a constant, so your answer and the book's answer agree (up to being sure you understand what the derivative of a function $f:\mathbb{R}^n\to \mathbb{R}$.
Recall that the chain rule for scalar valued functions is
$$
\frac{d}{d{t}}f(x(t))=\nabla f(x(t))\cdot x'(t)
$$
So,
$$
\frac{d}{dt}\psi(\vec{r}-\vec{a(t)})=\nabla\psi(\vec{r}-\vec{a(t)})\cdot -\frac{d\vec{a}(t)}{dt}
$$


text:
Q: iphone TouchJson + ASIHTTPRequest => Android ? +? Is it
iphone TouchJson + ASIHTTPRequest => Android Gson + DefaultHttpClient
Many thanks

A: Yes. If you're actually storing a DefalutHttpClient into a GSON string make sure you nullify any InputStreams or RandomAccessFiles as GSON will not store these.


text:
Q: JSF 2 : can EL do something like this? This works :
<h:outputText value="Active Locale : " />
#{view.locale}

But how can i achieve something like this with EL ?
<h:outputText value="Active Locale Decimal Separator : " />
#{new DecimalFormat(view.locale).decimalFormatSymbols.groupingSeparator}

A: I wonder what you exactly mean with groupingSeparator?
The standard java.text.DecimalFormat has neither a getGroupingSeparator nor groupingSeparator field or method. So I'm a bit in the dark what you're actually trying to achieve. Would you like to have the _ printed? So if the local is en_uk, that the result is "_"?
Regardless of what you exactly want, you can pretty much do everything by building your own EL functon. In EL it would then look like this:
#{my:someFormatting(view.locale)}

someFormatting is then implemented as a static Java method, which you then assign your own namespace ("my" in this case). Look up a tutorial to help you with this if you need that.
There are also a few standard EL functions available to Facelets. These are the JSTL functions defined in the following namespace:
xmlns:fn="http://java.sun.com/jsp/jstl/functions"

Depending on what you exactly need they may be of some help as well.


text:
Q: How to get the email I entered on Proxmox VE setup in the shell? When I login to my Proxmox VE7 host, I'd like to get the email that I entered when I set up Proxmox on installation. Is it possible?
The idea is to automate certbot initialization non-interactively and I would rather use the email I entered previously automatically than asking for the email in my script again.
To clarify, I wish to get the email that I entered here within a shell script:

A: I think you can find your installation email address here :
cat /etc/pve/user.cfg
To get the email address :
EMAIL=`cat /etc/pve/user.cfg | awk '{split($0,a,":"); print a[7]}'`
echo $EMAIL
# test@test.com

Tested on PVE6 and PVE7, but note I've only one user (root).
In the GUI, you can find it under Datacenter / Permissions / Users, double-click on your user, and voila !

A: You can just copy "template" ( /etc/pve/priv/acme/default ) from another proxmox where LE cert is working, to /etc/pve/priv/acme/default and run order certificate.
pvenode acme cert order
I suggest to create mail something like letsencrypt@example.com and have it in the template.
Im using this in ansible role. Get inspired :D
##################
#LETS ENCRYPT CERT
##################

- name: Create empty file /etc/pve/priv/acme/default - workaround for action below
  file:
    path: /etc/pve/priv/acme/default
    owner: root
    group: www-data
    mode: '0600'
    state: touch
  become: true
  tags:
    - hypervizor_proxmox_letsencrypt

- name: Copy template of LE CERT account - default
  template:
    src: lets_encrypt/le_account_default.j2
    dest: /etc/pve/priv/acme/default
    owner: root
    group: www-data
    mode: '0600'
  become: true
  tags:
    - hypervizor_proxmox_letsencrypt

- name: Create LETS ENCRYPT cert
  block:
    - name : Create LETS ENCRYPT cert
      shell: pvenode config set --acme domains="$(hostname -f|tr -d [:space:])" && pvenode acme cert order
  rescue:
    - name: Create LETS ENCRYPT cert failed, trying to rescue probably too much retries
      shell: pvenode config set --acme domains="$(hostname -f|tr -d [:space:])" && pvenode acme cert order --force
      ignore_errors: yes
  tags:
    - hypervizor_proxmox_letsencrypt


text:
Q: What is the difference between gson and json? I see word 'gson' at various places in books related to android , blogs etc. Is it similar to kml in any way or it is different .

A: Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.
The following points highlight why you should be using this library −
Standardized − Gson is a standardized library that is managed by Google.
Efficient − It is a reliable, fast, and efficient extension to the Java standard library.
Optimized − The library is highly optimized.
Support Generics − It provides extensive support for generics.
Supports complex inner classes − It supports complex objects with deep inheritance hierarchies.

A: Gson is Java API,used to convert between Java objects and JSON objects.

A: JSON is a data format that is human-readable and supported by a wide variety of languages.  An example of JSON encoded data:
{
  "name":"John",
  "age":27,
  "interests":["running", "guitar", "foreign movies"],
  "favorites":{
               "color":"blue",
               "book":"Gödel, Escher, Bach: An Eternal Golden Braid"
              }
}

GSON is a java API from Google that converts java objects to their JSON representations and vice-versa.  Installation instructions and sample usage here.

A: GSON is a library that is used to convert serializable java objects to JSON and vice-versa .

A: GSON can use the Object definition to directly create an object of the desired type.
While JSONObject needs to be parsed manually.


text:
Q: Accessing public class from another class in wpf I am working on a wpf application. In this application I received JSON response from server and deserialize it as follow :-
StreamReader streamReader = new StreamReader(jsonResponse.GetResponseStream());
                String responseData = streamReader.ReadToEnd();
                var myData = JsonConvert.DeserializeObject<List<RootObject>>(responseData);
                //UserData ud = new UserData();
                foreach (var val in myData)
                {
                    string res = val.response;
                    if (res == "true")
                    {
                        this.Hide();
                        new lobby().Show();

                    }
                }

My class is as follow :-
public class RootObject
{
    public string response { get; set; }
    public string user_id { get; set; }
    public string username { get; set; }
    public string current_balance { get; set; }
    public string message { get; set; }
    public string oauth_token { get; set; }
    public List<string> lastFiveSpinNumbers { get; set; }

}

When I execute this code everything is ok and after checking response lobby.xaml open. Now I need to access values of RootObject class in lobby.xaml.cs. So I created an instance of this class as follow:-
RootObject cd = new RootObject();
UserNameTextBlock.Text = cd.response;

but cd.response is always null. What may be the reason?

A: You are creating a new instance of RootObject and by default the response property is null.
You can give your lobby class a constructor that takes in a RootObject:
public class lobby
{
   public lobby(RootObject rootObject)
   {
       UserNameTextBlock.Text = rootObject.response;
   }
}

Then in your foreach you could do:
if (res == "true")
{
   this.Hide();
   new lobby(val).Show(); // Pass the root object to the Lobby constructor
}

Note: You may wish to rename lobby to Lobby for your class name, this adheres to better C# naming conventions.


text:
Q: Stokes' theorem to evaluate an integral Let $C$ be the intersection curve of the parabolic sheet $y=x^2$ with the cylinder $x^2+z^2=4$, oriented clockwise when viewed from the positive $y$-axis. Apply Stoke's Theorem to the integral

$$ \int_C 2y\,dx+xz\,dy+z^2\,dz$$ and continue until you have an iterated double integral. Do not solve.

So far I computed the curl to be $(-x,0,z-2)$ , and what I attemped to do was plug $y=x^2$ into the cylinder equation and found the normal to be $(0,1,2z)$ and then found the double integral bounds to be $0<z<\sqrt{4-x^2}$ and $-2<x<2$. Am I on the right track so far? I have no idea if I'm proceeding on the right direction so any pointers would be appreciated.
My final integral that I end up with after plugging everything in is
$$\int_2^2\int_0^\sqrt{4-x^2} \ 2z^2-4z\, dz\, dx.$$


text:
Q: Trying to deform any mesh into a sphere. How to translate the vertex position to lie on a sphere? I am trying to write a deformer script for maya, using the maya API which deforms any mesh into a sphere by translating it's vertices.
What i already have is a deformer which translates every vertex of mesh in the direction of it's normal with the amount specified. This is done using the below equation.
point += normals[itGeo.index()] * bulgeAmount * w * env;

Where, point is the vertex on the mesh. normals[itGeo.index()] is a vector array which represents the normals of each vertex. w and env are to control the weights of the deformation and the envelope.
What this code basically does is, it translates the vertex in the direction of the normal with the amount specified. While this works for a sphere, because a sphere's vertex normals would point at the center. It would not work for other meshes as the normals would not point at the center of the mesh.

    float bulgeAmount = data.inputValue(aBulgeAmount).asFloat();
    float env = data.inputValue(envelope).asFloat();
    MPoint point;
    float w;
    for (; !itGeo.isDone(); itGeo.next())
    {
        w = weightValue(data, geomIndex, itGeo.index());

        point = itGeo.position();

        point += normals[itGeo.index()] * bulgeAmount * w * env;

        itGeo.setPosition(point);
    }

I initially thought changing the direction of translation would solve the problem. As in, if we can find the vector in the direction from the center of the mesh to each vertex and translate it along that direction for an amount specified would solve it. Like so :
point += (Center - point) * bulgeAmount * w * env;

Where, Center is the center of the mesh. But this does not give the desired result. I also would want the deformer to be setup in such a way that the user can input radius "r" value and can also change the amount attribute from 0 to 1 to deform the mesh from it's original state to a spherical one. So that he can choose a value in between if her desires and the mesh would be something between a sphere and it's original shape.
This is my very first post in stackOverflow. I apologize if the format does not follow the community expectations. Any help on this will be greatly appreciated.
Thank You.

A: About the direction:
I think your line :
    point += (Center - point) * bulgeAmount * w * env;
is a good starting point.
But instead of using (Center - point), you should use its opposite, (point-Center) and normalize it before using it. If you don't use a normalized version of this (point-Center) vector, every vertex will be translated to a wrong position.
About your variation between 0.0 (original) to 1.0 (sphere):
If Po is the original position
If Pf is the final position
If d is the original distance between the point Po and the Center C:
d=norm(Center - point) = norm(C-Po)
If Direction is (Center - point)/d (so normalized, as explained above)
What we want:
At r=0.0 your vertex must stay at its original position: Pf = Center + Direction * d
At r=1.0 your vertex must stick to the sphere of radius R: Pf = Center + Direction * R
And if we generalize:
Pf = C + Direction * ( r*R + (1-r)*d )
With d = norm(C-Po)
Direction = (C-Po)/d
R the radius of your sphere
and r a user param between [0.0; 1.0]
Not sure I am clear enough, I'm not used neither to answer here :)
Best


text:
Q: Averaging grade scores in python? for some reason when I average the scores, it's not the right answer i.e usually something like 2 percent or 540, even if that's not what the arithmetic answer would be. Sometimes it works, sometimes it doesn't! As well, code runs in VS, but displays syntax error in IDLE. I have no idea if they're related, but in any case, I have no idea how to fix it. Any help is appreciated!
number=1
quiz=1
mini=1
peer=1
sum=0
while number <51:
    assignment = int(input("What's your grade for assignment "+ str(number) + "?"))
    number = number + 1
    sum += assignment
    assigns = (sum // 500)*100
    assigns2 = round(assigns, 2)
while peer <4:
    peers = int(input("What is your grade for peer assignment "+ str(peer) + "?"))
    peer = peer + 1
    sum += peers
while quiz <11:
    quizzes = int(input("What's your grade for quiz "+ str(quiz) + "?"))
    quiz = quiz + 1
    sum += quizzes
    quiznos = (sum // 100)*100
    quiznos2 = round(quiznos, 2)
while mini <11:
    minisss = int(input("What is your grade for mini-project "+ str(mini) + "?"))
    mini = mini + 1
    sum += minisss
    miniz = (sum // 200)*100
    miniz2 = round(miniz, 2)
final = int(input("What was your score on the final? "))
print("CALCULATING YOUR GRADE...")
gradez = (sum/1200)*100
grader = round(gradez, 2)
print("*******")
print("The total possible points was 1100, and your total is",sum,"points! Your grade is", grader, "percent!")
print("*******")
if grader >= 90:
    print("You've gotten an A!")
elif grader >= 80:
    print("You've gotten a B!")
elif grader >= 70:
    print("You've gotten a C!")
elif grader >= 60:
    print("That's a D, sorry man!")
elif grader >= 0:
    print("You've failed the class...")
print("*******")
print("You got a", assigns2, "percent for assignments!")
print("*******")
print("You got a", quiznos2, "percent for quizzes!")
print("*******")
print("You got a", miniz2, "percent for mini projects!")
print("*******")
examity = (final / 300)*100
examity2 = round(examity, 2)
print("Your final was", final, "out of 300, for a grade of", examity2, end="!")

A: For calculating the percent score for assignments, quizzes, and mini-projects, you are using the same sum variable. This means that your test scores are still added into the sum variable when you are calculating the quiz score, and the quiz and test scores are added into the sum when calculating the mini-projects score, leading to inflated scores. In short, you are using the sum variable in two conflicting ways - both to count up the total number of points and to store the separate sum values for each specific section. If I were you, I would create a separate total points variable and possibly separate sum variables with different names for each section (or reset the sum variable to 0 for each section). Also, I think you may be missing the final score in your total sum when you calculate the student's overall grade, and when calculating that total grade, you divide by 1200 but you say the total max points is 1100, and I'm not really sure how the peer assignments work into the overall score.
For the syntax error, it could be because of the versions of Python you are running in your different environments. If so, it may have to do with the end parameter in your last print statement. This article could be useful: Python SyntaxError: invalid syntax end=''.


text:
Q: Error with addstoredproc method in cfscript I am calling a stored procedure with cfscript, but when I add the addProcResult method to the call, ColdFusion returns the error The specified key, result, does not exist in the structure. Removing the method fixes the error and doesn't effect the results, but I still would like to know why the error appeared. Using <cfstoredproc> and <cfprocparam> doesn't generate the error. I am running CF9. My code is below.
spService = new storedProc();
spService.setDatasource("mydb");
spService.setProcedure("someSP");
spService.setUsername("TaskRunner");
spService.setPassword("password");
spService.addProcResult(name="result",resultset=1);
spService.execute();

A: You'll get this error if your stored procedure actually doesn't return a resultset (perhaps it returns an output parameter--or nothing at all).
Simply remove the call to .addProcResult(), and you'll be fine.


text:
Q: Entity Framework Code First - two Foreign Keys from same table I've just started using EF code first, so I'm a total beginner in this topic.
I wanted to create relations between Teams and Matches:
1 match = 2 teams (home, guest) and result.
I thought it's easy to create such a model, so I started coding:
public class Team
{
    [Key]
    public int TeamId { get; set;}
    public string Name { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}

public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey("HomeTeam"), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey("GuestTeam"), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

And I get an exception:

The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = Match_GuestTeam ]

How can I create such a model, with 2 foreign keys to the same table?

A: It's also possible to specify the ForeignKey() attribute on the navigation property:
[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

A: I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.
The below code is un-tested.
public class Team
{
    [Key]
    public int TeamId { get; set;}
    public string Name { get; set; }

    [InverseProperty("HomeTeam")]
    public virtual ICollection<Match> HomeMatches { get; set; }

    [InverseProperty("GuestTeam")]
    public virtual ICollection<Match> GuestMatches { get; set; }
}

public class Match
{
    [Key]
    public int MatchId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships

A: Try this:
public class Team
{
    public int TeamId { get; set;}
    public string Name { get; set; }

    public virtual ICollection<Match> HomeMatches { get; set; }
    public virtual ICollection<Match> AwayMatches { get; set; }
}

public class Match
{
    public int MatchId { get; set; }

    public int HomeTeamId { get; set; }
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

public class Context : DbContext
{
    ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.HomeTeam)
                    .WithMany(t => t.HomeMatches)
                    .HasForeignKey(m => m.HomeTeamId)
                    .WillCascadeOnDelete(false);

        modelBuilder.Entity<Match>()
                    .HasRequired(m => m.GuestTeam)
                    .WithMany(t => t.AwayMatches)
                    .HasForeignKey(m => m.GuestTeamId)
                    .WillCascadeOnDelete(false);
    }
}

Primary keys are mapped by default convention. Team must have two collection of matches. You can't have single collection referenced by two FKs. Match is mapped without cascading delete because it doesn't work in these self referencing many-to-many.

A: You can try this too:
public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey("HomeTeam"), Column(Order = 0)]
    public int? HomeTeamId { get; set; }
    [ForeignKey("GuestTeam"), Column(Order = 1)]
    public int? GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.
In my case, this simple modification solve the problem.

A: InverseProperty in EF Core makes the solution easy and clean.
InverseProperty
So the desired solution would be:
public class Team
{
    [Key]
    public int TeamId { get; set;}
    public string Name { get; set; }

    [InverseProperty(nameof(Match.HomeTeam))]
    public ICollection<Match> HomeMatches{ get; set; }

    [InverseProperty(nameof(Match.GuestTeam))]
    public ICollection<Match> AwayMatches{ get; set; }
}

public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey(nameof(GuestTeam)), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public Team HomeTeam { get; set; }
    public Team GuestTeam { get; set; }
}

A: This is because Cascade Deletes are enabled by default. The problem is that when you call a delete on the entity, it will delete each of the f-key referenced entities as well.  You should not make 'required' values nullable to fix this problem.  A better option would be to remove EF Code First's Cascade delete convention:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

It's probably safer to explicitly indicate when to do a cascade delete for each of the children when mapping/config. the entity.

A: I know this is pretty old question but coming here in 2021 with EF Core > 3 solution below worked for me.

*

*Make sure to make foreign keys nullable

*Specify default behavior on Delete
public class Match
{
   public int? HomeTeamId { get; set; }
   public int? GuestTeamId { get; set; }

   public float HomePoints { get; set; }
   public float GuestPoints { get; set; }
   public DateTime Date { get; set; }

   public Team HomeTeam { get; set; }
   public Team GuestTeam { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Match>()
                .HasRequired(m => m.HomeTeam)
                .WithMany(t => t.HomeMatches)
                .HasForeignKey(m => m.HomeTeamId)
                .OnDelete(DeleteBehavior.ClientSetNull);

    modelBuilder.Entity<Match>()
                .HasRequired(m => m.GuestTeam)
                .WithMany(t => t.AwayMatches)
                .HasForeignKey(m => m.GuestTeamId)
                .OnDelete(DeleteBehavior.ClientSetNull);
}


text:
Q: Element 'footer' cannot be nested witin element 'html' Pretty simple question. Why does this error occur, and how do i correct it?
running visual studio express 2012 for web.
Thank you in advance

A: The <footer> tag should be within the <body> tag
Hope that helps.

A: Your question is incredibly vague but I can tell you what you're doing wrong.
You probably have your <footer>tag outside of your <body> tag.
<!DOCTYPE HTML>

<html>
    <head>
    </head>

    <body>
    </body>

    <footer>
    </footer>

</html>

So you probably have something that looks similar to that, however it should look like this:
<!DOCTYPE HTML>

<html>
    <head>
    </head>

    <body>
        <footer>
        </footer>
    </body>
</html>


text:
Q: The point of throwing exceptions What's the point of throwing exceptions?
For example I stumbled across this:
static List<Integer> list(int [] a) {
    if (a == null)
        throw new NullPointerException();
        //...

But when you don't throw the nullpointer, you'll also get a nullpointer?
I see this regularly and I wanted to know if this is a good habit to learn?

A: It's better to fail fast. For example the function could do a bunch of stuff before it even references the variable "a" in your example resulting in a lot of unnecessary processing.. It would be best just to fail immediately if you know "a" is null from the very beginning. You could also append a custom error message to the exception as well.

A: The idea behind the THROW is to prevent the error from stopping your program.
If it's a fatal enough error, your program will stop anyway.  But if the program can continue it will, and just let you know that an error occurred.
In many cases, you assign a function to report the error, since you threw it up and know what it is.

A: I always found throwing exceptions to be a matter of design and readability. For example, generally when I design something I prefer to handle errors where they occur. However an equally valid design would be to throw the exception and handle it somewhere else. I have seen some abstractions where generally your flow is something similar to this...
FlowControl -> GenericMethod(catches exceptions and calls methods only) -> PrivateMethods (generally used to do the work, throws exceptions).
You might find a more complete answer here as well: When to catch the Exception vs When to throw the Exceptions?

A: It's possible that the rest of your method will not throw the exception and will instead have some kind of undesirable behavior if you use a null pointer.  In your example, if it's basically a "ToList" wrapper, it might be implemented as:
static List<Integer> list(int[] a)
{
    List<int> ret = new List<int>();
    foreach (int i in a)
        ret.add(i);
    return ret;
}

Instead of throwing, this will simply return an empty list (if I recall correctly at least, I don't think C# throws on null lists used in foreach).  As such, you'll need to include an explicit null check and throw to get your desired behavior.

A: Throwing specific exception means that your application has faced something it shouldn't have. It can be either invalid argument(when someone passes null and current method cannot work with value of null), invalid field state(its value has been changed to some value, which is forbidden for instance current state) and many many more.
Basically when you throw exceptions in a good manner, each person using your e.g. library can preserve its correct flow.


text:
Q: Why are the results different in these two sql's I try to update a column in an table with the following query.  In that case 32000 Rows are updated.
Update Table72D012 t2 set DEFINING_ARGUMENT_ID =
(
SELECT   t3.ID
FROM     Table70t3 t3,
         Table70t1 t1,
         Table70t0 t0,
         Table4 t4
WHERE    t2.Model_id = t4.ID
AND      t3.ID = t1.PARAM_VALUE_BPVA_ID
AND      t3.VALUE_BPAR_ID = t0.ID
AND      t0.KEY='SPECIAL_KEY'
AND      t1.LANGUAGE='en'
AND      t4.Model = t1.name

);

I wanted check result and I used the following query to get the count of relevant ids. I got the result 26500..  Why are the result (count of update and count of select result) different from each other ?
How can I correct the UPDATE query?
ONLY SELECT
SELECT   t3.ID
FROM     Table70t3 t3,
         Table70t1 t1,
         Table70t0 t0,
         Table72D012 t2,
         Table4 t4
WHERE    t2.Model_id = t4.ID
AND      t3.ID = t1.PARAM_VALUE_BPVA_ID
AND      t3.VALUE_BPAR_ID = t0.ID
AND      t0.KEY='SPECIAL_KEY'
AND      t1.LANGUAGE='en'
AND      t4.Model = t1.name

A: First, you need to learn the correct join syntax.  Doing the joins in the WHERE clause is a bad, bad idea.
The reason is simple.  The first query is updating very row in the table, because you have no WHERE clause or other condition.
The second query is returning all the rows that match the query.  In the update version, those rows will get values of NULL.
This is the nice syntax, supported by MS SQL but not by DB2:
Update Table72D012 t2
    set DEFINING_ARGUMENT_ID = t3.ID
    from (SELECT t4.id as t4_id, t3.ID
          FROM Table70t3 t3 join
               Table70t1 t1
               on t3.ID = t1.PARAM_VALUE_BPVA_ID join
               Table70t0 t0
               on t3.VALUE_BPAR_ID = t0.ID join
               Table4 t4
               on t4.Model = t1.name
          WHERE t0.KEY='SPECIAL_KEY' AND t1.LANGUAGE='en'
          ) t
    WHERE t2.Model_id = t4_ID

I don't think DB2 allows the FROM clause in an UPDATE, so you need something like this:
Update Table72D012 t2
    set DEFINING_ARGUMENT_ID =
         (SELECT t3.ID
          FROM Table70t3 t3 join
               Table70t1 t1
               on t3.ID = t1.PARAM_VALUE_BPVA_ID join
               Table70t0 t0
               on t3.VALUE_BPAR_ID = t0.ID join
               Table4 t4
               on t4.Model = t1.name
          WHERE t0.KEY='SPECIAL_KEY' AND t1.LANGUAGE='en' and t2.Model_id = t4.ID
          )
    WHERE exists
         (SELECT t3.ID
          FROM Table70t3 t3 join
               Table70t1 t1
               on t3.ID = t1.PARAM_VALUE_BPVA_ID join
               Table70t0 t0
               on t3.VALUE_BPAR_ID = t0.ID join
               Table4 t4
               on t4.Model = t1.name
          WHERE t0.KEY='SPECIAL_KEY' AND t1.LANGUAGE='en' and t2.Model_id = t4.ID
          )


text:
Q: Exclusion constraint generates: ERROR: operator &&(anyrange,anyrange) is not a member of operator family "range_ops" How come when I try to create an exclusion constraint with GIST,
CREATE TABLE foo (
  a tsrange,
  EXCLUDE (a WITH &&)
);
ERROR:  operator &&(anyrange,anyrange) is not a member of operator family "range_ops"
DETAIL:  The exclusion operator must be related to the index operator class for the constraint.

A: An EXCLUSION constraint with && (Overlaps) needs to be GIST or SP-GIST because the default index is btree and its operator class does not support && (Overlaps). From the docs on Interfacing Extensions To Indexes

GiST indexes are more flexible: they do not have a fixed set of strategies at all. Instead, the "consistency" support routine of each particular GiST operator class interprets the strategy numbers however it likes. As an example, several of the built-in GiST index operator classes index two-dimensional geometric objects, providing the "R-tree" strategies shown in Table 37.4. Four of these are true two-dimensional tests (overlaps, same, contains, contained by); four of them consider only the X direction; and the other four provide the same tests in the Y direction.

You can use the GIST index on an exclusion constraint with,
CREATE TABLE foo (
  a tsrange,
  EXCLUDE USING GIST (a WITH &&)
);

The operator class

*

*btree supports only <, <=, =, >, >=

*gist and sp-gist support far more. And, gin may also one day support being used in an EXCLUSION constraint.

So long as the default GIST operator class is properly defaulted for the type you're using it should work: it's not for inet and cidr
See also,

*

*Why does a CIDR or INET index require me to specify the index's Operator Class?


text:
Q: Calling Objective-C method from C++ function? I picked this up from an answer to a question on how to call objective-c method from C++ method
This runs fine.
MyObject-C-Interface.h
 #ifndef __MYOBJECT_C_INTERFACE_H__
 #define __MYOBJECT_C_INTERFACE_H__ 1

 int MyObjectDoSomethingWith (void *myObjectInstance, void *parameter);

 #endif

MyObject.h
#import "MyObject-C-Interface.h"

@interface MyObject : NSObject
{
     int someVar;
}

- (int) doSomethingWith:(void *) aParameter;
@end

MyObject.mm
 #import "MyObject.h"

 @implementation MyObject

 int MyObjectDoSomethingWith (void *self, void *aParameter)
 {
     return [(id) self doSomethingWith:aParameter];
 }

 - (int) doSomethingWith:(void *) aParameter
 {
     // ... some code
     return 1;
 }

 @end

MyCPPClass.cpp
#include "MyCPPClass.h"
#include "MyObject-C-Interface.h"

int MyCPPClass::someMethod (void *objectiveCObject, void *aParameter)
{
     return MyObjectDoSomethingWith (objectiveCObject, aParameter);
}

NOW if i use something like
MyObject-C-Interface.h
 #ifndef __MYOBJECT_C_INTERFACE_H__
 #define __MYOBJECT_C_INTERFACE_H__ 1

 @class MyObject;

 int MyObjectDoSomethingWith (MyObject* myObjectInstance, void *parameter);

 #endif

My question is instead of using void *myObjectInstance if i use MyObject *myObjectInstance.
it gives this error
 error: expected unqualified-id [1] : @class line and
 error: use of undeclared identifier 'MyObject' [3] in function prototype's line
Help!!!!

A: Link Error:
The link error is to do with the way C++ mangles function names, which C doesn't do. This actually has nothing to do with Objective-C. Specifically,
int MyObjectDoSomethingWith (void *myObjectInstance, void *parameter);

in C or Objective-C (on OSX) is exported to the linker using the name _MyObjectDoSomethingWith. A function with the same name and prototype, compiled with a C++ or Objective-C++ compiler, is known to the linker as __Z23MyObjectDoSomethingWithPvS_. This is called "name mangling", and it encodes the parameter types. Otherwise, function overloading wouldn't work, as functions with different parameter types but the same name couldn't be distinguished. To call a function defined in C from C++, you therefore have to mark the prototype such that C linkage is expected, and it won't mangle the name of that specific overload of the function.
You'll need to tell the C++ compiler to treat it as a C function using extern "C", either like this:
#ifndef MYOBJECT_C_INTERFACE_H
#define MYOBJECT_C_INTERFACE_H

#ifdef __cplusplus
extern "C" {
#endif

int MyObjectDoSomethingWith (void *myObjectInstance, void *parameter);

#ifdef __cplusplus
}
#endif

#endif

or like this:
#ifndef MYOBJECT_C_INTERFACE_H
#define MYOBJECT_C_INTERFACE_H

#ifdef __cplusplus
#define CFUN extern "C"
#else
#define CFUN
#endif

CFUN int MyObjectDoSomethingWith (void *myObjectInstance, void *parameter);

#endif

@class declaration compile error (please do not ask more than one question at a time):
You're trying to #include "MyObject-C-Interface.h", which contains an Objective-C @class forward declaration, from MyCPPClass.cpp, which will be compiled as pure C++. Objective-C directives are mostly syntax errors in C++, so you can't do that. To pass around Objective-C objects in pure C++ or C, you will need to use the id type. You'll need to #include <objc/objc.h> for that, as id isn't defined by default in C or C++.
*Also, please don't prefix your names with two underscores: __ - such names are reserved.*


text:
Q: Using Google's App Invites beta with an android app that has multiple build flavors (production, qa, debug, etc.) I'm trying to use Google's App Invites API with my Android app and according to their guide, I need to put a config file that is generated from the developer console in the app/ directory of the project. My app has multiple build flavors, one for production, qa, and debug. I don't know how this works (since it is a pluging) with multiple build flavors and am hoping that someone can shed some light on this issue.

A: I investigated a bit regarding the google-services plugin and json and found the sources to this plugin.
First things first:
The gradle-plugin google-services that is referenced by classpath and with apply is a build-time plugin only! So it only influences the build-process of your app, but not the runtime-process!
This plugin is only meant as a quickstart-helper to integrating Google-services quickly in your app. Obviously, the process is somewhat convoluted and not documented, so Google should have made it clear what this process does.
In fact, I found the source code for the plugin version com.google.gms:google-services:1.4.0-beta3 and didnt find any specific reference in it regarding appinvites nor did I find any Google API for App Invites! (But maybe it just uses a generic API project with its project id, I didnt try this)
What it does:
The google-services gradle-plugin looks for the mentioned google-services.json file in your app-module. Then it looks for configured settings like project-id's and tracking-id's and such, generated by the Google API developer console into the google-services.json file.
From the settings it found, Android resource values are generated into the following path:
$project.buildDir/generated/res/google-services/$variant.dirName/values/values.xml

For example for a debug-build of your app:
app/generated/res/google-services/debug/values/values.xml

E.g. if you followed the GCM tutorial, the JSON file would include the API project's id as the following android-resource:
<string name="gcm_defaultSenderId">project-id</string>

So this plugin and JSON file are not essential to running or publishing your app, it is just a quickstart helper to generate some basic android-resource files for easier integration of specific Google API features.
Notice in the source code referenced below that the google-services plugin always generates those android-resources for every app-variant that is defined in your app/build.gradle.
If you don't want that, you should use those generated resources in the app-variants you want, and delete the others. Don't forget to remove the google-services plugin apply from app/build.gradle, or else it will be regenerated for all app-variants.
What it does not:
This plugin and JSON-file do NOT directly influence the inner workings of said Google-features for your app!
If you already have followed older tutorials on developer.android.com on how to integrate e.g. GCM or Google Analytics, then you don't even need to integrate either the gradle-plugin google-services or the google-services.json file!
Notice about where I found the sources:
After you integrated the google-services gradle-plugin and when sync your project, Gradle automatically downloads the google-services dependency to a path similar to this (on Windows, you might need to look into your home/.gradle for Linux):
C:\Users\user\.gradle\caches\modules-2\files-2.1\com.google.gms\google-services\1.4.0-beta3\f1580f62e3be313eba041ce19b64fd3f44cf8951\google-services-1.4.0-beta3-sources.jar
If you extract this jar-file, you will find two files:
GoogleServicesPlugin.groovy
GoogleServicesTask.java

which contain the plain source code of the gradle-plugin.
GoogleServicesPlugin.groovy

contains the handling of the app-variants and basic definitions of paths etc.
GoogleServicesTask.java

contains the actual task-definition, look for the following method to see what it really does:
@TaskAction
public void action() throws IOException {
    checkVersionConflict();
    // google-services.json
    if (!quickstartFile.isFile()) {
        getLogger().warn("File " + quickstartFile.getName() + " is missing from module root folder." +
                " The Google Services Plugin cannot function without it.");

        // Skip the rest of the actions because it would not make sense if `quickstartFile` is missing.
        return;
    }

    // delete content of outputdir.
    deleteFolder(intermediateDir);
    if (!intermediateDir.mkdirs()) {
        throw new GradleException("Failed to create folder: " + intermediateDir);
    }

    JsonElement root = new JsonParser().parse(Files.newReader(quickstartFile, Charsets.UTF_8));

    if (!root.isJsonObject()) {
        throw new GradleException("Malformed root json");
    }

    JsonObject rootObject = root.getAsJsonObject();

    Map<String, String> resValues = new TreeMap<String, String>();

    handleProjectNumber(rootObject, resValues);

    JsonObject clientObject = getClientForPackageName(rootObject);

    if (clientObject != null) {
        handleAnalytics(clientObject, resValues);
        handleAdsService(clientObject, resValues);
        handleGoogleAppId(clientObject, resValues);
    } else {
        getLogger().warn("No matching client found for package name '" + packageName + "'");
    }

    // write the values file.
    File values = new File(intermediateDir, "values");
    if (!values.exists() && !values.mkdirs()) {
        throw new GradleException("Failed to create folder: " + values);
    }

    Files.write(getValuesContent(resValues), new File(values, "values.xml"), Charsets.UTF_8);
}

So if the Google-docs don't say which resources are needed for specific Google-features, I would suggest to generate the JSON-file for each relevant buildtype/flavor, see what resources get generated by the plugin and then put those resources manually into their respective src/buildtypeORflavor/res directories.
Delete the references to google-services plugin and the JSON-file after that, and you are done.

A: According to the Google services gradle plugin documentation, the plugin supports different google-services.json per buildType, but not per flavor

[...] as of version 2.0.0-alpha3 of the plugin support was added for
  build types, which would make the following directory structure valid:
app/src/
main/google-services.json
dogfood/google-services.json
mytype1/google-services.json

However, it's not working for me. I'm using 2.0.0-alpha9 and Gradle still complains that it can't find a google-services.json file in root folder

Error:Execution failed for task
  ':app:processProdReleaseGoogleServices'.

File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it.

I've filed a bug: https://code.google.com/p/android/issues/detail?id=200116


text:
Q: How do I handle media metadata in separate class? Im making a mediaplayer using JavaFX Media classes. I made a SongModel class, that incapsulates all metadata from a file and creates Media and MediaPlayer instances.
It looks something like this:
private final StringProperty album =
            new SimpleStringProperty(this, "album");

public String getAlbum(){ return album.get(); }
public void setAlbum(String value){ album.set(value); }
public StringProperty albumProperty() { return album; }

There are also artist, year, title, and albumCover fields that look just like that. Also, MediaPlayer property is exposed as a read-only:
public MediaPlayer getMediaPlayer(){ return mediaPlayer.get(); }
    public ReadOnlyObjectProperty<MediaPlayer> mediaPlayerProperty(){
        return mediaPlayer.getReadOnlyProperty();
    }

I use a MapChangelistener to check if the field is available and then pass it to the handleMetadata method:
private void initializeMedia(String url){

        try {
            final Media media = new Media(url);
            media.getMetadata().addListener(new MapChangeListener<String, Object>(){
                @Override
                public void onChanged(MapChangeListener.Change<? extends String, ? extends Object> ch) {
                    if(ch.wasAdded()){
                        handleMetadata(ch.getKey(), ch.getValueAdded());
                    }
                }
            });

            mediaPlayer.setValue(new MediaPlayer(media));
            mediaPlayer.get().setOnError(new Runnable() {
                @Override
                public void run() {
                    String errorMessage = mediaPlayer.get().getError().getMessage();
                    System.out.println("MediaPlayer error: "+errorMessage);
                }
            });

        }catch(RuntimeException e){
            System.out.println("Construction error: "+e);
        }
    }

    private void handleMetadata(String key, Object value){
        if(key.equals("album")){
            setAlbum(value.toString());
        } else if (key.equals("artist")){
            setArtist(value.toString());
        } if (key.equals("title")){
            setTitle(value.toString());
        } if (key.equals("year")){
            setYear(value.toString());
        } if (key.equals("image")){
            setAlbumCover((Image)value);
        }
    }

Then I made an AbstractView class that provides access to SongModel:
public abstract class AbstractView {
    protected final SongModel songModel;
    protected final Node viewNode;

    public AbstractView(SongModel songModel){
        this.songModel = songModel;
        this.viewNode = initView();
        }

        public Node getViewNode() {
            return viewNode;
        }

        protected abstract Node initView();
}

But when I try to make a MetadataView class, I run into some problems.
Heres how it looks:
public class MetadataView extends AbstractView{
    public Label artist;
    public Label album;
    public Label title;
    public Label year;
    public ImageView albumCover;

    public MetadataView(SongModel songModel) {
        super(songModel);
    }

    @Override
    protected Node initView() {
        artist = new Label();
        artist.setId("artist");
        album = new Label();
        album.setId("album");
        title = new Label();
        title.setId("title");
        year = new Label();
        year.setId("year");

        final Reflection reflection = new Reflection();
        reflection.setFraction(0.2);

        final URL url = getClass().getResource("resources/defaultAlbum.png");
        Image image = new Image(url.toString());

        albumCover = new ImageView(image);
        albumCover.setFitWidth(240);
        albumCover.setPreserveRatio(true);
        albumCover.setSmooth(true);
        albumCover.setEffect(reflection);

        final GridPane gp = new GridPane();
        gp.setPadding(new Insets(10));
        gp.setHgap(20);
        gp.add(albumCover, 0,0,1, GridPane.REMAINING);
        gp.add(title, 1,0);
        gp.add(artist, 1,1);
        gp.add(album, 1,2);
        gp.add(year, 1,3);

        final ColumnConstraints c0 = new ColumnConstraints();
        final ColumnConstraints c1 = new ColumnConstraints();

        c1.setHgrow(Priority.ALWAYS);
        gp.getColumnConstraints().addAll(c0,c1);

        final RowConstraints r0 = new RowConstraints();
        r0.setValignment(VPos.TOP);
        gp.getRowConstraints().addAll(r0,r0,r0,r0);

        return gp;

    }

}

And heres how I call it in the start method:
metaDataView = new MetadataView(songModel);

The problem is that it displays only default metadata without taking it from the songmodel class. I tried running metadata view code together with data handling in one class and everything worked, but when i try to put them in separate classes - it doesnt. Music runs just fine, its just the data thats not displaying. Could anybody tell me what am I missing? How do i make it display metadata from a SongModel class? Ive spent a lot of time on that and dont want it to go to waste.

A: After a day of searching I have found an answer: binds. All I had to do was to bind label property of SongModel class to label property of MetadataView class:
title.textProperty().bind(songModel.titleProperty());
artist.textProperty().bind(songModel.artistProperty());
album.textProperty().bind(songModel.albumProperty());
year.textProperty().bind(songModel.yearProperty());
albumCover.imageProperty().bind(songModel.albumCoverProperty());


text:
Q: On premise: Can not understand how external ips works We have on-prem kubernetes cluster set up with 1 master and 2 workers and metallb with calico networking. Issue is that our application is not opening from outside world.
I can curl external IP from my K8S cluster but can't open the same from browser.
The IP range of master & worker nodes is different from config map address pool -
Master/worker node --> a.b.c.d
Metallb config.yaml -->
apiVersion: v1
kind: ConfigMap
metadata:
namespace: metallb-system
name: config
data:
config: |
address-pools:
- name: default
protocol: layer2
addresses:
- w.x.y.z

I want to know if the address range in metallb config.yaml needs to be same as cluster network? Because when I give kubernetes cluster IP range, the application opens from outside, otherwise not.

A: To use MetalLB, your assign IPs range must be reachable from your cluster network. For example if your cluster IP is 192.168.1.0 /24 you can assign IPs from range 192.168.1.1 - 192.168.1.254
So if you will specify in ConfigMap
...
addresses:
      - 192.168.1.1-192.168.1.254

it will work.
However if you will set cluster IP for example 192.168.1.0/28 you will be able to use addresses only from range 192.168.1.1-192.168.1.14.
Please remember that network configruation and proper ConfigMap is not all. You have to create service(loadbalancer) which will expose your cluster to the world.
Please check this MetalLB tutorial. It contains example of proper MetalLB set.

A: In Layer 2 mode the IP address range you give to metallb should be within the cluster node network range. You need the IP packet originating external to cluster to reach the cluster subnet first. Then the endpoint(probably a router connecting the cluster subnet to external network) that received the traffic destined to the virtual IP assigned by metallb can do an ARP request to figure out the MAC address of the interface on node that currently owns the virtual IP. This is how the external packet gets routed.


text:
Q: If $A, B \in M_n$ be positive definite and $detA \circ B ) = det(AB)$ then $A$ and $B$ are positive diagonal matrices Let $A, B \in M_n$ be positive definite.We define $A \circ B = [{a_{ij}}{b_{ij}}]$.
Suppose  $detA \circ B ) = det(AB)$.
Why are $A$ and $B$ positive diagonal matrices?

A: Hadamard's inequality states that $\det A\le\prod_{i=1}^na_{ii}$ when $A\succeq0$ and in case $A\succ0$, equality holds iff $A$ is diagonal. Oppenheim's inequality states that $(\det A)\prod_{i=1}^nb_{ii}\le\det A\circ B$ when $A,B\succeq0$. Combining the two, the result immediately follows.


text:
Q: How do I open files that are not located inside wine's virtual C drive? I am running winamp using wine. When I am choosing music to open in winamp I can only browse inside wine's C drive but I have all my music on a separate partition. I want to be able to play the music from that partition instead of having to copy it into a folder in wine's virtual C drive.

A: From inside Winamp and other applications running within Wine then you should be able to navigate to the 'Z' drive to access your Ubuntu filesystem.

A: You can do what fluteflute said, or put a link into your ~/Music folder or wine C:\ drive (type ln -s /path/to/partition ~/.wine/pathtocdrive in a terminal and press enter).


text:
Q: Help solving $\oint _{C} \frac{e^{3z}}{(z-\ln{2})^{4}}dz$ I've been trying to solve this problem but have a few questions regarding the final steps. I've been using this formula here $$f^{(n)}(a)=\frac{n!}{2\pi i}\oint _{C} \frac{f(z)}{(z-a)^{n+1}}dz$$
and finding $\oint _{C} \frac{f(z)}{(z-a)^{n+1}}dz = \frac{2\pi i}{n!}f^{(n)}(a) =$ was relatively easy. I am stuck on how to find $f(a)$ however. When integrating do I still include constants so that $f(a)=\frac{1}{27}e^{3a}+c_1a^{2}+c_2a+c_3$? If so how do I find what the constants are? C is the square with vertices $\pm1 \pm i$.

A: You need $\oint _{C} \frac{e^{3z}}{(z-\ln{2})^{4}}dz$.
You have the formula
$$f^{(n)}(a)=\frac{n!}{2\pi i}\oint _{C} \frac{f(z)}{(z-a)^{n+1}}dz.$$
Here $a= \ln 2$, $n=3$ and $f(z)=e^{3z}$. Since $f^{(3)}(z)=27e^{3z}$, then
$$\oint _{C} \frac{e^{3z}}{(z-\ln{2})^{4}}dz=\frac{2\pi i}{3!} \cdot f^{(3)}(\ln 2)=\frac{\pi i}{3}\cdot(27e^{3(\ln 2)})=\frac{\pi i}{3}\cdot(27\cdot 2^3)=72 \pi i.$$


text:
Q: Display Alternate Message (KeyDown) I am creating a simple practice program where if I am going to press "Enter" the first message that will be displayed is "Enter a word", then if I press again "Enter", the second message will be "Hello." I am really new to KeyDown events and I'm just starting to learn it bit by bit. Any help is appreciated.
Here's the code that I've tried so far. But the output is not what I wanted to be.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            if (textBox1.Text == "1")
            {
                MessageBox.Show("Enter a word");

            }

            else if (textBox1.Text == "1")
            {
                MessageBox.Show("Hello");
            }
        }
    }

A: You would really need to save your state before you press Enter key second time. In the following implementation I saved the state in boolean "State" variable, as task only requires there to be 2 possible states.
    private bool State = false;

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            if (State == false)
            {
                MessageBox.Show("Enter a word");
                State = true;
            }

            else if (State == true)
            {
                MessageBox.Show("Hello");
                State = false;
            }
        }
    }

If you had more states, you could use different variable like string or use private method which performs some work to determine next state.

A: Your two if clauses are the same (textBox1.Text == "1"). You shouldn't use a TextBox to track your state, anyway. Try creating a private int time = 1; field in your form source code and check it instead. Don't forget to increase it by 1 every time you find out you pressed "Enter".