text:
Q: Large amount of timecourses in database I have a rather large amount of data (~400 mio datapoints) which is organized in a set of ~100,000 timecourses. This data may change every day and for reasons of revision-safety has to be archived daily.
Obviously we are talking about way too much data to be handled efficiently, so I made some analysis on sample data. Approx. 60 to 80% of the courses do not change at all between two days and for the rest only a very limited amount of the elements changes. All in all I expect much less than 10 mio datapoints change.
The question is, how do I make use of this knowledge? I am aware of concepts like the Delta-Trees used by SVN and similar techniques, however I would prefer, if the database itself would be capable of handling such semantic compression. We are using Oracle 11g for storage and the question is, is there a better way than a homebrew solution?
Clarification
I am talking about timecourses representing hourly energy-currents. Such a timecourse might start in the past (like 2005), contains 8760 elements per year and might end any time up to 2020 (currently). Each timecourse is identified by one unique string.
The courses themselves are more or less boring:
"Course_XXX: 1.1.2005 0:00 5; 1.1.2005 1:00 5;1.1.2005 2:00 7,5;..."
My task is making day-to-day changes in these courses visible and to do so, each day at a given time a snapshot has to be taken. My hope is, that some loss-free semantical compression will spare me from archiving ~20GB per day.

A: Basically my source data looks like this:
Key | Value0 | ... | Value23

to archive that data I need to add an additional dimension which directly or indirectly tells me the time at which the data was loaded from the source-system, so my archive-database is
Key | LoadID | Value0 | ... | Value23

Where LoadID is more or less the time the source-DB was accessed.
Now, compression in my scenario is easy. LoadIDs are growing with each run and I can give a range, i.e.
Key | LoadID1 | LoadID2 | Value0 | ... | Value23

Where LoadID1 gives me the ID of the first load where the 24 values where observed and LoadID2 gives me the ID of the last consecutive load where the 24 values where observed.
In my scenario, this reduces the amount of data stored in the database to 1/30th


text:
Q: writing QList to file So here is a little piece of code for writing some information to file
void Receiver::fileWrite1(int dd, int mm, int yy, int h, int m, int s, QString commandID, QList<int> parameters)
{
    QString v = "Date - ";
    QString w = "Time - ";
    QString port = "Port = ";
    QString x = "Command = ";
    QString y = "Parameters = ";

    QFile file("E:/practica/data.txt");
    if(!file.open(QIODevice::Append)) {
        std::cerr << "Cannot open file for writing: "
                  << qPrintable(file.errorString()) << std::endl;

        return;
    }

    QTextStream out(&file);
    out << v << dd << "/" << mm << "/" << yy << "\r\n";
    out << w << h << " : " << m << " : " << s << "\r\n";
    out << port << c << "\r\n";
    out << x << commandID << "\r\n";
    out << y << << parameters << "\r\n";
    out << "\r\n";
}

The problem is, that "parameters" is dynamic and can change it's amount of members and QTextStream is incompactible with QList

A: *

*You can add the contents of the parameters one by one in the required format by iterating the QList<int>

*Depending on the format you want the parameter contents to apppear, try some thing like this
QTextStream out(&file);
out << v << dd << "/" << mm << "/" << yy << "\r\n";
out << w << h << " : " << m << " : " << s << "\r\n";
out << port << c << "\r\n";
out << x << commandID << "\r\n";
out << y;
//Iterate through your QList and write the contents
for(int i=0;i<parameters.length();i++){
out<< QString::number(parameters.value(i));
out << "Parameter Seperator here";
}

out<< "\r\n";
out << "\r\n";

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to center align How to center align following html in such way that ':' should be at the center & should be listed below one another

Suomething 1 :
Another 111111111111111111

Suomething 2222222222 :
Another 2

CSS:
label{
width:25%;
display: inline-block;
width: 250px;
}

Edit:-added CSS

A: Try this:
label{width:170px;display:inline-block;}

Fiddle here.

A: You might want to use table displays:
http://jsfiddle.net/5NarV/1
CSS
ul {
    display: table;
    padding: 0;
}

li {
    display: table-row;
}

label, span {
    display: table-cell;
    width: 50%;
}

label {
    text-align: right;
}

span {
    padding-left: 0.35em;
}

HTML

        Suomething 1 :
        Another 111111111111111111

        Suomething 2222222222 :
        Another 2

A: It works with this CSS:
li {
    display: block;
}
label {
    width:35%;
    display: inline-block;
    text-align:right;
    float:left;
}

span {
    width:65%;
    float:right;
    display: inline-block;
}

Demo: http://jsfiddle.net/tVSte/

A: Like this
demo
css
ul{
    text-align:center;
}


text:
Q: Epson ePos Javascript SDK: TM-P80 not working over HTTPS I've build an intergration between our online software to Epson EPOS printers. (epos-2.22.0.js) I have successfully connected serveral printers such as tm-t88vi. I've solved much of the SSL problems with generating custom SSL certificates with OpenSSL and install them in the printer through EpsonNet Config. Then add the CA of the certificate in your browser, and https communication is up and running.Still there were some errors and no printing but another hour of googling lead me to this solution:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

to ensure all the insecure requests from the epson js libary are upgraded to secure requests, and our webapplication doesn't throw errors about insecure communication, and is printing!
But how different it is with the TM-P80. First problem i've ran in to, was that my custom certificate wasn't accepted by EsponNet Config. After hours of trying I figured out that it only accepts v1 ssl certificates (created with openssl-1.1). That gives me the gray lock (SSL ok) when opening the EpsonConfig page in Chrome. But still my application won't print with the error:
POST https://192.168.2.180/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000 net::ERR_EMPTY_RESPONSE

If I comment out the "upgrade-insecure-requests" tag, and accept insecure content on the page (Chrome setting) then the request goes to: (http instead of https)
 POST http://192.168.2.180/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000

and the printer is printing, but the whole application is flagged as insecure.
Another test:
http://192.168.2.180/cgi-bin/epos/service.cgi returns a HTTP code 200
https://192.168.2.180/cgi-bin/epos/service.cgi returns a HTTP code 404
So to sum up:

*

*code / certification works with other Epson ePOS printers fully SSL

*certificate works on printer config page (https://192.168.2.180)

*insecure requests to printer lets the printer print

*secure requests are responded with an EMPTY_RESPONSE

Has anyone dealt with this exact problem, or has another idea to try ?
Thanks in advance for your reactions!


text:
Q: Masked out triangle div I have the following code creating a triangle div on the top and bottom of the page:

#arrowdown, #arrowup {
  display: block;
  position: fixed;
  left: 0; right: 0;
  width: 0; height: 0;
  margin: 0 auto;
  border-left: 55px solid transparent;
  border-right: 55px solid transparent;
  z-index: 20;
}

#arrowdown {
  bottom: 0;
  border-bottom: 55px solid rgba(250,250,250,0.75);
}

#arrowup {
  top: 0;
  border-top: 55px solid rgba(250,250,250,0.75);
 }

 #arrowdown .icn, #arrowup .icn {
  display: block;
  position: absolute;
  left: -18px;
  color: #000;
  text-align: center;
  padding: 10px;
  z-index: 25;
}

#arrowdown .icn {bottom: -52px;}
#arrowup .icn {top: -52px;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.1/css/font-awesome.css" rel="stylesheet"/>

<button id="arrowup">

</button>

<button id="arrowdown">

</button>

This creates the triangles with the icns inside. I want the triangles transparent (currently white) with a 2pt blue border around the outside. The examples I found put one element on top of the other, which won't work since it will be seen through the top transparency.

A: You could use opacity.
#arrowup {
  top: 0;
  border-top: 55px solid rgba(250,250,250,0.75);
  opacity: 0.4;
  filter: alpha(opacity=40); /* For IE8 and earlier */
}

http://www.w3schools.com/css/css_image_transparency.asp

A: mix-blend-mode could help you if IE did mind it.

https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/mix-blend-mode

button {
  /* reset */
  background:white;
  border:none;
  /* prepare */
  color:white;
  /* make a CSS stroke */
  text-shadow:0 0 2px blue,0 0 2px blue,0 0 2px blue,0 0 2px blue,0 0 2px blue,0 0 2px blue;/* increase numbers of shadow to erase the blur effect */
  /* do blend it */
  mix-blend-mode:multiply;
}
/* show transparency */
body {
  background:linear-gradient(45deg,lime,turquoise,gray,purple,tomato) yellow;
  background-size:450px 450px;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<button id="arrowdown">

</button><button id="arrowup">

</button>

<button id="arrowdown">

</button><button id="arrowup">

</button>

<button id="arrowdown">

</button>

SVG will do or basic png image with an alt attribute.


text:
Q: Using triggers in Postgres I have two tables A and B in Postgres DB.
Whenever I insert a new row or rows in table A I want to add those updates to table B. If table B is empty, all the news rows inserted in table A will be also added to table B. However, when new rows are inserted in table A and if there is already data in table B, I want to delete all those data from table B before performing insert of the new rows of table A into table B.
So basically, every time when new rows are inserted into table A, corresponding rows should also be added to table B but perform delete operation every time before inserting to table B so that there is no old rows in table B. Table B is intended to hold only newly added rows of table A.
Following is the Postgres script where I have used a trigger.
    CREATE TRIGGER test_one AFTER INSERT ON A
    FOR EACH ROW EXECUTE PROCEDURE addRows();

    CREATE OR REPLACE FUNCTION addRows() RETURNS TRIGGER AS $remove_table$
       BEGIN
          DELETE from B;
          INSERT INTO B(std_id, name) VALUES (new.col1, new.col2);
          RETURN NEW;
       END;
    $remove_table$ LANGUAGE plpgsql;

This trigger function does the job but not all the newly added rows in table A are preserved. I end up with only one row in table B that is the last row of newly inserted data in the table A. To reemphasize, if I insert 10 new rows into table A, table B is expected to have 10 rows added. However, only the 10th row is added into table B which is not the desired result.
Can anybody help me understand what's wrong?

A: Since Postgres 10, pseudo tables are supported through which the inserted set can be accessed in FOR EACH STATEMENT triggers.
Change your function to do an INSERT ... SELECT ... from such a pseudo table.
CREATE
 OR REPLACE FUNCTION addrows
                     ()
                     RETURNS TRIGGER
AS
$$
BEGIN
  DELETE FROM b;

  INSERT INTO b
              (std_id,
               name)
              SELECT col1,
                     col2
                     FROM inserted;
  RETURN NULL;
END;
$$
LANGUAGE plpgsql;

And when creating the trigger, make it a a FOR EACH STATEMENT trigger and add a reference for the pseudo table.
CREATE TRIGGER test_one
               AFTER INSERT ON a
               REFERENCING NEW TABLE AS inserted
               FOR EACH STATEMENT
               EXECUTE PROCEDURE addrows();

db<>fiddle

A: The problem with the trigger is that it fires for each row you insert, not each 'collection' of rows.  With, for example, a batch of 10 inserts, the trigger will fire 10 times always removing all data  in B, leaving you with 1 row - the last to be inserted.
Why create this additional table and duplicate data?  Could you not store an insert date/time or an 'insert batch number' in table A and either query from this or create a view on it?


text:
Q: Why are answers removed from my user page when a question is migrated? Although similar questions have been asked before (such as this one), I would like a bit more background information on why answers are deleted from a user's page when a question is migrated to another site. I can understand why the question itself is removed, but I would feel cheated if I put a lot of thought and effort into an answer only to have it vanish entirely from my user page. Furthermore, even if the question itself is off-topic for Stack Overflow, I may still want to refer back to it and my answer at some point in the future. Is there some technical or philosophical reason why this information is completely removed from user pages?

A: It's removed on your user page on the original site, but it will appear on your user page (if you have one) on the destination site.
If you don't have an account on the destination site, you should be able to make one and then the post will either be automatically linked to your new profile or you can email team@stackoverflow.com to link it for you.

A: When a question is migrated, that means the question didn't belong on the source site in the first place.
Therefore, there's no reason to keep track of the answers on the source site either.
If you have an associated account on the target site, any migrated post will be auto-associated with that account. So the posts don't disappear, they just get moved to where they belong. (If you don't have an account on the target site, if you create one and associate it, the new account will automatically take ownership of the posts.)


text:
Q: ERC1155 Token, How To Create ERC1155 Token I am trying to create a ERC1155 token using openzeppelins's git repositery.
I am trying to write the contract.sol file but I am getting some sort of errors.
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol";

contract KapilERC1155Token is ERC1155 {
    uint256 public constant GOLD = 0;
    uint256 public constant SILVER = 1;
    uint256 public constant THORS_HAMMER = 2;
    uint256 public constant SWORD = 3;
    uint256 public constant SHIELD = 4;

    constructor() ERC1155("https://game.example/api/item/{id}.json") {
        _mint(msg.sender, GOLD, 10**18, "");
        _mint(msg.sender, SILVER, 10**27, "");
        _mint(msg.sender, THORS_HAMMER, 1, "");
        _mint(msg.sender, SWORD, 10**9, "");
        _mint(msg.sender, SHIELD, 10**9, "");
    }
         function getBalance(address account, uint256 id) external {
             _mint(account, id);

      }
    }

Above is my code.
Below is My Error
TypeError: Wrong argument count for function call: 2 arguments given but expected 4.
--> ERC1155token.sol:22:14:
|
22 | _mint(account, id);
| ^^^^^^^^^^^^^^^^^^

I can understand that the _mint() which I am using inside the getbalance() requires 4 arguments and the arguments are.
        address account,
        uint256 id,
        uint256 amount,
        bytes memory data

The _mint() is-
function _mint(
        address account,
        uint256 id,
        uint256 amount,
        bytes memory data
    )

So I tried passing 4 arguments and got new error while passing the third argument.
    function getBalance(address account, uint256 id, uint256 amount) external {
             _mint(account, id, amount);

      }

And the Error I got-
TypeError: Wrong argument count for function call: 3 arguments given but expected 4.
--> ERC1155token.sol:22:14:
|
22 | _mint(account, id, amount);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^

This is not working at all. so What i did. I used the same function defined inside the openzepplin's(https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol) contract which I am inheriting inside my contract.
  function balanceOf(address account, uint256 id) external{
             _mint(account, id);
         }

This gives me another Error see below.
1st-
TypeError: Overriding function is missing "override" specifier.
--> ERC1155token.sol:21:10:
|
21 | function balanceOf(address account, uint256 id) external{
| ^ (Relevant source part starts here and spans across multiple lines).
Note: Overridden function is here:
--> https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol:69:5:
|
69 | function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
| ^ (Relevant source part starts here and spans across multiple lines).

Now I am totally stuck while creating ERC1155 token. I am looking for some help. One last thing I am using remix editor to write my contract.

A: why you _mint inside getBalance function

*

*this is balanceOf function
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
         require(account != address(0), "ERC1155: balance query for the zero address");
         return _balances[id][account];
     }

This function is already inside ERC1155 so you don't need to write it

*You need to write mint function cause it is internal
function mint(
address account,
uint256 id,
uint256 amount
) public {
_mint(account,id,amount,"");
}


text:
Q: conexion de python a oracle alguien sabrá como hacer la conexión de python a oracle ya que intente hacerla con

import cx_Oracle

pero me salio el siguiente error

cx_Oracle.DatabaseError: DPI-1047: 32-bit Oracle Client library cannot
  be loaded: "The specified module could not be found". See
  https://oracle.github.io/odpi/doc/installation.html#windows for help

espero me puedan ayudar.
saludos!

A: Como hecho mi mini receta es para window 7 de 64 bits es

*

*Se descarga Python 2.7 64 bit para Windows, Python

*Se descarga el módulo de conexión de Python a Oracle, Driver

*Puedes probar con el siguiente codigo cambiando por tus valores
import cx_Oracle
conn_str='HR/HR@127.0.0.1:1521/XE'
db_conn = cx_Oracle.connect(conn_str)
cursor = db_conn.cursor()
cursor.execute('SELECT * FROM countries')
registros = cursor.fetchall()
for r in registros:
print str(r)

A: Yo he implementado el siguiente script muchas veces y siempre me ha funcionado. Previo debes descargar el módulo de conexión de Python a Oracle.
import cx_Oracle
ip = '10.8.8.8' #ip
port = 46  #port
SID = 'database'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
connection = cx_Oracle.connect('user', 'password', dsn_tns)


text:
Q: log4cpp stops working properly after sometime I have a log4cpp implementation in a multiple process environment . Logger is configured once during initialization and then is shared among forked processes which server http requests.
During first minute or so , I see the logs rolls perfectly fine at the query per second load( say it runs at 100qps).
After that, the log slows down dramatically. So, I logged pid as well and notice that only one process gets to write to the log for a time duration ( around 10-15 seconds) and then another process starts writing and so on so forth . Processes don't die. They just don't get a chance to write.
This is different from what happens when the server starts . At that time, every other log line is written by a different process. ( Also, I write one-log-line per process at the end of serving the request. )
At this point, I can't think of what could be going wrong.
This is how my log4cpp conf file looks
log4cpp.rootCategory=DEBUG,rootAppender
log4cpp.appender.rootAppender=org.apache.log4cpp.RollingFileAppender
log4cpp.appender.rootAppender.fileName=/tmp/mylogfile.log
log4cpp.appender.rootAppender.layout=org.apache.log4cpp.PatternLayout
log4cpp.appender.rootAppender.layout.ConversionPattern=%d|%p|%m%n

log4cpp.category.http.server.main=INFO,MAIN
log4cpp.additivity.http.server.main=false
log4cpp.appender.MAIN=org.apache.log4cpp.RollingFileAppender
log4cpp.appender.MAIN.maxBackupIndex=10
log4cpp.appender.MAIN.maxFileAge=1
log4cpp.appender.MAIN.append=true
log4cpp.appender.MAIN.fileName=/tmp/mylogfile.log
log4cpp.appender.MAIN.layout=org.apache.log4cpp.PatternLayout
log4cpp.appender.MAIN.layout.ConversionPattern=%d|%p|%m%n

Edit: more updates : Thanks @Botje for your time.
I see that whenever a new child process is created , it is only that process that gets to write to the log. That tells me that all the reference other processes were holding become invalid.
I also tried setting additive property to true. With that , server starts properly writing into the /tmp/myfile.log and then switches to writing into /tmp/myfile.log.1 withing a minute . And then stops writing after a minute.
At that point logs gets directed to stderr which is directed to another log file.
Also,

A: I did notice that the log4cpp FileAppender uses seek to determine the file size before writing log entries. If the file handle is shared between processes that will cause writes to end up at the start of the file instead of the end. Even if you fix that, you still have multiple processes that think they are in charge of log file rotation.
I suggest you have all processes write to a common udp/tcp/Unix socket and designate one process that collects all log entries and actually writes it to a file. You don't have to reinvent the wheel, you can use the syslog protocol and either the system syslog or a copy running in userspace.


text:
Q: Reclaiming mysql empty space... nothing works I've deleted tons of records from my database but I can't reclaim the space....
Use % is at 96%
Your MariaDB connection id is 242212
Server version: 10.1.44-MariaDB-0ubuntu0.18.04.1 Ubuntu 18.04

I have innodb_file_per_table -
MariaDB [(none)]>  show variables like 'innodb_file_per_table';
+-----------------------+-------+
| Variable_name         | Value |
+-----------------------+-------+
| innodb_file_per_table | ON    |
+-----------------------+-------+
1 row in set (0.16 sec)

I have the table with the space I need to reclaim
MariaDB [(none)]> SELECT TABLE_NAME,
    -> ROUND(DATA_LENGTH/1024/1024) AS USED_SPACE_MB,
    -> ROUND(DATA_FREE/1024/1024) AS UNUSED_SPACE_MB
    -> FROM INFORMATION_SCHEMA.TABLES
    -> WHERE ROUND(DATA_FREE/1024/1024) > 1000
    -> ORDER BY UNUSED_SPACE_MB;
+--------------+---------------+-----------------+
| TABLE_NAME   | USED_SPACE_MB | UNUSED_SPACE_MB |
+--------------+---------------+-----------------+
| correlations |         65720 |           54103 |
+--------------+---------------+-----------------+
1 row in set (0.01 sec)

But when I run
'optimize table correlations'
.... it does nothing.
I even ran mysqlcheck -o
....it does nothing.
Use % stays at 96%.
Is there something I'm missing?   I'd appreciate any suggestions.  Thanks!
Adding config info...
[mysqld]
innodb-defragment=1
#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
innodb_buffer_pool_size = 4G
skip-name-resolve
max_heap_table_size= 128M
tmp_table_size= 128M

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address            = 127.0.0.1

#
# * Fine Tuning
#
key_buffer_size         = 16M
max_allowed_packet      = 16M
thread_stack            = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam_recover_options  = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10

#
# * Query Cache Configuration
#
query_cache_limit       = 1M
query_cache_size        = 16M

A: Down to 4% disk space?  This will be tricky.
Find the largest files on the system; sort by size; see if any other files (logs, other apps, etc) can be freed up.

*

*Find out how big ibdata1 is.

*Run SHOW TABLE STATUS.  (Show me this, so I can explain what the rest of the steps mean.)

*Figure out whether some tables are "file-per-table" and some are in ibdata1.

*Figure out how much free space is in ibdata1.  Let'c call this x.

*For each table that is not in ibdata1, but is small enough (data_free+index_free) to fit into x, move it into ibdata1 -- but start with the one with the largest Data_free.  Do not bother will tables with free space below 8MB.  (This involves a SET and an ALTER.)

*For each of the rest of the tables with more than 8MB free and not currently in ibdata1, rebuild (ALTER).  Start with the smallest and work your way up, until their is not enough free disk to do the next table.

If that won't suffice then:  Get a bigger machine, dump and reload.
For the future:  You should worry about disk space when 50% full (not 96%).

A: You are not counting the index pages.
You have this in your diskspace query
SELECT
    TABLE_NAME,
    ROUND(DATA_LENGTH/1024/1024) AS USED_SPACE_MB,
    ROUND(DATA_FREE/1024/1024) AS UNUSED_SPACE_MB
    FROM INFORMATION_SCHEMA.TABLES
    WHERE ROUND(DATA_FREE/1024/1024) > 1000
    ORDER BY UNUSED_SPACE_MB
;

What you should have is this:
SELECT
    TABLE_NAME,
    ROUND((DATA_LENGTH+INDEX_LENGTH)/1024/1024) AS USED_SPACE_MB,
    ROUND(DATA_FREE/1024/1024) AS UNUSED_SPACE_MB
    FROM INFORMATION_SCHEMA.TABLES
    WHERE ROUND(DATA_FREE/1024/1024) > 1000
    ORDER BY UNUSED_SPACE_MB
;

or this (to see the Index Pages Separately
SELECT
    TABLE_NAME,
    ROUND(DATA_LENGTH/1024/1024) AS USED_DATA_MB,
    ROUND(INDEX_LENGTH/1024/1024) AS USED_INDEX_MB,
    ROUND((DATA_LENGTH+INDEX_LENGTH)/1024/1024) AS USED_SPACE_MB,
    ROUND(DATA_FREE/1024/1024) AS UNUSED_SPACE_MB
    FROM INFORMATION_SCHEMA.TABLES
    WHERE ROUND(DATA_FREE/1024/1024) > 1000
    ORDER BY UNUSED_SPACE_MB
;

Perhaps seeing the Data and Index Pages Together will clarify space differences you are seeing (NOTE : If your table has no secondary indexes and only a PRIMARY KEY, Index Space Usage will be zero(0)).
Since you already ran optimize table correlations; there should be a .ibd file. That will at least verify that innodb_file_per_table applies to the correlations table;


text:
Q: TokenMismatchException in laravel 5.4 with image upload I'm building a Laravel 5.4 application that let's you upload an image to each registered entry. I was using the intervention image package but realized I needed a way to enable image cropping and rotation (iphone images are rotated when uploaded for some reason), so I decided to use the jquery plugin Slim Cropper. I've added the necessary files to my code but can't succesfully upload an image.
Slim Cropper offers two ways to upload an image: through a regular form which gives me the "TokenMismatchException in VerifyCsrfToken.php (line 68)" after submitting, and an ajax form that simply shows a "cannot upload" message. I've tried both ways with different changes but can't get it to work. All my classes/controllers check for authentication, and I have tried sending the csrf token every way I could think of, all show the same error.

UPDATE: As per the suggestions in the comments, I've moved csrf token right after <form>, I've updated the input file names to match those from the example and attempted to debug through middleware with no error messages whatsoever. The TokenMismatchException error is no longer an issue, but once the form is submitted I get the error Constant expression contains invalid operations in Slim.php (line 106) for public static function saveFile($data, $name, $path = public_path('/uploads/mascotas-img/'), $uid = true). Still have no fix for this.
Here's the code:
Routes
Route::post('/mascotas/avatar', 'PetsController@avatar');

Pets Controller
use App\Slim;
public function avatar(Request $request)
{
    if ( $request->avatar )
    {
        // Pass Slim's getImages the name of your file input, and since we only care about one image, postfix it with the first array key
        $image = Slim::getImages('avatar')[0];
        $mascota_num = $image['meta']->petId;

        // Grab the ouput data (data modified after Slim has done its thing)
        if ( isset($image['output']['data']) )
        {
            // Original file name
            $name = $image['output']['name'];
            //$name = $request->input('mascota_num');

            // Base64 of the image
            $data = $image['output']['data'];

            // Server path
            $path = public_path('/uploads/mascotas-img/');

            // Save the file to the server
            $file = Slim::saveFile($data, $name, $path);

            // Get the absolute web path to the image
            $imagePath = public_path('/uploads/mascotas-img/' . $file['name']);

            DB::table('mascotas')
                ->where('num',$mascota_num)
                ->update(['foto' => $imagePath]);

            //$mascota->foto = $imagePath;
            //$mascota->save();
        }
    }

    return redirect()->back()->with('success', "User's profile picture has been updated!");
}

Slim Class
namespace App;

abstract class SlimStatus {
    const Failure = 'failure';
    const Success = 'success';
}

class Slim {

    public static function getImages($inputName = 'slim') {

        $values = Slim::getPostData($inputName);

        // test for errors
        if ($values === false) {
            return false;
        }

        // determine if contains multiple input values, if is singular, put in array
        $data = array();
        if (!is_array($values)) {
            $values = array($values);
        }

        // handle all posted fields
        foreach ($values as $value) {
            $inputValue = Slim::parseInput($value);
            if ($inputValue) {
                array_push($data, $inputValue);
            }
        }

        // return the data collected from the fields
        return $data;

    }

    // $value should be in JSON format
    private static function parseInput($value) {

        // if no json received, exit, don't handle empty input values.
        if (empty($value)) {return null;}

        // The data is posted as a JSON String so to be used it needs to be deserialized first
        $data = json_decode($value);

        // shortcut
        $input = null;
        $actions = null;
        $output = null;
        $meta = null;

        if (isset ($data->input)) {
            $inputData = isset($data->input->image) ? Slim::getBase64Data($data->input->image) : null;
            $input = array(
                'data' => $inputData,
                'name' => $data->input->name,
                'type' => $data->input->type,
                'size' => $data->input->size,
                'width' => $data->input->width,
                'height' => $data->input->height,
            );
        }

        if (isset($data->output)) {
            $outputData = isset($data->output->image) ? Slim::getBase64Data($data->output->image) : null;
            $output = array(
                'data' => $outputData,
                'width' => $data->output->width,
                'height' => $data->output->height
            );
        }

        if (isset($data->actions)) {
            $actions = array(
                'crop' => $data->actions->crop ? array(
                    'x' => $data->actions->crop->x,
                    'y' => $data->actions->crop->y,
                    'width' => $data->actions->crop->width,
                    'height' => $data->actions->crop->height,
                    'type' => $data->actions->crop->type
                ) : null,
                'size' => $data->actions->size ? array(
                    'width' => $data->actions->size->width,
                    'height' => $data->actions->size->height
                ) : null
            );
        }

        if (isset($data->meta)) {
            $meta = $data->meta;
        }

        // We've sanitized the base64data and will now return the clean file object
        return array(
            'input' => $input,
            'output' => $output,
            'actions' => $actions,
            'meta' => $meta
        );
    }

    // $path should have trailing slash
    public static function saveFile($data, $name, $path = public_path('/uploads/mascotas-img/'), $uid = true) {

        // Add trailing slash if omitted
        if (substr($path, -1) !== '/') {
            $path .= '/';
        }

        // Test if directory already exists
        if(!is_dir($path)){
            mkdir($path, 0755);
        }

        // Let's put a unique id in front of the filename so we don't accidentally overwrite older files
        if ($uid) {
            $name = uniqid() . '_' . $name;
        }
        $path = $path . $name;

        // store the file
        Slim::save($data, $path);

        // return the files new name and location
        return array(
            'name' => $name,
            'path' => $path
        );
    }

    public static function outputJSON($status, $fileName = null, $filePath = null) {

        header('Content-Type: application/json');

        if ($status !== SlimStatus::Success) {
            echo json_encode(array('status' => $status));
            return;
        }

        echo json_encode(
            array(
                'status' => $status,
                'name' => $fileName,
                'path' => $filePath
            )
        );
    }

    /**
     * Gets the posted data from the POST or FILES object. If was using Slim to upload it will be in POST (as posted with hidden field) if not enhanced with Slim it'll be in FILES.
     * @param $inputName
     * @return array|bool
     */
    private static function getPostData($inputName) {

        $values = array();

        if (isset($_POST[$inputName])) {
            $values = $_POST[$inputName];
        }
        else if (isset($_FILES[$inputName])) {
            // Slim was not used to upload this file
            return false;
        }

        return $values;
    }

    /**
     * Saves the data to a given location
     * @param $data
     * @param $path
     */
    private static function save($data, $path) {
        file_put_contents($path, $data);
    }

    /**
     * Strips the "data:image..." part of the base64 data string so PHP can save the string as a file
     * @param $data
     * @return string
     */
    private static function getBase64Data($data) {
        return base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
    }

}

Picture submit form (tokenmismatch error)
<form action="{{ url('mascotas/avatar') }}" method="post" enctype="multipart/form-data">

num }}">
            @if ( $mascota->foto )
                foto) }}" />
            @endif
            <input type="file" name="avatar" required />
            {{ csrf_field() }}

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-red">Cambiar Foto</button>

</form>

Alternate submit form (error message)

num }}">
        @if ( $mascota->foto )
            foto) }}" />
        @endif
        <input type="file" name="avatar" />

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-red">Cambiar Foto</button>

Slim image cropper website with examples http://slimimagecropper.com/

My original upload form through laravel image intervetion, this works with no problems at upload, but would very much like to replace with one of the above.
<form enctype="multipart/form-data" action="{{ url('mascotas/foto') }}" method="POST">

        foto) }}">

        <input type="file" name="foto">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <input type="hidden" name="mascota_num" value="{{ $mascota->num }}">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-red">Cambiar Foto</button>

</form>

Thanks for any help!

A: You should include the {{ csrf_field() }} on each of your forms, for the Ajax one, you could send the token as header.


text:
Q: Force a file to overwrite instead of appending the filename I've got an application running is OS X that won't overwrite a file with the same filename. It will only append the filename with a 'space 1'. If I write a file more than once I get something like this:
* filename.jpg
* filename 1.jpg
* filename 2.jpg

What I need is to only ever have the newest file without the extra space and number.
Is there anyway around this? Perhaps an applescript running in the folder?


text:
Q: ¿Cómo hacer un autocomplete en el control de la lib ngx-intl-tel-input? Estoy usando un ngx-intl-tel-input, para formatear un número de teléfono con los códigos de área de cada país. Lo hice funcionar correctamente y toda va bien, pero ahora quiero poder agregar un autocomplete con ayuda de material angular mat-autocomplete (https://material.angular.io/components/autocomplete/overview), es decir que al escribir un número de télefono empuje el numero encontrado en mi control ngx-intl-tel-input(https://www.npmjs.com/package/ngx-intl-tel-input). ¿Creen que esto sea posible? ¿o es muy loco de mi parte?
Claro al ser una libreria tiene sus limitantes y lo sé ¿pero si se pudieran saltar esas limitantes sería posible?
Les dejo el proyecto en stackblitz, en donde estaba intentando hacer lo dicho con formularios reactivos. (https://stackblitz.com/edit/angular-ivy-zhb7dh?file=src%2Fapp%2Fapp.component.html)
Porfavor si alguien pudiese ayudarme. Gracias!


text:
Q: Bottom Toolbar doesnt show in Fragment with Grid View i have a massive problem with my second toolbar which should be on the bottom of my View. It just doenst show up, i spent hours trying to make it work already but cant figure out why the scrollable GridList in my Fragment overshadows it...
Take a look at my main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<!-- This DrawerLayout has two children at the root  -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- This LinearLayout represents the contents of the screen  -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/main_container"
        >
        <!-- The ActionBar displayed at the top -->
        <include
            layout="@layout/toolbar_top"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- The main content view where fragments are loaded -->
        <FrameLayout
            android:id="@+id/flContent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/background_dark"/>

        <!-- The Toolbar displayed at the bottom -->
        <include
            layout="@layout/toolbar_bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <!-- The navigation drawer that comes from the left -->
    <!-- Note that `android:layout_gravity` needs to be set to 'start' -->
    <android.support.design.widget.NavigationView
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        android:id="@+id/nvView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/black_90percent"
        app:menu="@menu/drawer_view"
        app:itemTextAppearance="@style/TextAppearance.AppCompat.Subhead"
        app:itemIconTint="@drawable/drawer_item"
        app:itemTextColor="@drawable/drawer_item"
        app:itemBackground="@drawable/drawer_item_background"
        app:elevation="16dp"
    />
</android.support.v4.widget.DrawerLayout>

And here is my animation_fragment.xml (thats the layout of the fragment that gets loaded into the main_activity.xml)
<?xml version="1.0" encoding="utf-8"?>

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.pymdev.pym.AnimationFragment">

        <GridView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:horizontalSpacing="4dp"
            android:numColumns="2"
            android:verticalSpacing="4dp" />

        <TextView
            android:id="@android:id/empty"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center" />

    </FrameLayout>

I want to create something like this where you have a second tool on the bottom for controls. :
I am very close already, the grid with images works and all the styling of the scrollable items is good. The only problem is that bottom toolbar. Please help,  i am totally stuck here.

A: Try RelativeLayout instead
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/main_container">
        <!-- The ActionBar displayed at the top -->
        <include
            layout="@layout/toolbar_top"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"/>

        <!-- The main content view where fragments are loaded -->
        <FrameLayout
            android:id="@+id/flContent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/background_dark"
            android:layout_below="@id/toolbar_top"
            android:layout_above="@id/toolbar_bottom"/>

        <!-- The Toolbar displayed at the bottom -->
        <include
            layout="@layout/toolbar_bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"/>

    </RelativeLayout>

A: use layout weights for the height of your grid view:
<!-- This LinearLayout represents the contents of the screen  -->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/main_container"
    >
    <!-- The ActionBar displayed at the top -->
    <include
        layout="@layout/toolbar_top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- The main content view where fragments are loaded -->
    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@android:color/background_dark"/>

    <!-- The Toolbar displayed at the bottom -->
    <include
        layout="@layout/toolbar_bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

This way your grid view won't use the entire screen.


text:
Q: org.codehaus.groovy.grails.validation.exceptions.ConstraintException is not supporting in Grails 4.0.8? I am in upgrading process from Grails 2.0.8 to Grails 4.0.8.
Supporting gradle version: Gradle 5.1.1
What would be replacement for importing package of
import org.codehaus.groovy.grails.validation.exceptions.ConstraintException

?
Because this package is not being supported in upgraded project?
Moreover,
Is  org.codehaus.groovy pacakge has been obsolete in Grails 4.0.x?

A:
Because this package is not being supported in upgraded project?

The package does not exist in Grails 4.

Moreover, Is org.codehaus.groovy pacakge has been obsolete in Grails
4.0.x?

Yes.  We removed the org.codehaus... packages from Grails quite a few years ago.


text:
Q: Should I use composite key or primary key from other table We have a Education Project which has following entities :

*

*Domain (e.g. Programming, UI/UX, AI, ML), each Domain has 5 Levels (1, 2, 3, 4, 5)

*Building Blocks - which are like small topics e.g. java, multi-threading, loops, prototyping, user interviews. Each Level in the Domain is build of multiple Building Blocks.

*Learning Asset (is like a link to study a concept - it can be associated with multiple Building Blocks) and further these Learning Assets are mapped to a particular Domain -> Level -> Building Block
These are the tables that we have thought of :
Domain
|    id     |      Name          |
|    10     |      UIUX          |
|    11     |      Programming   |
|    12     |      AI            |

Building Blocks
|    id    |      Name               |
|    1     |       loops             |
|    2     |     multi-threading     |
|    3     |     user-interview      |

Then we store mapping of Building Blocks to a Domain - Level
Domain-Level-BuildingBlocks Mapping Table
|  DLB_Id    |       domainId   |   level      |   buildingBlockId
|    100     |        11        |    1         |    1
|    200     |        11        |    2         |    2
|    300     |        10        |    1         |    3

in this table - (domainId, level, buildingBlockId) form a composite key
Learning Asset Table
|    id    |       Name                 |   link
|    1     |      Loop Notes            |    https://a.com
|    2     |       Operators            |    https://b.com
|    3     |       Process and Threads  |    https://c.com

A Learning Asset can be connected to multiple building blocks
Learning Asset -BuildingBlocks Mapping Table
|    id    |       learningAssetId  |     buildingBlockId
|    1     |        1               |        1
|    2     |        2               |        1
|    3     |        3               |        2

Now the Admin can select if a Learning Asset is applicable in Domain-Level-BuildingBlock combination so
Learning Asset-Domain-Level-BuildingBlocks Mapping Table (Table A)
|    id    |       learningAssetId  |   domainId   |   level      |   buildingBlockId
|    1     |        1               |      11      |    1         |      1
|    2     |        2               |      11      |    1         |      1

in this table - (domainId, level, buildingBlockId) form a composite key
My question was in the above table :  should I again store (domainId, level, buildingBlockId) or should I use their primary key DLB_id from the Domain-Level-BuildingBlocks table
something like this :
Learning Asset-Domain-Level-BuildingBlocks Mapping Table (Table B)
|    id    |       learningAssetId  |   DLB_Id
|    1     |        1               |      100
|    2     |        3               |      200

*

*My question is whether to use Table A or Table B

*If Table B is the correct way should I generate DLB_Id as string by combining domainId + "-" + level + "-" + buildingBlockId instead of using Auto-increment Integet Primary Keys. Will the indexing on the generated string be as efficient as the Auto-increment Integer Primary Key.  The reason for generating the string is that when we need to fetch the Learning Assets that belong to a Domain-Level-BuildingBlock combination I don't need to use the Domain-Level-BuildingBlocks Mapping Table - rather I can directly look up the generated string Id in the Learning Asset-Domain-Level-BuildingBlocks Mapping Table
Learning Asset-Domain-Level-BuildingBlocks Mapping Table (Table C)
|    id    |       learningAssetId  |         DLB_Id   (as generated string)
|    1     |        1               |        '11-1-1'
|    2     |        3               |        '11-2-2'

i.e. Table B or Table C ?
Thank you

A: In general, a mapping table does not need its own id.  Instead, the PRIMARY KEY should be a composite key with the 2 (or more) column-ids referencing the tables that are being related in a many-to-many relationship.
For a 1-to-many relationship, a mapping table is unnecessary.
Your "DLB" smells like a "Relation", hence the above comments apply.  If, instead, you can reasonably think of it as an "Entity", then it would have its own id.  And it would probably have more columns of attributes of the "entity".


text:
Q: Mathematical representation of ++a We can define a++ as
a = a + 1;

Which is self-explaining that it makes a copy of a then adds 1 to it and puts the result in a.
But can we define ++a the same way? Maybe the answer is very simple but I'm  unaware of it.

A: a++ and ++a have differences in precedence.
- a++: you evaluate a before a is incremented;
- ++a: you increment a before it is evaluated or used

A: The difference is:
int a = 1;
int b = ++a;
// Now a == 2 and b == 2

int c = 1;
int d = c++;
// Now c == 2 and d == 1

The difference is in the returned value of the operation.


text:
Q: Cross site forgery on AJAX service I'm a little confused as to how to prevent cross site forgeries. Still.  I know there is a wealth of information out there, but I'm confused.
In Steven Anderson's post he describes a form like this:
<body onload="document.getElementById('fm1').submit()">
    <form id="fm1" action="http://yoursite/UserProfile/SubmitUpdate" method="post">
        <input name="email" value="hacker@somewhere.evil" />
        <input name="hobby" value="Defacing websites" />
    </form>
</body>

On someone else's site.
The solution given is a "anti-forgery" token, generated by the server, that is POST-ed back to with any requests in a hidden form.  That's cool, but what is to stop the hacker just downloading the form page, extracting the token and POSTing it?
My application for this is:  On the sign-up for to my website I'd like a AJAX function that sends the currently entered Username to the server which should respond "True/False"  if it is available or not.  This happens onKey so the user can pick a username that has not been used already.  The Submit button will enable when all the conditions for "new user" are met.
Clearly this is an opportunity for a hacker to use the service to "test" lots of usernames to see if they available - I know it's not exactly internet-banking level sort of risk, but I'd still like to service only requests from my application, not a hacker.
Any ideas how about these queries?
UPDATE:
So in my scenario.  I generate a Token (say some hashed value of the client's IP address) and the service expects to receive this back if it is give the information about whether the username is available or not.
-- The problem remains, someone off domain simply calls the service e.g. /generateToken   This looks at the client's IP... could be a hacker who knows.
Returns
{ token: 4uru32br }

Which is then submitted to the /isUsernameAvailable?token=4uru32br&partialUsername=usernam
Where does that get me?

A:
what is to stop the hacker just downloading the form page, extracting the token and POSTing it?

The same-origin policy, that's what.

I'd like a AJAX function that sends the currently entered Username to the server which should respond "True/False" if it is available or not.

That's a user-enumeration vulnerability right there.

Any ideas how about these queries?

Here's your new process:

*

*Use email addresses for usernames.

*Use CAPTCHA to prevent automation on registration forms.
Email username does not exist:
Show "success" message. Send email to address with one-time link. Register user after returns to your site with that link.
Email username does exist:
Show "success" message. Send email to that address with message saying "someone is trying to create an account with this address but it already exists".

A: You're mixing up CSRF and user enumeration.

The solution given is a "anti-forgery" token, generated by the server,
  that is POST-ed back to with any requests in a hidden form. That's
  cool, but what is to stop the hacker just downloading the form page,
  extracting the token and POSTing it?

Say Bob is a normal user on your site.
Chuck is an evil attacker.
Bob goes on your site and submits the comments form (in your code example). If there is CSRF protection, a token is included in this form too:
<input type="hidden" name="csrf_token" value="zxcvbnnmm1235152" />

Bob's session has token zxcvbnnmm1235152 stored for him server-side.
Chuck also has a login to your site because he has registered.
However, when he goes to this page he gets this token instead:
<input type="hidden" name="csrf_token" value="lklkljlk898977" />

If Chuck downloads the page, gets Bob somehow (e.g. sends him an email) to access this page on Chuck's server, because the csrf_token doesn't match Bob's, Chuck can't post the message as Bob.
Bob can continue just fine, because the token in the form matches the one associated with his session.
CSRF is about stopping Chuck from submitting stuff as Bob, using Bob's browsing session.

My application for this is: On the sign-up for to my website I'd like
  a AJAX function that sends the currently entered Username to the
  server which should respond "True/False" if it is available or not.
  This happens onKey so the user can pick a username that has not been
  used already. The Submit button will enable when all the conditions
  for "new user" are met.
Clearly this is an opportunity for a hacker to use the service to
  "test" lots of usernames to see if they available - I know it's not
  exactly internet-banking level sort of risk, but I'd still like to
  service only requests from my application, not a hacker.

Yes, this is your user enumeration vulnerability.
Have username as email, and follow this answer on how to make this secure.

A: The anti-forgery token is not a random code. Nor a reused token for several requests.
Rather, the server couples the token with the callers ip-address or session, for example by encrypting the ip+salt with a server-key.
Thus, if the attacker tries to download the token from your site, it won't be usable by the real client


text:
Q: Grabbing links of header/footer of webpages I try to get all links of the header of a HTMLDocument to process them.
Therefore I use:
Dim docHTML As New HTMLDocument
Dim docElements As IHTMLElementCollection
Dim docElement As IHTMLElement
Dim sPageSource as String

    docHTML.body.innerHTML = sPageSource

    set docElement = docHTML.getElementsByTagName("header")(0)
    set docElements = docElement.getElementsByTagName("a")

But the links aren't in docElements. The length is zero. What is wrong here?
I can't use a specific specific id or classname, because the values are changing depending on the website I read. I have to exclude links from data-target, which is defined in one of the parents.
Any ideas?
As alternative I tried Selenium. With that code:
Dim aData As Selenium.WebElements
Dim htmlElement As Selenium.WebElement

    Set htmlElement = bot.FindElementByTag("header")
    Set aData = htmlElement.FindElementsByTag("a")

Here I get all links of header, but I have no possibility to get information about the parents.
I would prefer the first approach, because I have the impression that Selenium is slower with data handling.


text:
Q: 400 bad request in http request but work perfectly in postman in ionic when I fire http.post() it's response is '400 (Bad Request)' but the same code works in another project in which data is sent with form-data but in this, I am sending data with application/json in row format.
API works fine with the postman and generates a token
this is my postman code that works fine
    var http = require("https");

      var options = {
         "method": "POST",
         "hostname": "dhc-app-api.azurewebsites.net",
         "port": null,
         "path": "/v2/auth/signIn",
         "headers": {
         "content-type": "application/json",
        "cache-control": "no-cache",
       "postman-token": "e9ba66bd-e56b-e526-e6c0-d1b3449760f2"
         }
        };

        var req = http.request(options, function (res) {
         var chunks = [];

        res.on("data", function (chunk) {
        chunks.push(chunk);
      });

      res.on("end", function () {
      var body = Buffer.concat(chunks);
      console.log(body.toString());
       });
       });

      req.write(JSON.stringify({ email: 'manojmht45@gmail.com',
       password: '********' }));
      req.end();

this is my code in ionic
         postData(){
              return new Promise((resolve, reject) =>{
            let headers = new Headers(
                {
                    'Content-Type' : 'application/json'
                });
            let options = new RequestOptions({ headers: headers });

            let data = JSON.stringify({
                "email":"manojmht45@gmail.com",
                "password":"********"
            });

            return new Promise((resolve, reject) => {
                this.http.post('https://dhc-app-api.azurewebsites.net/v2/auth/signIn', data, options)
                    .toPromise()
                    .then((response) =>
                    {
                        console.log('API Response : ', response.json());
                        resolve(response.json());
                    })
                    .catch((error) =>
                    {
                        console.error('API Error : ', error.status);
                        console.error('API Error : ', JSON.stringify(error));
                        reject(error.json());
                    });
            });
        });

postman result
        {
"token": "eyJhbGciOiJIUzI1NiICI6IkpXVCJ9.eyJlbWFpbCI6ImN1aV9ib21iMDIwNEBvdXRsb29rLmNvbSIsImFjY291bnRJZCI6ImxYRVhPMFZqXNlcklkIjoiNXJ5NzNaeUQiLCJyb2xlIjoidXNlciIsImFjY2Vzc09wZXJhdGlvbiI6IltPcGVyYXRpb25dLltSZWdpb25dLltBbGxdIiwiZGVmYXVsdE9wZXJhdGlvbiI6IltPcGVyYXRpb25dLltSZWdpb25dLltBbGxdxpZW50IjoiRGVtbyIsIm5hbWUiOiJEYXZpZCBCdWNjaSIsIm1hZ2ljTGluayI6ZmFsc2UsImlhdCI6MTU2MTI3MTUwMywiZXhwIjoxNTYxMjczOTAzfQ.71asfbf2Nop-QeqVbi2YswnnkY-5qHrhTRjSUZlFKI"
      }

my ionic code result
    polyfills.js:3 OPTIONS https://dhc-app-api.azurewebsites.net/v2/auth/signIn 400 (Bad Request)

     (index):1 Access to XMLHttpRequest at 'https://dhc-app-api.azurewebsites.net/v2/auth/signIn' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
     auth-service.ts:47 API Error :  0

    auth-service.ts:48 API Error :  {"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}


text:
Q: Prepared statements: num_rows is always zero I am in the process of converting my site to prepared statements (before I just relied on a custom function that included mysqli_real_escape_string, among others), but when I run the code, I always get zero records. I know the SQL is fine because I can run the SQL in the MySQL workbench tool and it returns several records. Here is my code:
<?php
$link = new mysqli($server,$dbusername,$dbpassword,$database);
if($link->connect_error){
    die($link->connect_error);
}

$sql = "select itemname from items where itemcategory = ?";
//if(!$query = mysqli_query($link, $sql)) die(mysqli_error($link));
if(!$stmt = $link->prepare($sql)) die("Error");

$stmt->bind_param("i", $category); //replace question mark with category id
$stmt->execute();
$stmt->bind_result($itemname);
//$numitems = mysqli_num_rows($query);
$numitems = $stmt->num_rows;

if($numitems>0){
    //while($array = mysqli_fetch_array($query)){
    while($stmt->fetch()) {
        echo $itemname."<br>";
    }
}
$stmt->close();
?>

$stmt->num_rows is always 0. What am I doing wrong?

A: The problem is actually documented in the php doc for mysqli_stmt_num_rows

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

So because the result has been not transferred to statement handle, you cannot calculate the rows properly. Thats why the solution is like you mentioned:
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($itemname);
$numitems = $stmt->num_rows;

A: My problem was solved by changing
$stmt->execute();
$stmt->bind_result($itemname);

to
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($itemname);


text:
Q: Spring Boot + AngularJS routing not working Spring Boot + AngularJS routing not working

A: Please change template to templateUrl. template is used when you are writing html code inside when like this:
template:'<b>Hello</b>'

templateUrl is used for providing html file as string URL.
templateUrl:'filmList.html'


text:
Q: My application crashes after I try to insert an Item into my database I can open my Datenbase but if I try to insert an item my application crashes.
Insert the item only to my ListView works.
I create a new Object in another Activity and take the Values in an Intent.
But when I start the intent and go back to the Main/List_page Activity my App crashes. Without the Database, the application runs.
Heres my codes: ReceptListAdapter.java:
public class ReceptListDatabase {

private static final String DATABASE_NAME = "receptlist.db";
private static final int DATABASE_VERSION = 1;

private static final String DATABASE_TABLE = "receptlistitems";

public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KATEGORY = "kategory";
public static final String KEY_INGREDIENTS = "ingredients";
public static final String KEY_DIRECTIONS = "ingredients";

public static final int COLUMN_NAME_INDEX = 1;
public static final int COLUMN_KATEGORY_INDEX = 2;
public static final int COLUMN_INGREDIENTS_INDEX = 3;
public static final int COLUMN_DIRECTIONS_INDEX = 4;

private ReceptDBOpenHelper dbHelper;

private SQLiteDatabase DB;

public ReceptListDatabase(Context context) {
    dbHelper = new ReceptDBOpenHelper(context, DATABASE_NAME, null,
            DATABASE_VERSION);
}

public void open() throws SQLException {
    try {
        db = dbHelper.getWritableDatabase();
    } catch (SQLException e) {
        db = dbHelper.getReadableDatabase();
    }
}

public void close() {
    db.close();
}

public long insertReceptItem(ListItem item) {
    ContentValues itemValues = new ContentValues();
    itemValues.put(KEY_NAME, item.getName());
    itemValues.put(KEY_KATEGORY,item.getKategory());
    itemValues.put(KEY_INGREDIENTS, item.getIngredients());
    itemValues.put(KEY_DIRECTIONS, item.getDirection());
    return db.insert(DATABASE_TABLE, null, itemValues);
}

public void removeReceptItem(ListItem item) {

    String toDelete = KEY_NAME + "=?";
    String[] deleteArguments = new String[]{item.getName()};
    db.delete(DATABASE_TABLE, toDelete, deleteArguments);

}

public ArrayList<ListItem> getAllReceptItems() {
    ArrayList<ListItem> items = new ArrayList<ListItem>();
    Cursor cursor = db.query(DATABASE_TABLE, new String[] { KEY_ID,
            KEY_NAME, KEY_KATEGORY, KEY_INGREDIENTS, KEY_DIRECTIONS, null}, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            String name = cursor.getString(COLUMN_NAME_INDEX);
            String kategory = cursor.getString(COLUMN_KATEGORY_INDEX);
            String ingredients = cursor.getString(COLUMN_INGREDIENTS_INDEX);
            String directions = cursor.getString(COLUMN_DIRECTIONS_INDEX);

            items.add(new ListItem(name, kategory, ingredients, directions, null));

        } while (cursor.moveToNext());
    }
    return items;
}

private class ReceptDBOpenHelper extends SQLiteOpenHelper {
    private static final String DATABASE_CREATE = "create table "
            + DATABASE_TABLE + " (" + KEY_ID
            + " integer primary key autoincrement, " + KEY_NAME
            + " text not null, " + KEY_KATEGORY
            + " text, " + KEY_INGREDIENTS
            + " text not null, " + KEY_DIRECTIONS
            + " text not null);";

        public ReceptDBOpenHelper(Context c, String dbname,
                            SQLiteDatabase.CursorFactory factory, int version) {
        super(c, dbname, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

And my Main Activity:
public class List_Page extends Activity {

private ListViewAdapter adapter;
private ArrayList<ListItem> itemList;
private ListView list;
private DatabaseAdapter receptDB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);
    setupButton();
    setupListView();
    addObject();
    setupDatabase();

}

private void setupDatabase() {
    receptDB = new DatabaseAdapter(this);
    receptDB.open();
}

private void setupButton() {
    Button addItemButton = (Button) findViewById(R.id.addItemButton);
    addItemButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            buttonClicked();
        }
    });
}

private void buttonClicked() {
    //get EditText
    Intent newItemIntent = new Intent(List_Page.this, Add_Object.class);
    startActivity(newItemIntent);
    finish();
}

private void setupListView() {
    itemList = new ArrayList<ListItem>();
    adapter = new ListViewAdapter(List_Page.this, itemList);
    list = (ListView) findViewById(R.id.listItem);
    list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long id) {
            //fehler bei removeTaskAtPosition(position);
            return true;
        }
    });
    View header = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_list_item, null);
    list.addHeaderView(header);
    list.setAdapter(adapter);

}

private void addObject(){
    Intent intent = getIntent();
    if (intent.hasExtra(Constants.KEY_RECEPT_NAME)) {
        String name = intent.getExtras().getString(Constants.KEY_RECEPT_NAME);
        String kategory = intent.getExtras().getString(Constants.KEY_KATEGORY);
        String ingredients = intent.getExtras().getString(Constants.KEY_INGREDIENTS);
        String directions = intent.getExtras().getString(Constants.KEY_DIRECTIONS);
        Bitmap image = (Bitmap) intent.getParcelableExtra(Constants.KEY_IMAGE);
        ListItem newObject = new ListItem(name,kategory,ingredients,directions, image);
        itemList.add(newObject);
        receptDB.insertReceptItem(newObject);
        //refreshArrayList();
    }
}

    private void refreshArrayList() {
    ArrayList tempList = receptDB.getAllReceptItems();
    itemList.clear();
    itemList.addAll(tempList);
    adapter.notifyDataSetChanged();
}

private void removeTaskAtPosition(int position) {
    if (itemList.get(position) != null) {
        receptDB.removeReceptItem(itemList.get(position));
        refreshArrayList();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
protected void onDestroy() {
    super.onDestroy();
    receptDB.close();
}

}

Logcat:
08-12 15:37:00.743 22879-22879/de.ur.mi.android.excercises.starter E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: de.ur.mi.android.excercises.starter, PID: 22879
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{de.ur.mi.android.excercises.starter/de.ur.mi.android.excercises.starter.List_Page}: java.lang.NullPointerException: Attempt to invoke virtual method 'long de.ur.mi.android.excercises.starter.DatabaseAdapter.insertReceptItem(de.ur.mi.android.excercises.starter.domain.ListItem)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2720)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:241)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6274)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long de.ur.mi.android.excercises.starter.DatabaseAdapter.insertReceptItem(de.ur.mi.android.excercises.starter.domain.ListItem)' on a null object reference
                                                                                at de.ur.mi.android.excercises.starter.List_Page.addObject(List_Page.java:99)
                                                                                at de.ur.mi.android.excercises.starter.List_Page.onCreate(List_Page.java:40)
                                                                                at android.app.Activity.performCreate(Activity.java:6720)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2673)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:241)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6274)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

A: In your Activity's onCreate you are calling addObject() before calling setupDatabase(). Only inside setupDatabase() you are initialising receptDB instance.
But you are accessing that receptDb inside addObject() method.
receptDB.insertReceptItem(newObject);

So during that time, your receptDB has null reference and so you are getting NullPointerException.
So swap the below two lines from,
addObject();
setupDatabase();

to this:
setupDatabase();
addObject();


text:
Q: Node.js requests VS PHP requests I've written in PHP before and when a user connected they get an individual instance of the code which is then closed when the code has finished executing.
In node, I set up my first server to console.log("hi") on every request.
When I refreshed I didn't expect the "hi" to be logged again, but it was - I get its being logged twice because of the browser looking for a favicon.
Is this one of the ways in which node behaves differently to languages like PHP?
Does every user connecting to the server share this - what should I call it - instance, at once? If I set var IP = *users IP* would it be over-written by the next user?
Edit: Is this actually a different instance, but the console doesn't indicate this and prints it straight below? --- I added an "I" counter and incremented it on every request and the logged value for I increased, so it must be the same instance.

A: PHP is a programming language. You use a web-server like Apache to handle HTTP requests and depending to your settings your web-server runs PHP in the background.
Node.js is an environment to run JavaScript. JavaScript is the programming language that you are building your stuff on it. Here Node.js is your web-server that handles HTTP requests.
Node.js doesn't create a new process to handle each request; That's why you see all the outputs in one place. It loads your file once and then serves all users with the same code.
In PHP, a fresh copy of file (either from cache or disk) will be used to serve each request which means re-initialising everything, including your variables, etc.
In JavaScript, this code will only hold the last value assigned to it:
var ip = req.ip;

// or...

function setIP ( ip ) {
    this.ip = ip;
};

setIP( req.ip );

If you want to keep the IP address of each individual users, you should do it either like this:
function User ( ip ) {
    this.ip = ip;
};

var user = new User( req.ip );

Or:
function User ( ip ) {
    var ip = ip;
}

var user = User( req.ip );

You should create a new User instance every time you handle a new request. It can't be one global variable/object, or the value will be replaced anytime you handle a new request.
(These are just example snippets to demonstrate the point)


text:
Q: How do i match data using mysql and php? Need some help
I have 5 tables in the database, here is the mysql code:
CREATE TABLE IF NOT EXISTS `candidate` (
  `CID` int(4) NOT NULL AUTO_INCREMENT,
  `title` varchar(5) NOT NULL,
  `fname` varchar(30) NOT NULL,
  `lname` varchar(30) NOT NULL,
  `dob` date NOT NULL,
  `email` varchar(50) NOT NULL,
  `address` varchar(255) NOT NULL,
  `city` varchar(50) NOT NULL,
  `postcode` varchar(10) NOT NULL,
  `phone_num` varchar(11) NOT NULL,
  `username` varchar(40) NOT NULL,
  `password` varchar(40) NOT NULL,
  `regdate` datetime NOT NULL,
  `acc_type` enum('c','s') NOT NULL DEFAULT 'c',
  `emailactivate` enum('0','1') NOT NULL DEFAULT '0',
  `cv_name` varchar(60) NOT NULL,
  `cv` blob NOT NULL,
  PRIMARY KEY (`CID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='// this is the table for the candidates' AUTO_INCREMENT=175 ;

-- --------------------------------------------------------

--
-- Table structure for table `candidate_skill`
--

CREATE TABLE IF NOT EXISTS `candidate_skill` (
  `CSID` int(4) NOT NULL AUTO_INCREMENT,
  `CID` int(4) NOT NULL,
  `S_CODE` int(4) NOT NULL,
  PRIMARY KEY (`CSID`),
  KEY `CID` (`CID`),
  KEY `S_CODE` (`S_CODE`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='//match candidate and skill' AUTO_INCREMENT=102 ;

-- --------------------------------------------------------

--
-- Table structure for table `job`
--

CREATE TABLE IF NOT EXISTS `job` (
  `JID` int(4) NOT NULL AUTO_INCREMENT,
  `job_title` varchar(40) NOT NULL,
  `job_desc` varchar(255) NOT NULL,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  PRIMARY KEY (`JID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='// this is the table for the job vacancies' AUTO_INCREMENT=10 ;

-- --------------------------------------------------------

--
-- Table structure for table `skill`
--

CREATE TABLE IF NOT EXISTS `skill` (
  `S_CODE` int(4) NOT NULL AUTO_INCREMENT COMMENT '// this is the skill primary key',
  `skill_name` varchar(40) NOT NULL,
  `skill_desc` varchar(255) NOT NULL,
  PRIMARY KEY (`S_CODE`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

-- --------------------------------------------------------

--
-- Table structure for table `skill_job`
--

CREATE TABLE IF NOT EXISTS `skill_job` (
  `SJID` int(4) NOT NULL AUTO_INCREMENT,
  `JID` int(4) NOT NULL,
  `S_CODE` int(4) NOT NULL,
  PRIMARY KEY (`SJID`),
  KEY `S_CODE` (`S_CODE`),
  KEY `JID` (`JID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=94 ;

And this is the query giving me problems:
$query = ("SELECT * FROM candidate, candidate_skill, job, skill, skill_job WHERE candidate_skill.S_CODE=skill_job.S_CODE AND skill.S_CODE=candidate_skill.S_CODE AND candidate.CID=candidate_skill.CID AND job.JID = skill_job.JID");

$result = mysql_query ($query);
$candidate_id ='';
$canskill ='';
        while ($result = mysql_fetch_array ($res)){
            $candidate_id .= $r['CID'];
            $canskill .= $r ['S_CODE'];

            }
        }

        }
    echo $candidate_id;

I'm trying to match candidates and jobs using their skills and i have sort of succeeded but im having candidates match with jobs even if they only have one skill and the job has for example three skills.
Can someone please point me in the right direction because I have searched, tested and recoded for days but im failing to move past this problem

A: you're doing a simple join, so any candidate who has even just one of the listed skills will be matched. You need to actually count how many of required skills are matched, and filter the query results using that.
Without rejiggering your whole query, it'd be something like:
SELECT ..., COUNT(skill_job.id) AS cnt
FROM ....
WHERE ...
HAVING (cnt = 3)

This'd restrict to candidates who have exactly 3 of the required skills. If you want "at least 2" or similar types, then it'd be
HAVING (cnt >= 2)

and so one for other variations.


text:
Q: Unity 2018.2 - UNet Matchmaking only works at LAN I'm trying to implement the UNET Matchmaking system based on a tutorial from Brackeys.
I already enabled the multiplayer services in my Unity account and enabled the service.
When I try to create a match and find it from another PC in my LAN, it works perfect.
When I try to create a match and find it from another PC outside of my LAN, I can't see the match in the match list.
I already searched the docs and google but didn't find anything about it.
Anyone have a clue?
By the way, here is my JoinRoom script.
The return from callback function is successful, but the list of rooms comes back empty.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using UnityEngine.Networking.Match;
using System;

public class JoinGame : MonoBehaviour
{
    List<GameObject> roomList = new List<GameObject>();

    [SerializeField] GameObject roomListItemPrefab;
    [SerializeField] Transform roomListParent;
    [SerializeField] Text status;
    private NetworkManager networkManager;

    void Start()
    {
        networkManager = NetworkManager.singleton;

        if (networkManager.matchMaker == null)
        {
            networkManager.StartMatchMaker();
        }

        RefreshRoomList();

    }

    public void RefreshRoomList()
    {
        ClearRoomList();
        networkManager.matchMaker.ListMatches(0, 20, "", false, 0, 0, OnMatchList);
        status.text = "Loading...";
    }

    public void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> responseData)
    {
        status.text = "";

        if (!success)
        {
            status.text = "Couldn't get room list";
            return;
        }

        responseData.ForEach(match =>
        {
            GameObject _roomListItemGO = Instantiate(roomListItemPrefab);
            _roomListItemGO.transform.SetParent(roomListParent);
            RoomListItem _roomListItem = _roomListItemGO.GetComponent<RoomListItem>();

            if (_roomListItem != null)
            {
                _roomListItem.Setup(match, JoinRoom);
            }

            //as well as setting up a callback function that will join the game
            roomList.Add(_roomListItemGO);
        });

        if (roomList.Count == 0)
        {
            status.text = "No rooms at the moment";
        }
    }

    public void JoinRoom(MatchInfoSnapshot _match)
    {
        Debug.Log($"Joining {_match.name}");
        networkManager.matchMaker.JoinMatch(_match.networkId, "", "", "", 0, 0, networkManager.OnMatchJoined);
        ClearRoomList();
        status.text = $"Joining {_match.name}...";
    }

    private void ClearRoomList()
    {
        roomList.ForEach(item =>
        {
            Destroy(item);
        });

        roomList.Clear();
    }
}

A: I actually figured out the problem. First, you have to refresh configuration and make sure that cloud configuration is in working state and Multiplayer service is enabled, sometimes it just randomly turns off. Then you should pick matchmaking server directly by naming it, for ex I'm using European server which is eu1-mm.unet.unity3d.com If you simply use mm.unet.unity3d.com it can host your game on different server than your client. And players in different servers not going to see each other. Alternatively you can start your own local server and port forward your IP, then using it as your host IP on client side. Except if you have dynamic IP then you can use services like no-ip to get static domain for your IP. I'm using this method now and plus it is free of charge.

A: The whole problem is related with the Unity MM servers load balancers.
My code was only working in my LAN because the server was being created in the same US region.
This happened because my LAN has a VPN with Canada.
When I connect from a PC outside of my LAN, I was being directed to another region, that was why I can't find the server created by my LAN machine.
After deploy to two computers outside of my LAN, they both can create and connect do another one server.


text:
Q: External Voronoi library "Mesh": What is Sketch and Processing? Question
This might be a too specific quesion but I figured I'd give it a shot. If it doesn't belong here, I apologize.
I've been looking for an external library that generates a Voronoi Diagram with edges and Regions.
I've had a look at simplevoronoi but it doesn't calculate regions so I figuered I'd continue looking.
I found Mesh made by Lee Bryon and I've tried to use it just like any other external library but it does produce an exception at compile time
Exception in thread "main" java.lang.NoClassDefFoundError: processing/core/PApplet
    at megamu.mesh.IntArray.add(IntArray.java:21)
    at megamu.mesh.Voronoi.<init>(Voronoi.java:88)

On the website the install guide reads
Install
    Download Mesh
    Unzip into Processing's libraries folder
    Sketch → Import Library → mesh

Now my questions are: What is Processing? What is Sketch? And will I be able to use this library in my project somehow or can someone recommend a different one?
Solution (kind of)
In the end I tried to use a library called Java Power Voronoi Diagram made by Arlind Nocaj.

A: Processing is an environment/language which is based on Java. You can find more information about it here: http://processing.org/
As far as getting that library working, it might be fairly simple to port it. Processing's syntax is nearly identical to Java's. You'll have to make proper Java classes for everything if that hasn't already been done.

A: you can quickly generate a voronoi diagram in Processing (Development Environment) using a library called toxi. Here is an example, https://github.com/hamzeen/voronoi_image
P.S. Processing is a tiny development environment specially for artists (yet not restricted to them) to quickly prototype their ideas with minimal code (java) & it's based on java applets.


text:
Q: How does kubernetes do service address to endpoint pod address translation? use kube-proxy and NAT? I deployed a service myservice to the k8s cluster. Using kubectl describe serivce ..., I can find that the service ip is 172.20.127.114 . At the same time, the service endpoint is 10.34.188.30:5000,10.34.89.157:5000. How does Kubernetes handle service address to endpoint address translation? Does kube-proxy handle the NAT?  Which linux module does kube-proxy use to handle NAT?
kubectl describe service myservice

Name:              myservice
Namespace:         default
Labels:            app=myservice
                   app.kubernetes.io/instance=myservice
Annotations:       argocd.argoproj.io/sync-wave: 3
Selector:          app=myservice
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                172.20.127.114
IPs:               172.20.127.114
Port:              <unset>  80/TCP
TargetPort:        5000/TCP
Endpoints:         10.34.188.30:5000,10.34.89.157:5000
Session Affinity:  None
Events:            <none>

iptables is used for setting node firewall rules. My understanding is that iptables does not do NAT.

A: I hope this helps you.
Pod to Pod communication

*

*No built-in solution

*Expects you to implement a networking solution

*But impose fundamental requirements on any implementation to be pluggable
into Kubernetes

K8s requirements of CNI Plugins

*

*Every Pod gets its unique IP address

*Pods on the same Node can Communicate with that IP address

*Pods on different Node can Communicate with that IP address without NAT
(Network Address Translation)

Kubernetes Networking Model

*

*All nodes must be able to reach each other, without NAT

*All pods must be able to reach each other, without NAT

*Pods and nodes must be able to reach each other, without NAT

*Each pod is aware of its IP address (no NAT)

*Pod IP addresses are assigned by the network implementation

Summary

*

*The "pod-to-pod network" or "pod network":

*

*Provides communication between pods and nodes

*Is generally implemented with CNI plugins

*The "pod-to-service network":

*

*Provides internal communication and load balancing

*Is generally implemented with kube-proxy

*Network policies:

*

*Provide firewalling and isolation

*Can be bundled with the "pod network" or provided by another component

*Inbound traffic can be handled by multiple components:

*

*Something like kube-proxy (for NodePort services)

*Load balancers (ideally, connected to the pod network)

*It is possible to use multiple pod networks in parallel (with "meta-plugins" like CNI-Genie or Multus)

Useful Links

*

*How CNI works?

*DNS in Kubernetes

*How requests are forwarded from Service to Pod

A: This depends on type of service being used for ClusterIP from within the cluster are never source NAT'd.  More details are k8s documentation


text:
Q: Are you supposed to look at the source when javadoc is not clear? How am I, as a developer, supposed to find out what exactly some library code is supposed to do according to the API?
To be more specific, I'm trying to learn the Android API. It seems to me that the javadocs are not always clear, but when you start reading the SDK source code of classes like Activity, Fragment, View, you get a much better impression of what is actually going on.
But doesn't that invalidate the idea of having an API (= interface), where the actual implementation (source code) can change while the API remains the same? And if you look at the source code, aren't you more likely to take some behavior for granted which wasn't intended to be part of the API?
I'm also relatively new to the concept of Inversion Of Control, where you, for example, have to subclass and override lots of methods like onCreate or onDraw. It seems to me that necessarily there are lots of hidden things going on in the background without having to write any code about it, because the SDK code contains the actual main thread loop. For example, the app creates a window, displays an action bar, it paints a white background, reacts to certain events from the very beginning. But I didn't write any code for this behavior. I just left out code. It's all taken over by the SDK.
I have the impression that this paradigm makes the learning curve steeper because you would actually have to look up somewhere what happens when you write nothing or when you leave out specific lines of code. But in the docs I can only look up what happens after some method gets called (probably by me, probably by the SDK) but not when it's called and what happens if I don't call it or don't override it. So is there some recommended way to look up those things that are supposed to happen implicitly all the time?

A: For learning the Android SDK, I would start with their developer website. There are tons of tutorials, sample code, and explanations of the SDK to browse through.


text:
Q: High Volume of API Errors Facebook Developer alert says that:

In the last three hours 100% of the calls to the method POST
  /achievements resulted in errors.

Error Code: 100 Error Description:
Invalid parameter Error Count: 4,708

But we haven't changed the code in 4 or 5 months.  What could be the problem?  As I see it there is no additional parameter added to facebook achievements.

A: It was because of some of the users did not grant the publish_actions permission.  Granting this permission solved the problem.


text:
Q: Citrix login performance How do you go about troubleshooting application startup time in a Citrix environment? We have some users that get very fast startup time, others take forever when starting the same application on similar hardware/network.

A: Take a look at the profiles. If they are on the same hardware and it's consistently the same users who are slow, look at the profile size. That's the first place we start. Larger profiles take longer to load. So if there's a substantial difference, there you go.

A: Try to establish the point in the logon process there is a delay. I would search the Brian Madden website for an article called Troubleshooting Slow Citrix and Terminal Server Logons. I would link to the site but am not allowed as a new user...
Note: If profile bloat is the problem, then you will see a delay whilst 'Loading personal settings' is displayed on screen.

A: Also check for differences in login scripts between your users.  Users who are mapping lots of drives and having multiple group policies being applied to them will take a lot longer to log in.

A: Check the number of files that are in the users profile, as having 100's of files will slow the copying of the profile.


text:
Q: Executing javascript inside div Question updated. Update at the bottom-
I have to put script on a page. Unfortunately, I don't have control over the header or footer or even the body tag. All, I have is a set of inner html that goes inside a wrapping DIV which sits inside the body tag. Something like this:

Now, I have to place some javascript. So, I obviously put it inside the section that I control. The problem is that the javascript is not being executed. I even put an alert but there is NO alert box popping up. The final code looks something like this:

Any idea what could be wrong? And how I can fix it?
Thanks.
UPDATE: I am not sure if this makes any difference, but I forgot to mention that all this HTML is present inside a frame tag (under a frameset). Will that make a difference?

A: EDIT:
I see you are trying to load an external javascript file - are you sure that file exists?

Instead, put some javascript wrapped in the document ready event:
The below is a way to run code when the dom loads using jQuery. However, if you don't want to use jQuery, see the last part of this answer.
$(document).ready(function(){
// dom ready
   alert("hello");
});

You can further control the div my content like so:
$(document).ready(function(){
// dom ready
   alert("hello");
   $("#mycontent").hide(); // for example, hide the div
});

Non jQuery:
At the bottom of your HTML page, place your code in


text:
Q: behavior of pipe operator in compostie functions purrr - dplyr usage of pipe operator in purrr-dplyr packages is (in short) defined as follows:

y%>%f(x,.,z) is the same as f(x,y,z)

I am trying to do the following task using pipe operator. First I show you the task without using pipes:
#####for reproducibility
set.seed(50)
z0<-factor(sample(c(letters[1:3],NA),100,replace = T))
###the task
rep(1,length(table(z0)))

now I want to do this using pipes:
z0%>%table%>%rep(1,length(.))

however the result is not the same. It seems that pipe operator cannot handle the proper assignation to a composition of functions. That is

y%>%f(x,g(.)) should be the same as f(x,g(y))

so, the concrete question is if ti is possible to do

y%>%f(x,g(.))

Thank you in advance for your comments.

A: The %>% implements a first argument rule, that is, it passes the previous data as first argument to the function if . is not a direct argument; In your second case, the argument to rep is 1 and length(.), so the first argument rule takes effect; To avoid this, use {} to enclose the expression; You can read more about this at Re-using the placeholder for attributes:

Re-using the placeholder for attributes
It is straight-forward to use the placeholder several times in a
  right-hand side expression. However, when the placeholder only appears
  in a nested expressions magrittr will still apply the first-argument
  rule. The reason is that in most cases this results more clean code.
 x %>% f(y = nrow(.), z = ncol(.)) is equivalent to f(x, y = nrow(x), z = ncol(x))

The behavior can be overruled by enclosing the right-hand side in
  braces:
x %>% {f(y = nrow(.), z = ncol(.))} is equivalent to f(y = nrow(x), z = ncol(x))

rep(1,length(table(z0)))
# [1] 1 1 1

Equivalent would be:
z0 %>% table %>% {rep(1,length(.))}
# [1] 1 1 1


text:
Q: How can I represent polymorphism in JMX? I have some types like this:
public interface Numbering {
    List<NumberingComponent> getComponents();
}

public interface NumberingComponent {
    Object getValue();
}

public interface StringNumberingComponent extends NumberingComponent {
    String getValue();
}

public interface IntegerNumberingComponent extends NumberingComponent {
    Integer getValue();
}

This is all well and good, unless you try to register an MXBean which happens to use this type, and you get:

...top of exception chain omitted ...
Caused by: javax.management.openmbean.OpenDataException: Cannot convert type: class com.acme.NumberingComponent
    at com.sun.jmx.mbeanserver.OpenConverter.openDataException(OpenConverter.java:1411)
    at com.sun.jmx.mbeanserver.OpenConverter.toConverter(OpenConverter.java:264)
    at com.sun.jmx.mbeanserver.OpenConverter.makeArrayOrCollectionConverter(OpenConverter.java:315)
    at com.sun.jmx.mbeanserver.OpenConverter.makeParameterizedConverter(OpenConverter.java:393)
    at com.sun.jmx.mbeanserver.OpenConverter.makeConverter(OpenConverter.java:296)
    at com.sun.jmx.mbeanserver.OpenConverter.toConverter(OpenConverter.java:262)
    ... 57 more
Caused by: javax.management.openmbean.OpenDataException: Cannot convert type: interface java.io.Serializable
    at com.sun.jmx.mbeanserver.OpenConverter.openDataException(OpenConverter.java:1411)
    at com.sun.jmx.mbeanserver.OpenConverter.toConverter(OpenConverter.java:264)
    at com.sun.jmx.mbeanserver.OpenConverter.makeCompositeConverter(OpenConverter.java:467)
    at com.sun.jmx.mbeanserver.OpenConverter.makeConverter(OpenConverter.java:293)
    at com.sun.jmx.mbeanserver.OpenConverter.toConverter(OpenConverter.java:262)
    ... 61 more
Caused by: javax.management.openmbean.OpenDataException: Can't map java.io.Serializable to an open data type
    at com.sun.jmx.mbeanserver.OpenConverter.makeCompositeConverter(OpenConverter.java:454)
    at com.sun.jmx.mbeanserver.OpenConverter.makeConverter(OpenConverter.java:293)
    at com.sun.jmx.mbeanserver.OpenConverter.toConverter(OpenConverter.java:262)
    ... 64 more

Strings and integers are representable in JMX but Object isn't, as at least one getter needs to be present on the class for it to recognise it as a usable type.  I know that any attempt to add an abstraction layer in is not going to help, because NumberingComponent itself is already such a layer.  The original version of the interfaces had generics in there as well, but I removed them to keep it simpler, and it fails in the same way with or without them.
Is there some other way I can go about mapping this to a composite type?  I googled the exception message, and got essentially no hits at all. (!!)

A: You could make StringNumberingComponent and IntegerNumbering interfaces also extend CompositeDataView. Assuming the MBean's MBeanInfo indicates the correct CompositeType for the attribute, the MBeanServer will "render" the attribute as a CompositeData instance which will serialize correctly.
The method the concrete implementations will need to implement is fairly straightforward since your CompositeType will only have one field:
public CompositeData toCompositeData(CompositeType ct)

There's a decent example in the JavaDoc.