text:
Q: How can I scroll content under a fixed header while respecting max-height inherit in Internet Explorer 11? I have a container with a max-height. I'd like to place in it a header and a scrolling body. It's simple in most browsers, but I'm struggling with IE11. Using max-height: inherit;, the .scroll div and its scrollbar extends below its parent (see snippet in IE11)
It's trivial using flexbox instead, but IE11 has a bug that requires changing the display of body to resolve. But I can't do that.
Is there some way to get .scroll to scroll correctly in IE11 without flexbox, and while respecting the max-height functionality on the container?

div {
  border: 1px solid #DDD;
}
.container {
  max-height: 150px;
  overflow: hidden;
}
.header {
  height: 40px;
}
.scroll {
  max-height: inherit;
  overflow: auto;
}

      header

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

A: Edited
You can place your header absolutely and add padding-top to container. But the height of the container will be 40px bigger.

div {
  border: 1px solid #ddd;
}
.container {
  position: relative;
  max-height: 150px;
  overflow: hidden;
  padding-top: 40px;
}
.header {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 40px;
  background: white;

}
.scroll {
  max-height: inherit;
  overflow: auto;
}

    header

scroll-first

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll-last

A: It not seems to be a specific problem of IE, I see the same problem on Chrome too.
Your container's height is 150px (since it's from 3-rd party framework we cannot change this number), so the 'scroll' element's height should be 150px - 40px = 110px. Let's set it instead of 'inherit':

div {
  border: 1px solid #DDD;
}
.container {
  max-height: 150px;
  overflow: hidden;
}
.header {
  height: 40px;
}
.scroll {
  max-height: 110px;
  overflow: auto;
}

      header

scroll first

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll last

and everything works fine (I've tested it on both IE and Chrome)

A: I had exactly the same issue, but after some searching I found that you could add the following styles to your container:
display: flex; flex-direction: column;

And change the max-height style to height.
This seems to work in IE11 as well as all other major browsers, and I didn't have to edit the body at all. Please see this JSFiddle for an example using the code you provided.
I hope this helps!

A: Hope it'll help ;)

div {
  border: 1px solid #DDD;
}
.container {
  max-height: 150px;
  height: 150px;
  overflow: hidden;
  position: relative;
}
.header {
  height: 40px;
}
.scroll {
  width: 100%;
  height: calc(100% - 40px);
  overflow: auto;
}

      header

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll


text:
Q: Background - single diagonal stripe I need to have a background with CSS as the image attached back I can't make it work with linear-gradient.

I was trying with the following but I am unable to create just 1 white stripe.

div {
  background: #5cbcb0;
  background: linear-gradient(120deg, #5cbcb0 10%, #ffffff 10%, #ffffff 27%, #5cbcb0 27%, #5cbcb0 50%, #5cbcb0 50%, #5cbcb0 74.81%, #ffffff 73.81%, #ffffff 76.19%, #5cbcb0 76.19%, #5cbcb0 100%);
  background-size: 593.97px 593.97px;
}

A: You just need to provide correct start and stop values for the colors. The occurrence of the multiple white stripes were due to the multiple #fff values that were used after 73.81%.

div {
  background: linear-gradient(135deg, #5cbcb0 5%, #ffffff 5%, #ffffff 15%, #5cbcb0 15%);
  /* Start #5cbcb0 from 0 and end at 5%, Start #fff at 5% and end at 15%, Start #5cbcb0 again at 15% and end at 100% */
  background-size: 593.97px 593.97px;
  background-repeat: no-repeat; /* To avoid multiple instances */
}

A: Try adding no-repeat if that helps check snippet.

div {
   background: #5cbcb0;
   background: linear-gradient(120deg, #5cbcb0 10%, #ffffff 10%, #ffffff 30%, #5cbcb0 27%, #5cbcb0 50%, #5cbcb0 50%, #5cbcb0 100%, #ffffff 73.81%, #ffffff 76.19%, #5cbcb0 100%, #5cbcb0 100%) no-repeat;
    background-size: 593.97px 593.97px;
}

A: You can try it like below. I defined the size in percentage so it will be responsive.

body {
  background:
   linear-gradient(to bottom right, #5cbcb0 15%,#fff 15.5% 49.5%,transparent 50%) top left/30% 80% no-repeat,
   #5cbcb0;
  margin:0;
  height:100vh;
}

If you want a static version simply use pixel values:

body {
  background:
   linear-gradient(to bottom right, #5cbcb0 15%,#fff 15.5% 49.5%,transparent 50%) top left/200px 200px no-repeat,
   #5cbcb0;
  margin:0;
  height:100vh;
}

A: Be careful with CSS!
The extra stripes remark that you did not just create 3 shapes, but another shape as well. If you want to create just 3 shapes, you only need 4 values instead of more.
So this will work:

div {
  background: #5cbcb0;
  background: linear-gradient(120deg, #5cbcb0 5%, #ffffff 5%, #ffffff 15%, #5cbcb0 15%);
  background-size: 593.97px 593.97px;
  background-repeat: no-repeat;
}

So you just need 4 values for that. Yes, this is a repeat of the top answer, but this gives what actually is going on here. So to avoid multiple instances, use no-repeat and it would work because if you remove that it will show multiple instances, if you try. Also, you can remove the height: 200px and move it to the div class to avoid inline styling. It works with 135 degrees also, so 120 is not a "special" number in which case this works. And also, you don't want it to show more than 1 white stripe so that's why I put up background-repeat: no-repeat.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uneven starting column alignments with large columns The following produces four tables, which I boxed to make them clearer.
The bottom two boxes are of even starting heights, but the top two are not.
I would like for the top pair of boxes to start at the exact same height like the bottom pair does. Is there some sort of padding parameter that I am not taking advantage of?
\documentclass[]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage[T1]{fontenc}
\usepackage[margin=0.5in]{geometry}
\usepackage{empheq}
\usepackage{multicol}

\newcommand*\widefbox[1]{\fbox{\hspace{2em}#1\hspace{2em}}}

\begin{document}

Uneven column heights:
\begin{multicols}{2}
    \begin{minipage}[t]{0.5\textwidth}
        \begin{empheq}[box=\widefbox]{align}\nonumber
        \begin{matrix}
        \text{Title number 1} & \text{Title number 2} & \text{Title Number 3}\\
        1a & 2a & 3a\\
        1b & 2b & 3b\\
        1c & 2c & 3c
        \end{matrix}
        \end{empheq}
    \end{minipage}
    \begin{minipage}[t]{0.5\textwidth}
        \begin{empheq}[box=\widefbox]{align}\nonumber
        \begin{matrix}
        \text{Title no. 4} & \text{Title no. 5} & \text{Title no. 6}\\
        4a & 5a & 6a\\
        4b & 5b & 6b\\
        4c & 5c & 6c
        \end{matrix}
        \end{empheq}
    \end{minipage}
\end{multicols}

\vspace{1cm}
Even column heights:
\begin{multicols}{2}
    \begin{minipage}[t]{0.5\textwidth}
        \begin{empheq}[box=\widefbox]{align}\nonumber
        \begin{matrix}
        \text{Title no. 1} & \text{Title no. 2} & \text{Title no. 3}\\
        1a & 2a & 3a\\
        1b & 2b & 3b\\
        1c & 2c & 3c
        \end{matrix}
        \end{empheq}
    \end{minipage}
    \begin{minipage}[t]{0.5\textwidth}
        \begin{empheq}[box=\widefbox]{align}\nonumber
        \begin{matrix}
        \text{Title no. 4} & \text{Title no. 5} & \text{Title no. 6}\\
        4a & 5a & 6a\\
        4b & 5b & 6b\\
        4c & 5c & 6c
        \end{matrix}
        \end{empheq}
    \end{minipage}
\end{multicols}

\end{document}


text:
Q: mysql database problem now I can't reach to the database
this my actual problem can somebody help I was developing website using python flask framwork  and now I facing issue to fill the form of my page in mysqldb error I have tried to install mysqlclient but can't install it


text:
Q: Java JPanel clear I need to create a 2d simulation, but while setting a new "frame" the old dont get cleared.
I want some Circles moving in an Arena, and every loop the old circles should get removed and new ones spawn. Everything works, but the old ones dont get cleared and are still visible, thats what I need to change.
GameLoop
@Override
public void run() {

    while(true){

        try {
            Thread.sleep(10);
            for(Schleimpilz s : this.pilz){
                s.move();
                fenster.getArena().repaint();;
                fenster.getArena().paintPilz();

            }

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Thats the Arena Class (extends Jpanel), where the Jpanel needs to get cleared
public void paintPilz() {

    //how to clear the old values here?
    super.paintComponent(graphics);
    setBackground(Color.WHITE);

    for(Schleimpilz s : schleimpilz){

        printNewSchleimpilz(s.getLocX(), s.getLocY());

    }
}

A: You should be doing all of your rendering in the paintComponent method. This is how to old shapes get removed (on repaint).
To do your animation / creating new circles, you should use a javax.swing.Timer instead of Thread.sleep
new Timer(10, new ActionListener() {
                 s.move();
                fenster.getArena().repaint();
});


text:
Q: Passing a environment variable to Supervisord subprocesses from an azure app service I want to pass a environement variable to my supervisord subprocesses, but the variable doesn't appear in the available names for the subprocesses. The major issue is because my azure app service builds dynamically, I can't explicitly define the variable but must use the env var $APP_PATH. I want to figure out how I can pass this to the Supervisor subprocess environments. Here are my config files;
supervisord.conf
[unix_http_server]
file=/var/run/supervisor.sock   ; path to your socket file
chmod=0700

[supervisord]
command=env
logfile=/home/LogFiles/supervisord/supervisord.log ; supervisord log file
logfile_maxbytes=50MB       ; maximum size of logfile before rotation
logfile_backups=10          ; number of backed up logfiles
loglevel=info               ; info, debug, warn, trace
pidfile=/var/run/supervisord.pid ; pidfile location
nodaemon=false              ; run supervisord as a daemon
minfds=1024                 ; number of startup file descriptors
minprocs=200                ; number of process descriptors
user=root                   ; default user
childlogdir=/home/LogFiles/supervisord/            ; where child log files will live

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///var/run/supervisor.sock ; use unix:// schem for a unix sockets.

[include]
files=etc/supervisor/conf.d/celeryd.conf

celerybeat.conf
[program:celerybeat]
environment=APP_PATH=$APP_PATH
; Set full path to celery program if using virtualenv
command=%(ENV_APP_PATH)s/antenv/bin/celery -A kinduwa beat --loglevel=INFO
;command=celery -A kinduwa beat -loglevel=INFO

; remove the -A myapp argument if you aren't using an app instance
user=nobody
numprocs=1
stdout_logfile=/home/LogFiles/beat.out.log
; stdout_logfile= /var/log/celery/beat.log
stderr_logfile=/home/LogFiles/beat.err.log
; stderr_logfile= /var/log/celery/beat.log
autostart=true
autorestart=true
startsecs=10

; Causes supervisor to send the termination signal (SIGTERM) to the whole process group.
stopasgroup=true

; if rabbitmq is supervised, set its priority higher
; so it starts first
priority=999

celeryd.conf
[program:celery]
environment=APP_PATH=$APP_PATH
user=nobody
numprocs=1
stdout_logfile=/home/LogFiles/celery/worker.out.log
; stdout_logfile=/var/log/celery/worker.log
stderr_logfile=/home/LogFiles/celery/worker.err.log
; stderr_logfile=/var/log/celery/worker.log
autostart=true
autorestart=true
startsecs=10

; Set full path to celery program if using virtualenv
;command=celery -A proj worker --loglevel=INFO
;command=celery -A kinduwa worker --loglevel=INFO

; Alternatively,

;command=celery --app=your_app.celery:app worker --loglevel=INFO -n worker.%%h
command=%(ENV_APP_PATH)s/antenv/bin/celery -A kinduwa worker --loglevel=INFO
;command=celery -A kinduwa worker --loglevel=INFO

; Or run a script
;command=celery.sh

; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600

; Causes supervisor to send the termination signal (SIGTERM) to the whole process group.
stopasgroup=true

; Set Celery priority higher than default (999)
; so, if rabbitmq is supervised, it will start first.
priority=1000

here is my start_up script for good measure;
apt-get update
apt-get install -y supervisor

mkdir /var/run/celery/
mkdir /var/lib/celery/
mkdir /var/log/celery/

# adding and starting custom supervisor config
cp kdw_supervisord/kdw_supervisord.conf /etc/supervisor/
supervisorctl -c /etc/supervisor/kdw_supervisord.conf

service supervisor stop
service supervisor start

# adding in celery beat and worker configs
cp kdw_supervisord/kdw_celerybeat.conf /etc/supervisor/conf.d/
cp kdw_supervisord/kdw_celeryd.conf /etc/supervisor/conf.d/

supervisorctl reread
supervisorctl update
supervisorctl start all

gunicorn --bind=0.0.0.0 --timeout 600 kinduwa.wsgi

The error I get when I attempt to deploy is;
2021-05-17T15:43:18.125749054Z ERROR: CANT_REREAD: Format string '%(ENV_APP_PATH)s/antenv/bin/celery -A kinduwa beat --loglevel=INFO' for 'program:celerybeat.command' contains names ('ENV_APP_PATH') which cannot be expanded. Available names: ENV_LANG, ENV_LANGUAGE, ENV_LC_ADDRESS, ENV_LC_ALL, ENV_LC_COLLATE, ENV_LC_CTYPE, ENV_LC_IDENTIFICATION, ENV_LC_MEASUREMENT, ENV_LC_MESSAGES, ENV_LC_MONETARY, ENV_LC_NAME, ENV_LC_NUMERIC, ENV_LC_PAPER, ENV_LC_TELEPHONE, ENV_LC_TIME, ENV_PATH, ENV_PWD, ENV_TERM, group_name, here, host_node_name, process_num, program_name in section 'program:celerybeat' (file: '/etc/supervisor/conf.d/kdw_celerybeat.conf')

tl:dr; I have a dynamically set $APP_PATH env_var want to use in supervisord subprocesses, how do I do that?


text:
Q: Stripping/removing the first line out of a html when importing data from an ajax query using jquery? In the code below, I want to edit it so that it strips out the first line.
function update(url,cln){
    $.ajax({
        url: url,
        dataType: "HTML",
        error: function(msg){
            alert(msg.statusText);
            return msg;
        },
        success: function(html){
            $("#main").html(html + '');
        }
    });
}

For example if the code contacts the url: http://stackoverflow.com/
The url returns:
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />

It would strip out the first line so that when it writes the html to the #main it would only write:

A: You can use a regular expression that matches everything from the beginning of the string up to the first line break:
html = html.replace(/^.*?\r?\n/, '');

Demo: http://jsfiddle.net/Guffa/7pdqw/
Explanation of the regular expression:
^    - matches the beginning of the string
.*?  - matches zero or more character, non-greedy
\r?  - matches zero or one carriage return character
\n   - matches a line feed character

A: The following will select the part of the content you need
function update(url,cln){
    $.ajax({
        url: url,
        dataType: "HTML",
        error: function(msg){
            alert(msg.statusText);
            return msg;
        },
        success: function(html){
            $("#main").html($(html).find('#data').html() + '');
        }
    });
}

A: You should use .filter() or .load(). http://api.jquery.com/load
How do I filter the returned data from jQuery.ajax?


text:
Q: InfluxDB aggregate on TOP function and display in Grafana I'm new to InfluxDB and Grafana. I'm using version 1.7.4 and playing through the Grafana Twitter example in the Spring Cloud Data Flow workshop. There is basically a hashtags measurement like this:
select * from hashtags limit 10
name: hashtags
time                       htag             value
----                       ----             -----
2019-03-07T07:46:59.096Z   現実見ろ           0
2019-03-07T07:46:59.097Z   キズのしょち松さん   0
2019-03-07T07:46:59.097Z   競馬              0
2019-03-07T07:46:59.098Z   PerthTanapon     0
2019-03-07T07:46:59.098Z   終活              0
2019-03-07T07:46:59.106Z   capolavoro       0
2019-03-07T07:46:59.108Z   Cenizas          0
2019-03-07T07:46:59.108Z   design           0
2019-03-07T07:46:59.108Z   hyungwon         0
2019-03-07T07:46:59.108Z   ざわちん           0

In the example screencast the author creates a pie chart that is supposed to display the top 10 hashtags on Twitter. The video shows that he creates a query like this:
SELECT sum("value") FROM "hashtags" GROUP BY "htag" SLIMIT 10
The problem here is that the chart only represents 10 hashtags in alphabetical order. What I want is the Top 10 hashtags. Now InfluxDB doesn't have a order by clause on tags or fields so I tried to come up with my own query that tries to solve my problem using TOP() and a subquery:
select top("sum", "htag",10) from (SELECT sum("value") FROM "hashtags" GROUP BY "htag") which yields the correct result:
name: hashtags
time                 top  htag
----                 ---  ----
1970-01-01T00:00:00Z 3172 TwoOfUs
1970-01-01T00:00:00Z 2301 BestCoverSong
1970-01-01T00:00:00Z 1480 เชงเม้ง
1970-01-01T00:00:00Z 1337 투모로우바이투게더
1970-01-01T00:00:00Z 1117 GOT7
1970-01-01T00:00:00Z 1106 MeMyselfAndI
1970-01-01T00:00:00Z 848  백현
1970-01-01T00:00:00Z 848  ยุบพรรค
1970-01-01T00:00:00Z 842  Jus2
1970-01-01T00:00:00Z 781  TOMORROW_X_TOGETHER

The problem with grafana is that it doesn't properly display my results in the pie chart

What am I missing? I saw that the first query has a grouping so the query result looks like this:
name: hashtags
tags: htag=01JokowiAs1k
time                 sum
----                 ---
1970-01-01T00:00:00Z 0

name: hashtags
tags: htag=01JokowiLagi
time                 sum
----                 ---
1970-01-01T00:00:00Z 9

name: hashtags
tags: htag=01OptimisIndonesiaMaju
time                 sum
----                 ---
1970-01-01T00:00:00Z 7

How can I achieve that grouping on my query?

A: Try additional GROUP BY "htag":
SELECT TOP("sum", "htag",10) FROM
  (SELECT SUM("value") FROM "hashtags" GROUP BY "htag")
GROUP BY "htag"


text:
Q: Pictorial explanation of Dynkin index and quadratic Casimir? Draw a colored loop. You explained quantum dimension. :-) OK, now you may use trivalent nodes and knot crossings too (with edges colored by irreps). You can now pictorialize 6j symbols, writhe normalizers, structure constants etc. My question is whether other things that also pop up all the time in Lie groups, as the (quadratic) Casimir or Dynkin index of an irrep can be visualized this way. (Since that's the only way I can do math :-)
Background: a) In "Birdtracks" an additive formula for Dynkin indices (multiplied with dimensions somehow) of the irreps involved in a Clebsch-Gordan expansion is given, b) I deduced another formula involving writhe normalizers and dimensions that is also valid for any Clebsch-Gordan expansion. (In short: Let $R_i\bigotimes{R_j}=\bigoplus_k{R_k}$, and $W_k=w_i*w_j/w_k$, where the $w_k$ are writhe normalizers, let $o_k$ be the dimensions, then $\Sigma_k{(W_k-W_k^{-1})o_k}=0$. Using pictures the proof is an one-liner.) It's natural to speculate whether a) and b) are essentially the same (or maybe even more things are additive over a Clebsch-Gordan expansion).

A: It really sounds like you'd want to look at works of Pierre Vogel, starting from The universal Lie algebra, and also check recent results that use the same setup, like this one.


text:
Q: How to ensure zoom controls always shown on a MapView? I'm having awful problems with this. I have a MapView, in my activity I set the flag to show the zoom controls, and it works. But then the user navigates to another activity, comes back to the map, and the zoom controls have gone.
Is there a simple way to ensure the zoom controls are always present, or do I need to roll my own on top? Ideally I want to set up the zoom controls in a subclass of MapView to keep things simple. I suspect it's failing as the zoom controls are being set up at the wrong time, but when is the right time?

A: Here is what I do. First add a ZoomControl view to the file with your MapView (I am using a RelativeLayout to hold the MapView and ZoomControls)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <MapView
        android:id="@+id/map"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="X"
        android:clickable="true" />

    <ZoomControls
        android:id="@+id/zoomcontrols"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true" />
</RelativeLayout>

Now in your onCreate method do something like
    mapView.setBuiltInZoomControls(false);
    ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
    zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mapController.zoomIn();
        }
    });
    zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mapController.zoomOut();
        }
    });

A: You can do it very easily.
On the onCreate() method do:
MapView mapView = (MapView) findViewById(R.id.map_view_id);
mapView.setBuiltInZoomControls(true);

With that, the zoom buttons appear at the bottom of the screen. They disappear if now touch events occur for a small period of time and they appear automatically again if any touch events happens.


text:
Q: Tensorflow, binary classification Is it possible to make a binary classification? Especially for pedestrian detection, whether it is or not a pedestrian. I couldn't find anything in the API or any good tutorials for this.
I tried to adapt the code from the deep MNIST tutorial, that was used for multi-class classification; I made the images with pedestrians in them labeled with 1, and the negatives with 0, and used 3 channels(for colours, shouldn't be a problem right?), but the accuracy just jumps all over the place.
The code
    import dataset as input_data
    import tensorflow as tf

    def weight_variable(shape):
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial)

    def bias_variable(shape):
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial)

    def conv2d(x, W):
        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

    def max_pool_2x2(x):
        return tf.nn.max_pool(x, ksize=[1, 3, 3, 1],
                              strides=[1, 2, 2, 1], padding='SAME')

    data = input_data.read_data_sets()

    sess = tf.InteractiveSession()

    x = tf.placeholder("float", shape=[None, input_data.HEIGHT * input_data.WIDTH * 3])
    y_ = tf.placeholder("float", shape=[None, 2])

    W_conv1 = weight_variable([5, 5, 3, 64])
    b_conv1 = bias_variable([64])

    x_image = tf.reshape(x, [-1, input_data.WIDTH, input_data.HEIGHT, 3])

    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)
    h_norm1 = tf.nn.lrn(h_pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)

    W_conv2 = weight_variable([5, 5, 64, 64])
    b_conv2 = bias_variable([64])

    h_conv2 = tf.nn.relu(conv2d(h_norm1, W_conv2) + b_conv2)
    h_norm2 = tf.nn.lrn(h_conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
    h_pool2 = max_pool_2x2(h_norm2)

    W_fc1 = weight_variable([input_data.HEIGHT / 4 * input_data.WIDTH / 4 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, input_data.HEIGHT / 4 * input_data.WIDTH / 4 * 64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

    keep_prob = tf.placeholder("float")
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    W_fc2 = weight_variable([1024, 2])
    b_fc2 = bias_variable([2])

    y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

    cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
    train_step = tf.train.AdamOptimizer(1e-6).minimize(cross_entropy)
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    sess.run(tf.initialize_all_variables())
    for i in range(20000):
        batch = data.train.next_batch(50)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={
                x: batch[0], y_: batch[1], keep_prob: 1.0})
            print "step %d, training accuracy %g" % (i, train_accuracy)
        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print "test accuracy %g" % accuracy.eval(feed_dict={
        x: data.test.images, y_: data.test.labels, keep_prob: 1.0})

The output
    step 0, training accuracy 0.14
    step 100, training accuracy 0.54
    step 200, training accuracy 0.28
    step 300, training accuracy 0.46
    step 400, training accuracy 0.32
    step 500, training accuracy 0.52
    step 600, training accuracy 0.56
    step 700, training accuracy 0.76
    step 800, training accuracy 0.66

Help would be apriciated, thanks.

A: You should definitely use tensorboard to visualize the cross entropy , biases and weights summaries. I think it will give you a much better  view of what is going on.
Try with this code and then run tensorboard:
import dataset as input_data
import tensorflow as tf

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 3, 3, 1],
                          strides=[1, 2, 2, 1], padding='SAME')

data = input_data.read_data_sets()

sess = tf.InteractiveSession()

x = tf.placeholder("float", shape=[None, input_data.HEIGHT * input_data.WIDTH * 3])
y_ = tf.placeholder("float", shape=[None, 2])

W_conv1 = weight_variable([5, 5, 3, 64])
b_conv1 = bias_variable([64])

x_image = tf.reshape(x, [-1, input_data.WIDTH, input_data.HEIGHT, 3])

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
h_norm1 = tf.nn.lrn(h_pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)

W_conv2 = weight_variable([5, 5, 64, 64])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_norm1, W_conv2) + b_conv2)
h_norm2 = tf.nn.lrn(h_conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
h_pool2 = max_pool_2x2(h_norm2)

W_fc1 = weight_variable([input_data.HEIGHT / 4 * input_data.WIDTH / 4 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, input_data.HEIGHT / 4 * input_data.WIDTH / 4 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 2])
b_fc2 = bias_variable([2])

y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# Add summary ops to collect data
w_fc2_hist = tf.histogram_summary("weights_fc2", W_fc2)
b_fc2_hist = tf.histogram_summary("bias_fc2", b_fc2)
w_in_hist = tf.histogram_summary("weights_in", W)
b_in_hist = tf.histogram_summary("bias_in", b)
y_hist = tf.histogram_summary("y_conv", y_conv)

cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
ce_summ = tf.scalar_summary("cross entropy", cross_entropy)
train_step = tf.train.AdamOptimizer(1e-6).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
accuracy_summary = tf.scalar_summary("train accuracy", accuracy)
# Merge all the summaries and write them out to /tmp/tf
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter("/tmp/tf", sess.graph_def)
sess.run(tf.initialize_all_variables())
for i in range(20000):
    batch = data.train.next_batch(50)
    feed={x: batch[0], y_: batch[1], keep_prob: 0.5}
    result = sess.run([merged, accuracy, train_step], feed_dict=feed)
    if i % 100 == 0:  # Record summary data, and the accuracy
            summary_str = result[0]
            acc = result[1]
            writer.add_summary(summary_str, i)
            print("Accuracy at step {0}/{1}: {2}%".format(i, 20000, int(acc*100)))

print "test accuracy %g" % accuracy.eval(feed_dict={
    x: data.test.images, y_: data.test.labels, keep_prob: 1.0})


text:
Q: How do I reply? 'It's time you started [to trust me]' or 'It's time you started to [trust me]? Given the following sentence: 'I don't trust you' - what's the proper way to end the following reply:'It's time you started' or 'It's time you started to'? Is there a rule governing the inclusion/omission of 'to'?

A: Both are reasonable.
The general rule about any omission is does it easily lead to mis-understanding or undesirable ambiguity.

It's time you started.

Clear what is meant.

It's time you started to.

Clear what is meant.

*It's time you started to trust.

Incorrect omission as it stands as its own statement too strongly to indicate anything was omitted. (Though that could well make it an even better statement, depending on why they don't trust you).

*It's time you.

Incorrect, leaves you hanging, "time I what?" Too little included to be clear that you are answering the previous statement and omitting something.

*It's time.

Combines the problems with both the previous bad examples.


text:
Q: Why useState hook don't update while using loop inside useEffect() Case 1:
    const [present, setPresent] = useState([]);

    useEffect(() => {

        for (var j = 1; j <= totalPeriod; j++) {
          setPresent([
            ...present,
            {
              period: j,
              present: true,
            },
          ]);
        }

    }, []);

Case 2:

    const [present, setPresent] = useState([]);

    let createPresent = [];
    for (var j = 1; j <= totalPeriod; j++) {
      createPresent = [
        ...createPresent,
        {
          period: j,
          present: true,
        },
      ]
    }

    useEffect(() => {
      setPresent(createPresent);
    }, []);

When I am trying to update the present state using loop in inside useEffect() in Case 1, present state is not updating. But when I am separately using loop outside the useEffect() and creating an array which I am then assigning to present state in case 2, the present state is getting updated.
What is the reason behind this? Why present state is not updating in Case 1?

A: In the below case, your present state is not the result of each subsequent state update but rather the initial one which you had which is []. React will batch these updates and not make them happen synchronously so effectively there will be just one state update with present updated to latest entry in your for loop.
  const [present, setPresent] = useState([]);

    useEffect(() => {

        for (var j = 1; j <= totalPeriod; j++) {
          setPresent([
            ...present,
            {
              period: j,
              present: true,
            },
          ]);
        }

    }, []);

In the below case, you are first assembling a createPresent array with all the values you need and finally calling the state updator function i.e. setPresent to set the state.
const [present, setPresent] = useState([]);

    let createPresent = [];
    for (var j = 1; j <= totalPeriod; j++) {
      createPresent = [
        ...createPresent,
        {
          period: j,
          present: true,
        },
      ]
    }

    useEffect(() => {
      setPresent(createPresent);
    }, []);

In order to achieve the second behaviour with first, you can make use of the state updator callback which holds the previous state as the argument like so :-
  const [present, setPresent] = useState([]);

    useEffect(() => {

        for (let j = 1; j <= totalPeriod; j++) {
          setPresent(prevState=>[
            ...prevState,
            {
              period: j,
              present: true,
            },
          ]);
        }

    }, []);

Here also state update is batched but previous state is factored in before updating the next one.
When I say a batched state update, I mean there will only be a single render. You can verify that by doing console.log('render') in your component's function body.
Note the use of let instead of var here since let is scoped you will get the accurate value for the variable j.

A: The assumption you're making in Case 1 is that the setPresent call is synchronous and that it updates present immediately, while in reality state updates in React are almost always asynchronous. Thus the present variable inside for (var j = 1; j <= totalPeriod; j++) { will be equal to the original value, which is an empty array []. So in essence, you're setting the state to this over and over:
  [
      ...[],
     {
        period: j,
        present: true,
     },
  ]

This will result in your state being updated to the last array the for loop creates. So if totalPeriod is equal to 5, your state will end up being [{period: 5, present: true}] instead of [{period: 1, present: true}, {period: 2, present: true}, ... ]
In Case 2, everything is very straightforward, you assemble the array without messing with state variables and then set the state in one shot. Just like you're supposed to in this case.

A: In addition to other answers:
You need to keep some key points in your mind while updating states in React component.
First of all updating state in React state is not synchronous, hence will be batched unless you trigger it asynchronously.
state = { count: 0};
increment() {
    this.setState({ count: this.state.count + 1});
    this.setState({ count: this.state.count + 1});
    this.setState({ count: this.state.count + 1});
    console.log(this.state.count) // 0
}

increment()
console.log(this.state.count); // 1

And, the final value of this.state.count will be 1 after completion of the calling incemenent()
Because React batch the all calls up, and figure out the result and then efficiently make that change. Kind of this pure JavaScript code, merging where last one wins
newState = Object.assign(
    {},
    firstSetStateCall,
    secondSetStateCall,
    thirdSetStateCall,
);

So, we can say here everything has to do with JavaScript object merging. So there's another cool way, where we pass a function in setState instead of object.
Secondly, in case of react hooks useState, the updating function(second element of the array returned by useState()) doesn't rerender on the content's change of the state object, the reference of the state object has to be changed. For example: here I created sandbox: link
had I not changed the reference of the array (which is the state), it would not rerender the components.
 for (let key in newState) {
      newStateToBeSent[key] = newState[key]; // chnaging the reference
    }


text:
Q: Microsoft: Private Team with read only sharepoint I am looking to have a Private Teams site where members can contribute to a document library.  I want the corresponding Sharepoint site to be viewable by all authenticated users.
Currently when I create a private team site the corresponding Sharepoint site cannot be accessed by non members.
If I create the Private Team then go to Sharepoint and change permissions to public the Team now becomes public also.
Again, I need a private team site for contributors and a public (any authenticated user) Sharepoint site.

A: You can add 'Everyone except external users' to the SharePoint Online site with View only permission. This can be done via Gear icon in the upper right -> Site Permissions -> Invite People -> Share Site Only.


text:
Q: How to get size for subimage from SURF descriptor I want to copy the part of an image which is descibed by a SURF descriptor. I know that the 9x9 filter in surf has a scale of 1.2. So if I have for example a descriptor with a scale of 1.2 is the part I can copy the 9x9 pixels around the descriptor point? And if I have a scale of 1.6 I would calculate the part with "9 / 1.2 * 1.6 = 12"? The subimage would be 12x12 pixels than?
On the other hand I read this in the OpenSURF documentation:
"The first step in extracting the SURF descriptor is to construct a square window around the interest point. This window contains the pixels which will form entries in the descriptor vector and is of size 20s, again where s refers to the detected scale."
So maybe I get the subimage if I take the 20*scale pixels around the descriptor point?
I don't know why it should be 20!? The first solution is more clear I guess...
Thanks!

A: According to SURF original paper, I can answer you with two things:

*

*The first solution you mention is the way to generate the filter size for an octave in SURF. However we don't have filter size 12x12. We just have {9x9,15x15,21x21,27x27},{15x15,27x27,..,..},{27x27,..},... It is not the region around the SURF key point for extracting the descriptor.

*The sub image that covers a descriptor region is rotated window (based on dominant orientation) with the size 20*scale around the descriptor point. In my opinion, practical experiments allow the authors to pick that number (20). Similar to minimum Hessian threshold for eliminating non-SURF key points, they are heuristic method.

A: If the implementation is exactly the one described in the original SURF paper, you have to use 20s. 9x9 is the starting filter size to detect interest points, but 20s is the window dimension to describe the area around an interest point.


text:
Q: How do you find a village on survival? My brother and I are playing Minecraft on our phones, but have yet to find a village in survival mode.
We've seen villages in creative but never in survival. How do we find one? What seed could I use to find one ?

A: 1) make sure you have structures turned on in the world settings.
2) villages spawn in specific biomes. Big plains biomes are the best ones to find villages in.
Good luck in searching and sometimes it does take a while to find one, just keep making new worlds if you have no luck! :)

A: Not always, but quite often, in MCPE, villages form on the banks of a river.
If you're playing in survival and come across a river, pick a direction and follow it (or even better make a boat and cruise the river) and you'll eventually find a village.


text:
Q: Dereferencing type-punned pointer breaks strict-aliasing rules Following error shows while compilation process:
ccm.c:152:5: error: dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing]
      HWREG(AES_AES_IV_0) = ((uint32_t *)&ui8A0)[0];

ccm.c:325:5: error: dereferencing type-punned pointer will break strict- aliasing rules [-Werror=strict-aliasing]
      ((uint32_t  *)&ui8MIC)[0] = HWREG(AES_AES_TAG_OUT_0);

Line 152-155:
HWREG(AES_AES_IV_0) = ((uint32_t  *)&ui8A0)[0];
HWREG(AES_AES_IV_1) = ((uint32_t  *)&ui8A0)[1];
HWREG(AES_AES_IV_2) = ((uint32_t  *)&ui8A0)[2];
HWREG(AES_AES_IV_3) = ((uint32_t  *)&ui8A0)[3];

ui8A0 is 16-sized uint8_t array:
uint8_t  ui8A0[16];

Line 325-328:
((uint32_t  *)&ui8MIC)[0] = HWREG(AES_AES_TAG_OUT_0);
((uint32_t  *)&ui8MIC)[1] = HWREG(AES_AES_TAG_OUT_1);
((uint32_t  *)&ui8MIC)[2] = HWREG(AES_AES_TAG_OUT_2);
((uint32_t  *)&ui8MIC)[3] = HWREG(AES_AES_TAG_OUT_3);

ui8MIC is 16-sized uint8_t array:
uint8_t volatile ui8MIC[16];

HWREG macro looks like this:
#define HWREG(x)                                                              \
        (*((volatile uint32_t *)(x)))

That's how I understand it:
ui8A0 is an array, &ui8A0 is an address of first element, (uint32_t  *)&ui8A0 is an address for array where elements are uint32_t contrary to uint8_t which were before, ((uint32_t  *)&ui8A0)[0] is the value of first element of an array which elements are uint32_t.
So basically this code has to pass 4 elements of ui8A0 to HWREG macro.
It looks like this problem: https://stackoverflow.com/a/20956250/1625856
But I would prefer not to use the union-based solution.
Is there any other, easier way to handle it?
My only idea is to replace:
HWREG(AES_AES_IV_1) = ((uint32_t  *)&ui8A0)[1];

with:
HWREG(AES_AES_IV_1) = (uintptr_t)&ui8A0[4];


text:
Q: How to convert shell script into python? I want to convert this shell script file to python.
#!/bin/bash

(cd ../frontend; npm run build)

for file in src/main/resources/static/*;
    do
        rm -rf "$file"
    done

for file in ../frontend/dist/*;
    do
        cp --recursive "$file" src/main/resources/static
    done

mvn clean install

I am trying to solve problem in this way:
import os
os.system("npm run build")
os.chmod('../backend/src/main/resources/static', 0o777)
for file in os.listdir('../backend/src/main/resources/static/*'):
    os.remove(file)

But getting an FileNotFoundErrors [WinError 2] that can't find my files.
Error also shows up when I try to delete files from a non-empty directory.
The rmdir command does not work too.
I was trying to do some permission changes.

A: Indeed, the listdir only retrives the filename. And it doesn't understand wildcards.
Then you should try:
import os
os.system("npm run build")
path = "../backend/src/main/resources/static"
os.chmod(path, 0o777)
for file in os.listdir(path):
    os.remove(f"{path}/{file}")


text:
Q: Do WinInet or WinHTTP support custom ports? If so, how do I implement it? I am trying to download a file using both HTTP and HTTPS (in different scenarios) from a service which defaults to using ports 5080 and 5443, respectively. I wanted to use WinInet (or WinHTTP) as they're native to Windows, but it appears that both WinInet and WinHTTP only support using port 80 or port 443, and do not support specifying anything else.
Is it possible to specify a different port, and I've overlooked something? If not, is the next-best native option to drop down to using WinSock?
Edit: As answered below, the third parameter is of type INTERNET_PORT, but will accept any DWORD. Microsoft's documentation is confusing, as written here, InternetConnect, it says "nServerPort can be one of the following values.", which makes one believe only the provided constants are valid.
Instead, you can provide any port value (of type DWORD).
I submitted feedback on the InternetConnect documentation page, so hopefully this will be clearer for future readers.

A: WinInet's InternetConnect() and WinHTTP's WinHttpConnect() both let you specify any port number you want in their respective nServerPort parameters. You don't have to use the pre-defined constants like INTERNET_DEFAULT_HTTP(S)_PORT.


text:
Q: Model not inheriting User data So I am working with built-in Django login forms and I want my blogger model to inherit all the users created using the form but it is not showing up in the blogger model.
Models
class Blogger(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,null=True)
    follows = models.ManyToManyField('self', related_name='following', symmetrical=False)

    def __str__(self):
        return self.user.username

View for the sign up
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('/blog')
    else:
        form = SignUpForm()
    return render(request, 'winterblog/signup.html', {'form': form})

Django form used
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('/blog')
    else:
        form = SignUpForm()
    return render(request, 'winterblog/signup.html', {'form': form})

Thanks a lot!

A: Your signup view does not create Blogger instance. You can create blogger record for new user inside view:
def signup(request):
if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
        form.save()
        username = form.cleaned_data.get('username')
        raw_password = form.cleaned_data.get('password1')
        user = authenticate(username=username, password=raw_password)
        Blogger.objects.create(user=user)
        login(request, user)
        return redirect('/blog')
    else:
        form = SignUpForm()
    return render(request, 'winterblog/signup.html', {'form': form})

Another option is add signal to create new blogger automatically once new user has been created:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Blogger.objects.create(user=instance)


text:
Q: How to create circular marks/buttons and circular window Let me try to explain what I am doing...
I am creating a map with some marks on the map, but I want to change these marks to circular buttons. When I click, it should open a circular window over my map with some options (map in the background).
Is it possible?
If my explanation is not clear I can paste my code. Any help will be appreciated!

A: U can use an outline object with android L or u can set an oval background image (f.e. define a oval drawable file)
Here is some sample code:
   //Outline
    int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
    Outline outline = new Outline();
    outline.setOval(0, 0, size, size);

And some code example for an oval drawable:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">

        <solid
           android:color="#79bfea"/>

A: Create a XML file inside your res/Drawable
round_button.xml

<!-- Bottom 2dp Shadow -->
<item>
    <shape android:shape="oval" >
        <stroke android:color="#ffffff" />

        <corners android:radius="2dp" />
    </shape>
</item>

And in your component xml set the background:
 android:background="@drawable/round_button"


text:
Q: Drop rows from each group if dates are within a given range Given a DataFrame like below:
dfx = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"],
                    "date":["01/01/2014","01/31/2014","01/23/2014","01/01/2014","01/20/2014"]})

I want to remove "duplicates". "duplicates" are defined as those rows where the ID of the rows are the same, but the "date" between them is Less Than 30 days.
The resulting DataFrame upon removal of the "duplicates" is expected appear as:
ID    date
A   01/01/2014
A   01/31/2014
C   01/23/2014
B   01/01/2014

A: *

*Convert date to datetime.

*Group date by ID and find difference between consecutive rows

*Extract the days component from the timedelta difference and compare it to 30

*Filter dfx based on the mask

dfx[~pd.to_datetime(dfx.date).groupby(dfx.ID).diff().dt.days.lt(30)]

  ID        date
0  A  01/01/2014
1  A  01/31/2014
2  C  01/23/2014
3  B  01/01/2014


text:
Q: alert on child load I want to open a window with window.open and attach a function to it's onload.
forexample, when child page load completed (just DOM), browser shows an alert in child page.
This code doesn't work::
var google;
function google(){
    google = window.open('http://www.google.com/');

    // Dean Edwards/Matthias Miller/John Resig

    /* for Mozilla/Opera9 */
    if (google.document.addEventListener){
        google.document.addEventListener("DOMContentLoaded", pageLoaded, false);
    }

    /* for Internet Explorer */
    /*@cc_on @*/
    /*@if (@_win32)
        google.document.write("


text:
Q: Cron does not launch automatically My cron on my django project does not work. I mean I have to launch it manually using the following instruction :
python3 manage.py crontab run 1a909d1e0a17391270108c0591b73ed
I tried this :
python3 manage.py crontab add

But it does not work automatically unfortunately ...
Could you help me please ?

A: You can check out this guide, it might help you fix the issue: https://gutsytechster.wordpress.com/2019/06/24/how-to-setup-a-cron-job-in-django/


text:
Q: PHP: SQL query to select columns provided by php array from any table I have array of columns which I want to search from table.
I am looking to use SQL something like :
$columns = array('a', 'b', 'c');
$sql = "select $columns from table";

Is this possible? How can we perform such action?

A: A part of it is possible:
$columns = array('a','b','c');
$sql = "Select ".implode(",", $columns) . " from table....";

PHP implode Manual
EDIT
I'm afraid, it is not possible to exclude the table-name!
But you can query first all table names and then select from those.


text:
Q: Please explain this for me please? private List<> name(List<> model, String name) in java Please explain this for me please?  private List<> name(List<> model, String name)

A: private List<> name(List<> model, String name) is not a correct java code.
But in the idea you has a private method (function)  called name that return a List.
That function has 2 parameters : 1 list called model and 1 String call name.
Your  problem : List of what ???
List if if the return of your function is a array of String.
Same problem with model, List of what ??


text:
Q: The build command requires to be run in an Angular project, but a project definition could not be found - build is incomplete I am new working in angular project. Trying to build a angular project which is not complete because of the below message.
build-prod-linux:
     [exec] The build command requires to be run in an Angular project, but a project definition could not be found.
     [exec] Result: 1

I tried installing yarn, angular-cli (re-installed) yet it shows build successful but because of this message build is incomplete and not able to see the output for my changes. Could you someone help. I looked in other answers but nothing helped so far. Thank you for the help.


text:
Q: Deleted member functions and constructors for r-value references behave differently I am trying to disable using some member functions with temporary objects. To achieve this, I declare a r-value reference overload as deleted:
struct X {};

struct A
{
  A();
  void f(X const& x);
  void f(X&&) = delete;
};

int main()
{
    A a;
    X x;

    a.f(X());
    a.f(x);

    return 0;
}

This works as expected giving a compiler error, but when I try this with constructors, it does not generate a compile-error:
struct X {};

struct A
{
  A(X const&);
  A(X&&) = delete;
};

int main()
{
    X x;

    A b(X()); // using deleted constructor
    A c(x);

    return 0;
}

Why is this compiling? Is the A(X const&) constructor a better match  than the  A(X&&) constructor?

A: Most vexing parse:
struct X {};

struct A
{
  A(X const&);
  A(X&&) = delete;
};

int main()
{
    X x;

    A b(X()); // using deleted constructor
}

A b(X()) does not call the constructor but declares a function (Most vexing parse: why doesn't A a(()); work?).


text:
Q: How can I limit or disable data usage for only my Android app (Kotlin)? I'm developing an application on Android (Kotlin), I was searching for some help with Network.
How can I limit or disable data usage for only my app, if it's possible, I don't want to make that seen to user.
I'm using the Retrofit library in my app to make network calls so maybe someone would tell me if I can disable retrofit and there won't be any calls?
I don't want to affect other apps for example by disabling wifi or mobile data, I just want to disable or limit for only my app.
I tried to enable/disable wifi or mobile data, but it's not what I wanted. Then I tried to redirect to the settings and let user disable it on its own but it's not still the same.

A: I just created a value in Shared Preferences and when i try to make a call , i'm checking for it's value and if it's true then i'm in offline mode , if it's false i'm in online mode and making a call .
it maybe a solution for a first time , but i will appreciate any suggestions.


text:
Q: Load iFrame at Margin: -9999px; Move iFrame Margin to +20px after 5 seconds As the title says, I want to load an iFrame out of the visible window, at margin:-9999px; and then move it into the visible window after a 5 second delay.
This is because I am performing a function on the iFrame and don't want users to see it until that function is complete.
The code I am running is this:
jQuery(window).load(function(){jQuery(".Remover").find("p, ul").remove()});
          jQuery(window).load(function(){jQuery(".footnote").find("*").remove()});

If I can tell the browser not to show the result until the above is complete that would also be acceptable.
Thanks for any help!

A: Give your iframe visibility hidden (via css or explicit styling):
iframe {visibility: hidden;}

then after your load is complete inside the frame you can set it to visible:
$(window.frameElement).css("visibility", "visible");


text:
Q: How to make a signature pad in AngularJS or pure javascript without Jquery? I'm making a mobile app and I need the simplest possible signature pad for javascript for implementing with AngularJS but I cant find any resources anywhere.
All the plugins use jquery which I refuse to load since it's a mobile app and jquery would just bloat the app. Does anyone know of a tutorial I could use or could give me basic directions how would I do this, what elements do i need... I'd really appriciate it!
UPDATE: I just wrote something basic as it was answered here. But it doesn't work. Can anyone indentifiy why? I have a directive that i inject into html as an element (). Console is not returning any exceptions.
sig.directive("signatureDirective", function () {
    return {
        template: '<canvas id="canvas" width="500" height="100" style="border: 1px solid #ccc;"></canvas>',
        restrict: 'E',
        link: function (scope, element, attrs) {

            var canvas = $(element);
            var context = canvas.getContext("2d");
            var clickX = new Array();
            var clickY = new Array();
            var clickDrag = new Array();
            var paint;

            $(element).addEventListener("mousedown", mouseDown, false);

            $(element).addEventListener("mousemove", mouseXY, false);

            document.body.addEventListener("mouseup", mouseUp, false);

            $(element).addEventListener("touchstart", mouseDown, false);

            $(element).addEventListener("touchmove", mouseXY, true);

            $(element).addEventListener("touchend", mouseUp, false);

            document.body.addEventListener("touchcancel", mouseUp, false);

            function draw() {
                context.clearRect(0, 0, 500, 100);

                context.strokeStyle = "#000000";
                context.lineJoin = "miter";
                context.lineWidth = 2;

                for (var i = 0; i < clickX.length; i++) {
                    context.beginPath();
                    if (clickDrag[i] && i) {
                        context.moveTo(clickX[i - 1], clickY[i - 1]);
                    } else {
                        context.moveTo(clickX[i] - 1, clickY[i]);
                    }
                    context.lineTo(clickX[i], clickY[i]);
                    context.stroke();
                    context.closePath();
                }
            }

            function mouseDown(e) {
                var mouseX = e.pageX - this.offsetLeft;
                var mouseY = e.pageY - this.offsetTop;

                paint = true;
                addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
                draw();
            }

            function mouseUp() {
                paint = false;
            }

            function mouseXY(e) {
                if (paint) {
                    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                    draw();
                }
            }

        }
    };
});

A: Take a look at the canvas element. You can directly manipulate the pixel data and draw primitive shapes with a canvas and as a HTML element, it supports all of the mouse manipulation events that you will need out of the box.
<canvas id='signature' width='300' height='50'></canvas>

Something like this:
var canvas, context;
var pen = {};
canvas = document.getElementById('signature');
context = canvas.getContext('2d');

canvas.addEventListener('mousemove', function(e) {
  pen.x = e.pageX;
  pen.y = e.pageY;
});

canvas.addEventListener('mousedown', function(e) {
  context.fillRect(pen.x, pen.y, 1, 1);
});

// when you're done, you can get a base 64 encoded png version
// of the image data.

context.getImageData();

This is a pretty primitive way of doing it, using the fillRect method to simulate pixels. If you wanted to look at heavier solutions, you could try doing something with click points and bezier curves.
If you're using Angular, then you'll almost certainly want to wrap this up in a directive as well.

EDIT
First off, you're using a strange mix of jQuery and plain js. All of the lines that look like this, won't work.
$(element).addEventListener("mousedown", mouseDown, false);

Should look like this:
$(element).on("mousedown", mouseDown, false);

Next off, you seem to be calling a method called addClick which isn't actually there.


text:
Q: How to add image(or custom shape) to divider? I want to recreate this divider. How to add the leaves to the divider?
Is there a nicer way to do it besides creating the border in photoshop, export as a jpg and linking it to the divider?
I don't care about the inner section.

A: You can use an SVG as well!
Since the leaves are plain color and linear shapes, why not turn them into a vector?
Here is an example:
.divider {
  border-image-source: url(leaves.svg);
}


text:
Q: String.match() function returns null even when there is a match I am trying to match a regex with some data in a file, the match function however returns null even when the match clearly exists in the data.
I have tried same data and regex on RegExr and it shows a match.
following is the code
var fs = require('fs');
try {
    var data = fs.readFileSync('File.txt', 'utf8');
    data = data.toString();
    var regex = /^(hi|hI|Hi|HI)\s[^dD].*?$/gm;
    var result = data.match(regex);
} catch(e) {
    console.log('Error:', e.stack);
}

and these are the contents of file
Hi Alex how are you doing
hI dave how are you doing
Good by Alex
hidden agenda
Alex greeted Martha by saying Hi Martha

I used same data on RegExr and it shows first line as a match. but when I run the above code on my machine the result variable remains null.
is there something that I am missing ?
following are some screen shots while i was debugging the code in vscode.

*

*contents of data variable

*state of result variable.

*result of JSON.stringify

Edit. JSON.stringify results
I ran the program on cmd and shockingly the string has a space in front of it.

A: The problem has been solved with the help of the @vsemozhetbyt's answer and many helpful comments. I am adding this answer to help if anybody encounters the some problem in future.
why it happened ?
Because of some wrong encoding, in my particular case the File.txt was originally File.jsp and I changed its extension to .txt and saved it.
after this I read the file.txt which contained same text as JSP and did some regex matching, it worked fine and there was no BOM in the file.
Problem appeared when I opened the file in notepad and replaced all its contents with 5 lines of text shown in the question and saved it.
what is BOM
Read this great article
How I removed BOM
I opened the file in binary mode in vim using
vim -b File.txt

and removed the first three chars (Bytes)

A: The space in the JSON output seems to be BOM. If so, data.codePointAt(0) should be 65279.

A: When you read file in with fs.readFileSync the BOM is not stripped from the data read and it is up to the programmer to handle it. See fs.readFileSync(filename, 'utf8') doesn't strip BOM markers.
You may just use
data = data.replace(/^\uFEFF/, '')

This will remove the BOM if it is there, and then you may run your regex.
Note you do not see the BOM when opening text files in text editors, like VIM, Notepad, because they can handle BOM.


text:
Q: adding end points in prometheus integration How to add/integrate rest api end points in prometheus. For eg in splunk we are monitoring micro services transactions and logs.
Lets say below spring boot:-
/abc/v1/something
/abce/v1/something2

In one line :-how can we add above micro services end points to prometheus for motioning

A: When using Spring Boot 2, you can easily expose your application metrics for Prometheus. See here. You'd add spring-boot-starter-actuator and the Prometheus support with micrometer-registry-prometheus to your dependencies.
This will expose the metrics under /actuator/prometheus in the Prometheus exposition format to be scraped by your Prometheus instance.
Assumung you are using Spring WebMvc, then you'll get out-of-the-box metrics for your HTTP endpoints. (Jersey support is also provided with an extra module/dependency.)


text:
Q: ElasticSearch bool search using array I would like to be able to exclude a number of nodes in my ElasticSearch query. Currently this code is working perfectly, but it will only exclude two nodes ($nodeId1 and $nodeId2).
How would I change this query so I can use an array which would contain as many node IDs as I want? Thank you.
$data_string = '{
    "from" : 0, "size" : "' . $maximumResults . '",
    "query": {
        "filtered": {
            "query": {
                "match" : {
                    "thread.title" : {
                        "query" : "' . $threadTitle . '",
                        "operator": "or"
                    }
                }
            },
            "filter": {
                "bool" : {
                    "must" : [],
                    "must_not" : [
                        {
                            "term" : {"thread.discussion_id" : "' . $currentThreadId . '"}
                        },
                        {
                            "term" : {"thread.node" : "' . $nodeId1 . '"}
                        },
                        {
                            "term" : {"thread.node" : "' . $nodeId2 . '"}
                        }
                    ],
                    "should" : []
                }
            }
        }
    }
}';

A: You can use the terms filter:
$data_string = '{
    "from" : 0, "size" : "' . $maximumResults . '",
    "query": {
        "filtered": {
            "query": {
                "match" : {
                    "thread.title" : {
                        "query" : "' . $threadTitle . '",
                        "operator": "or"
                    }
                }
            },
            "filter": {
                "bool" : {
                    "must" : [],
                    "must_not" : [
                        {
                            "term" : {"thread.discussion_id" : "' . $currentThreadId . '"}
                        },
                        {
                            "terms" : {"thread.node" : ["' . $nodeId1 . '", "' . $nodeId2 . '", "' . $nodeId3 . '"}
                        }
                    ],
                    "should" : []
                }
            }
        }
    }
}';


text:
Q: Returning hashmap keys in order of value in Java? Is there a way to do this? I was thinking it could be done with streams but I'm not super experienced with them and would like some help regarding that.
For example: If the hashmap is currently like:
"A" : 5
"B" : 2
"C" : 4
You then return ["A", "C", "B"].

A:  Map<String, Integer> sortedMap = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

A: You can use TreeMap it will give you ordered by keys
List<Character> sortedKey() {
    Map<Character, Integer> map = new TreeMap<>();
    List<Character> list = new ArrayList<>();
    for(Map.Entry entry: map.entrySet()) {
        list.add((Character)entry.getKey());
    }
    return list;
}

A: Using collections.sort approach:

*

*convert HashMap to List

*sort list using custom comparator

*then create list of key(sorted order based on their values)

code:
// function to sort hashmap by values
public static List sortByValue(HashMap < String, Integer > hm) {
  // Create a list from elements of HashMap
  List < Map.Entry < String, Integer > > list =
    new LinkedList < Map.Entry < String, Integer > > (hm.entrySet());

  // Sort the list
  Collections.sort(list, new Comparator < Map.Entry < String, Integer > > () {
    public int compare(Map.Entry < String, Integer > o1,
      Map.Entry < String, Integer > o2) {
      return (o2.getValue()).compareTo(o1.getValue());
    }
  });

  // put data from sorted list to hashmap
  List < String > temp = new ArrayList < String > ();
  for (Map.Entry < String, Integer > aa: list) {
    temp.add(aa.getKey());
  }
  return temp;
}

A: Given
Map<String,Integer> map = Map.of("A",5,"B",2,"C",4);

This is relatively simple.

*

*stream the entrySet and sort in reversed order using the Entry comparator for values.

*then get the key and collect to a list. If you return a set, they may not be in sorted order.  Nor can you access elements in a set as easily as a List, even if a LinkedHashSet is used to preserve order.

List<String> keys = map.entrySet().stream()
.sorted(Entry.<String,Integer>comparingByValue()
        .reversed()).map(Entry::getKey)
        .toList();  // java 16+ -- prior to Java 16 use .collect(Collectors.toList())

System.out.println(list);

prints
[A, C, B]

A: Create new List of Map.Entries and sort List using method Map.Entry.comparingByValue witch returns a comparator that compares Map.Entry in natural order on value and then turns it in reverse order:
List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.<String, Integer>comparingByValue().reversed());
System.out.println(list);


text:
Q: How to output messages to the Eclipse console when developing for Android How can I print messages (like a flag) to the Eclipse console (or log) when developing and debugging an Android app

A: Log.v("blah", "blah blah");

You need to add the android Log view in eclipse to see them. There are also other methods depending on the severity of the message (error, verbose, warning, etc..).

A: System.out.println() also outputs to LogCat. The benefit of using good old System.out.println() is that you can print an object like System.out.println(object) to the console if you need to check if a variable is initialized or not.
Log.d, Log.v, Log.w etc methods only allow you to print strings to the console and not objects. To circumvent this (if you desire), you must use String.format.

A: Rather than trying to output to the console, Log will output to LogCat which you can find in Eclipse by going to: Window->Show View->Other…->Android->LogCat
Have a look at the reference for Log.
The benefits of using LogCat are that you can print different colours depending on your log type, e.g.: Log.d prints blue, Log.e prints orange. Also you can filter by log tag, log message, process id and/or by application name. This is really useful when you just want to see your app's logs and keep the other system stuff separate.

A: I use Log.d method also please import import android.util.Log;
Log.d("TAG", "Message");

But please keep in mind that, when you want to see the debug messages then don't use Run As
rather use "Debug As" then select Android Application. Otherwise you'll not see the debug messages.

A: i use below log format for print my content in logCat
Log.e("Msg","What you have to print");


text:
Q: How Can I Detect My Character's Nearest Enemy? I want to be able to control this when my player is close to the enemy. It's partially happening but I have a problem and I don't know why it's happening.
There are 2 enemy objects on the stage. The player notices one of them when he approaches, but nothing happens when he approaches the other.
This is my codes;
private void Start()
{
    InvokeRepeating("UpdateTarget", 0f, 0.5f);
}

private void UpdateTarget()
{

    Target = GameObject.FindGameObjectsWithTag("Enemy");

    foreach(GameObject enemy in Target)
    {
        float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);

        if(distanceToEnemy < range)
        {
            closeEnemy = enemy;
        }
        else
        {
            closeEnemy = null;
        }

    }

}

And this is what happened; / This picture is gif.
NOT: All targets have same tag.


text:
Q: home page widget - product weird padding on hover I have the widget in my home page
{{widget type="Magento\CatalogWidget\Block\Product\ProductsList" title="" show_pager="0"
    products_count="6" template="Magento_CatalogWidget::product/widget/content/grid.phtml"
    conditions_encoded="^[`1`:^[`type`:`Magento||CatalogWidget||Model||Rule||Condition||Combine`,`aggregator`:`all`,`value`:`1`,`new_child`:``^]^]"}}

With the layout:

but when I hover, the layout gets weird like there's some padding:

I want it to remain the same. I added the green, yellow and pink colors to make it more clear. I've been trying to find what's the reason for the hovering but for the life of me I can't seem to get it to work. This is in the home page. The catalog product page works fine for the hovering.
test site:
https://testweb.ustrading.com/

A: okay so I found the code:
there's a weird margin: -10px; and padding: 9px;
.products-grid .product-item-info:hover, .products-grid .product-item-info.active {
background: #ffffff;
background-color: rgb(255, 255, 255);
box-shadow: 3px 4px 4px 0 rgba(0, 0, 0, 0.3);
border: 1px solid #bbbbbb;
margin: -10px;
padding: 9px;
position: relative;
z-index: 9;
}
I just set the margin and padding to 0 and it's fixed!


text:
Q: How to send a list of models to a controller using a form POST in a view I want to send to my controller an IEnumerable(ICustomModel) via POST in my view. This is my View
@model IEnumerable<string>
@{
    //This just gets me a Dictionary of <Views,Models> that I will use to render partal views,
    var forms = CustomFormUtil.GetCustomMetaPartial2(Model);

    //List of models I want to send to my Controller via Post
    var result = forms.Select(x => x.Model);

}

//I am sendind the IE<ICustomModels>
@using (Html.BeginForm(MVC.Service.NewOrderRequest.Index(result), FormMethod.Post))
{
    foreach (var form in forms)
    {
        { Html.RenderPartial(form.View, form.Model); }
    }
    <p style="clear: both">
        <input id="submitNOR" type="submit" value="Submit" style="float: right" />
    </p>
}

And my controller is the following
[HttpPost]
    [SaveModelState]
    public virtual RedirectToRouteResult Index(IEnumerable<ICustomMetaModel> forms)
    {
        if (!ModelState.IsValid)
        {
            ModelState.AddModelError("error", "Please fill out the required fields");
            return RedirectToAction(MVC.Service.NewOrderRequestForms.Index());
        }
...

Debugging I can see in the controller that he is receiving the correct data, but when I click submit, the value of 0 is received.
I am really confused about this behavior.
Is this the best way to pass multiple Models to the Controller?


text:
Q: Аккордион не работает как на примере Пример аккордиона работает так, если нажать на одну и потом нажать на другую, то первый закроется. А у меня первый остается открытым. Вроде все делаю как в примере.
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>TEST</title>
        <link href="css/bootstrap.css" rel="stylesheet">
        <link href="css/bootstrap-responsive.css" rel="stylesheet">

            <?php
                for($i=1; $i < 5; $i++){
                    echo accordion('accordion2', 'Bla_'.$i.'Зеленый', 'Hello world <button>BTN</button>');
                }
            ?>

<?php
    function accordion($main_id, $head, $body){
        static $num = 0;
        $num++;
        return
        '

                 ' . $head . '

                    '.$body.'

';
    }
?>


text:
Q: Do-while cycle scanf reads cycles two times instead of one when reading single character I have this code :
char c;
do
{
    scanf("%c",&c);
    printf("coucou\n");
} while (c!='q');

And here my result :
Input:
M

Output:
coucou
coucou

Why does it print "coucou" 2 times every time ?

A: The cycle is executed 2 times because scanf scans 2 characters, one for M and another for the \n new line character.
You can easily solve this by adding a condition to your cycle:
do
{
  if(getchar() != '\n')
    printf("coucou\n");
} while (c!='q');


text:
Q: Convert string to JSON object and send it as response I am constructing a string like the following:
List<string> itemList = new List<string>();

foreach (i in items)
{
 itemList.Add("{ type: " + i.DocumentType + " ,id: " + i.ID + " ,name: " + i.name + " }" );
}

I want to convert the itemList to a JSON object and return it as response in my controller.
Please help.

A: In ASP.Net MVC you could use Linq to get your List in your desired style and then convert to Json using Json(). ie:
public JsonResult GetMyItems()
{
   var myItems = items.Select(i => new {
                    type = i.DocumentType,
                    id = i.ID,
                    name = i.name
                 });

   return Json(myItems, JsonRequestBehavior.AllowGet);
}

A: See Serializing and Deserializing JSON
public class Data {
 public Data(string type, long id, string name) {
  Type = type;
  Id = id;
  Name = name
 }
 public string Type { get; set; }
 public long Id { get; set; }
 public string Name {get; set;
}

var itemList = items.Select(i => Data(i.DocumentType , i.ID, i.name).ToList();
string json = JsonConvert.SerializeObject(itemList);


text:
Q: Does time complexity change based on parameters? If my function void foo(n) has a time complexity of O(n), and I have a function call foo(4), would I say that the time complexity of foo(4) is O(4)?

A: Normally, the complexity of the function doesn't change depending of the parameters inserted, since it has been calculated over that parameter. In this case, if the complexity is O(n), over the parameter of the function (in you case, 4). Let's say that your function contains a for loop. Let's see an example in pseudo-code:
fun foo(int n) {
    for int i = 0; i < n; i++) {
        print(i);
    }
}

This function prints the numbers from 0 to n. Since increasing n only increases the number of elements linearly, the function is O(n) independently of the value of n.
Another example in pseudo-code:
fun foo(int n) {
    for int i = 0; i < 2^n; i++) {
        print(i);
    }
}

In this case, the function prints the values from 0 to 2^n. Increasing n increases the number of elements exponentially, so the function is O(2^n). Changing the value of n does not change the complexity of the function.
But what happens if we have a function like this one?:
fun foo(int n, boolean b) {
    if(b == true) {
        for int i = 0; i < n; i++) {
            print(i);
        }
    } else {
        for int i = 0; i < 2^n; i++) {
            print(i);
        }
    }
}

In this case, the complexity of the function is O(n) if b is true, and O(2^n) if b is false. So, yes, the complexity of the function can change depending of the value of the parameters of the function, only if that parameter is not the selected for calculating the complexity.

A: Using Big-O notation will give you the notion how the time will increase with the n input. In this case, if foo() have always the same argument, the behavior will be constant. But keep this in mind, almost metrics used to measure complexity on time or/and memory only makes sense for a big n, because when the input is small the performance will be anyway high. So, in Big-O, you will look to your fucntion for an increasing n, then will be measurable and comparable.
I hope this will help you.

A: The big O of n (O (n)) notation allows to obtain an order of n for the execution time of your algorithm depending on the increase of n during the function. For example, if the complexity of your algorithm (foo(n)) is in order of (n ^ 2) (O(n²)) then in the worst case (when your algorithm performs a maximum of loop turns), n which is a variable which represents the size of the input data will be in order of n ^ 2. I hope it helped you

A: No.
O(n) simply means that as n gets large, the time it takes the function to execute is proportional to n; In other words, it's a qualitative statement, not a quantitative one.  The time complexity of foo is O(n) whether the input is 4, 4000, 4000000, or 4000000000; all O(n) says is that the runtime grows linearly with n.
O(4) implies that the runtime is constant regardless of the size of the input - it's equivalent to writing O(1).  Your function cannot be both O(n) and O(4).


text:
Q: ListView control for Silverlight 4? It seems like Silverlight 4 does not have a ListView control, unless I am missing something.  Or a control that's basically replicates its function (e.g. re-sizable column headers, etc...).
Is there an example of how to create something similar?  I am after a setup like this:

A: You can use the DataGrid control. It has re-sizable column headers, column-click ordering, grouping, in-place editing, etc.

A: For your case a DataGrid makes sence as Rafa already stated.
Just for reference issues, an equivalent to ListView for Silverlight would be ItemsControl.


text:
Q: `PRAGMA ignore_check_constraints = ON;` does not work I have a question about PRAGMA ignore_check_constraints on sqlite3. I did setted it ON, but apparently it does not work, cause when I try to insert some data, the error "NOT NULL constraint" is raised.
Please, somebody can tell me what is wrong?

A: The documentation for ignore_check_constraints:

PRAGMA ignore_check_constraints = boolean;
This pragma enables or disables the enforcement of CHECK constraints. The default setting is off, meaning that CHECK constraints are enforced by default.

It only mentions CHECK constraints, so I assume it only applies to them, not NOT NULL and UNIQUE constraints.


text:
Q: how to bypass mozilla confirm alert box When i try to go to last visited page on my website in mozilla i get this message "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier". Can anyone tell me how to bypass this. This is so frustrating. i have used php on my website

A: Yes. Redirect user to the same page or to another page so it won't show again
 header("Location: ".$_SERVER['PHP_SELF']);

However, PHP_SELF is dangerous, please use current page name instead of it.

A: Use the Post-Redirect-Get method.

A: Use method="get" in your forms, when it's not necessary to use "post". the POST method should be used to submit sensitive / huge number of data.
Or, if your form doesn't have to show up again, redirect the page using the Location header, after submitting the POST form.

A: After processing a POST request, redirect to another page (using GET). In that way, the browser won't prompt for it anymore. Note that your application must support it.
header('Location: /your/page.php');

Alternatively, if a POST request is not necessary, use method="get" in your <form> elements.


text:
Q: Where to save "next pathname" if redirecting to Login in react-router? I use react-router and react-router-redux, I will redirect user to Login page if he tries to visit a page requiring logged in without logging in:
<Route path="/react/myprofile" component={MyProfile} onEnter={requireAuth} /></Route>

function requireAuth(nextState, replace) {
   const state_user = store.getState().auth.user;
   if (!state_user) {
     console.log('not logged in, redirect')
     replace({
       pathname: '/react/login',
       state: { nextPathname: nextState.location.pathname }
     })
   }
}

And after the user logs in, I will redirect the user to "/react/myprofile": in my redux-saga, I do the following:
const route_state = get routing state from the store;
redirectTo(route_state.locationBeforeTransitions.state.nextPathname);

As above, I have to retrieve the information from  route_state.locationBeforeTransitions.state.nextPathname, it is too verbose, and it seems strange to do as this.
I wonder if there is a better way to do this? Thanks.

A: You can create a selector to extract the relevent piece of state and use it with the select effect from inside your saga
// for example in some file selectors
export const nextPathSelector = state => ...

// in some sagas.js file
import { nextPathSelector } from './selectors'
import { call, select, ... } from 'redux-saga/effects'

function* saga() {
  ...
  const nextPath = yield select( nextPathSelector )
  yield call(redirectTo, nextPath)
}

Using selectors makes your sagas independant from the state shape. And using the select effect you can test the logic of the saga without moking the whole store.  For example
const gen = saga()

assert.deepEqual(
   gen.next().value,
  select( nextPathSelector )
)

assert.deepEqual(
   gen.next('dummy-path').value,
   call(redirectTo, 'dummy-path')
)


text:
Q: VAE reconstructed images are extremely blurry I am very new to machine learning and have build a VAE from the Keras VAE code example. I only changed a few layers in the model. I trained the model on the Kaggle cats and dogs dataset and then tried to reconstruct a few images. All the reconstructed images looked the same just like these Reconstructed Images. What could be the cause of this? Is it due to a bad model, short training time or do I have a mistake in reconstructing the images?
The encoder model:
latent_dim = 2
encoder_inputs = keras.Input(shape=(328, 328, 3))
x = layers.Conv2D(32, 3, strides=2, padding="same")(encoder_inputs)
x = layers.Activation("relu")(x)
x = layers.BatchNormalization()(x)
x = layers.Conv2D(64, 3,strides=2, padding="same")(x)
x = layers.Activation("relu")(x)
x = layers.BatchNormalization()(x)
x = layers.Conv2D(128, 3,strides=2, padding="same")(x)  #neu
x = layers.Activation("relu")(x)
x = layers.BatchNormalization()(x)
x = layers.Flatten()(x)
x = layers.Dense(16, activation="relu")(x)
z_mean = layers.Dense(latent_dim, name="z_mean")(x)
z_log_var = layers.Dense(latent_dim, name="z_log_var")(x)
z = Sampling()([z_mean, z_log_var])
encoder = keras.Model(encoder_inputs, [z_mean, z_log_var, z], name="encoder")
encoder.summary()

The decoder model:
x = layers.Dense(41 * 41 * 128, activation="relu")(latent_inputs)
x = layers.Reshape((41, 41, 128))(x)
x = layers.Conv2DTranspose(128, 3, activation="relu", strides=2, padding="same")(x)
x = layers.BatchNormalization()(x)
x = layers.Conv2DTranspose(64, 3, activation="relu", strides=2, padding="same")(x)
x = layers.BatchNormalization()(x)
x = layers.Conv2DTranspose(32, 3, activation="relu", strides=2, padding="same")(x)
x = layers.BatchNormalization()(x)
decoder_outputs = layers.Conv2DTranspose(3, 3, activation="sigmoid", padding="same")(x)
decoder = keras.Model(latent_inputs, decoder_outputs, name="decoder")
decoder.summary()

The training:
train_data_dir ='/content/PetImages'
nb_train_samples = 200
nb_epoch = 50
batch_size = 32
img_width = 328
img_height = 328

def fixed_generator(generator):
    for batch in generator:
        yield (batch, batch)

train_datagen = ImageDataGenerator(
        rescale=1./255,
        )

train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode=None)

vae = VAE(encoder, decoder)
vae.compile(optimizer=keras.optimizers.Adam())
vae.fit(
        fixed_generator(train_generator),
        steps_per_epoch=nb_train_samples,
        epochs=nb_epoch,
        )

And reconstructing the images:
import matplotlib.pyplot as plt

test2_datagen = ImageDataGenerator(rescale=1./255)

test2_generator = test2_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        batch_size=10,
        class_mode=None)

sample_img = next(test2_generator)

z_points = vae.encoder.predict(sample_img)

reconst_images = vae.decoder.predict(z_points)

fig = plt.figure(figsize=(10, 8))
fig.subplots_adjust(hspace=0.1, wspace=0.1)

n_to_show =2

for i in range(n_to_show):
    img = sample_img[i].squeeze()
    sub = fig.add_subplot(2, n_to_show, i+1)
    sub.axis('off')
    sub.imshow(img)

for i in range(n_to_show):
    img = reconst_images[i].squeeze()
    sub = fig.add_subplot(2, n_to_show, i+n_to_show+1)
    sub.axis('off')
    sub.imshow(img)


text:
Q: Preventing the defaults of unset object properties from being overridden in a JS function So, I have a function with an object as a parameter:
function example(options = { param1: true, param2: 42 })
{
   return options.param2;
}

The problem is, if I call the function with parameters like this:
example({ param1: false });

the default for options.param2 gets overridden and set to undefined, even though it wasn't defined when the function was called. I realize why this is (the object is all one parameter so the entire thing gets set when you call the function), but is there any easy way to prevent this from happening, short of making all of the object parameters their own arguments in the function?

A: Destructure the argument instead, and assign default destructured values.
function example({ param1 = true, param2 = 42 } = {}) {
   return param2;
}


text:
Q: error when using (For Each) with datatable I try to execute (For Each) loop through records of datatable in vb.net, but it doesn't work and give me an error message (code and msg attach.) it seems that (tblName) couldn't be accepted from vb.net
thank you in advance

A: The idiomatic way in newer .NET versions is to call AsEnumerable on your DataTable:
For Each row In tblName.AsEnumerable()
    ...
Next

Explanation: DataTable is a very old class of the .NET Framework. It dates back to the dark ages where .NET did not have generics. In particular, the return type of its Rows property does not implement IEnumerable<DataRow>, which means that the type of the For Each variable cannot be infered and you still need to use the old (pre-type-inference) syntax of For Each row *As DataRow*.
This has been fixed by adding an extension method AsEnumerable.


text:
Q: why doesn't bower update angular upgrade my angular? I have angular 1.2.3 and I want to upgrade to 1.2.7
> cat bower.json
...
  "dependencies": {
    "json3": "~3.2.4",
    "jquery": "~1.9.1",
    "es5-shim": "~2.0.8",
    "toastr": "~2.0.1",
    "angular-ui-tinymce": "latest",
    "underscore": "~1.5.2",
    "underscore.string": "~2.3.3",
    "angular-ui-utils": "~0.0.4",
    "angular-dragdrop": "~1.0.5",
    "angular-cookies": "~1.2.3",
    "angular-animate": "~1.2.3",
    "angular-resource": "~1.2.3",
    "angular": "~1.2.3"
  },
  "devDependencies": {
    "angular-mocks": "~1.2.3",
    "bootstrap": "~3.0.1",
    "font-awesome": "~4.0.3",
    "angular-bootstrap-affix": "~0.3.0"
  }
...

I don't know what the following output even means...., what is it doing?
> bower update angular
bower angular#~1.x              cached git://github.com/angular/bower-angular.git#1.2.7
bower angular#~1.x            validate 1.2.7 against git://github.com/angular/bower-angular.git#~1.x
bower angular#>= 1.0.2          cached git://github.com/angular/bower-angular.git#1.2.7
bower angular#>= 1.0.2        validate 1.2.7 against git://github.com/angular/bower-angular.git#>= 1.0.2
bower angular#1.2.3             cached git://github.com/angular/bower-angular.git#1.2.3
bower angular#1.2.3           validate 1.2.3 against git://github.com/angular/bower-angular.git#1.2.3
bower angular#~1.2.3            cached git://github.com/angular/bower-angular.git#1.2.7
bower angular#~1.2.3          validate 1.2.7 against git://github.com/angular/bower-angular.git#~1.2.3
bower angular#~1.x                 new version for git://github.com/angular/bower-angular.git#~1.x
bower angular#~1.x             resolve git://github.com/angular/bower-angular.git#~1.x
bower angular#>= 1.0.2             new version for git://github.com/angular/bower-angular.git#>= 1.0.2
bower angular#>= 1.0.2         resolve git://github.com/angular/bower-angular.git#>= 1.0.2
bower angular#~1.2.3               new version for git://github.com/angular/bower-angular.git#~1.2.3
bower angular#~1.2.3           resolve git://github.com/angular/bower-angular.git#~1.2.3
bower angular#~1.x            download https://github.com/angular/bower-angular/archive/v1.2.8-build.2095+sha.28fc80b.tar.gz
bower angular#>= 1.0.2        download https://github.com/angular/bower-angular/archive/v1.2.8-build.2095+sha.28fc80b.tar.gz
bower angular#~1.2.3          download https://github.com/angular/bower-angular/archive/v1.2.8-build.2095+sha.28fc80b.tar.gz
bower angular#>= 1.0.2         extract archive.tar.gz
bower angular#>= 1.0.2        resolved git://github.com/angular/bower-angular.git#1.2.8-build.2095+sha.28fc80b
bower angular#~1.x             extract archive.tar.gz
bower angular#~1.x            resolved git://github.com/angular/bower-angular.git#1.2.8-build.2095+sha.28fc80b
bower angular#~1.2.3           extract archive.tar.gz
bower angular#~1.2.3          resolved git://github.com/angular/bower-angular.git#1.2.8-build.2095+sha.28fc80b

nothing changed?  I'm still on 1.2.3
> git diff
diff --git a/ngapp/app/bower_components/angular/.bower.json b/ngapp/app/bower_components/angular/.bower.json
index dc9d0b6..842a1f3 100644
--- a/ngapp/app/bower_components/angular/.bower.json
+++ b/ngapp/app/bower_components/angular/.bower.json
@@ -11,6 +11,6 @@
     "commit": "b112b099971f4cf016023bdeb00b267e9bf6dfb5"
   },
   "_source": "git://github.com/angular/bower-angular.git",
-  "_target": "~1.2.3",
+  "_target": "1.2.3",
   "_originalSource": "angular"
 }

> bower --version
1.2.8

Am I missing something?
> bower info angular
.... shows all versions including 1.2.7 and 1.2.8-builds as well

A: I think the problem is about this
"angular": "~1.2.3"

https://github.com/isaacs/node-semver/
"Reasonably close to 1.2.3".

so you should change it with
"angular": "1.2.7"

UPDATE:
(it's in the comment but I think it's better point it out)
Note that you can't pass a package name to the update command and only update that individual package: it will still update 'em all. You can get the latest version of a single package by running bower install ; it will just over-write the version you currently have

A: I think your dependencies are preventing you from updating angular in isolation.  E.g., look at bower_components/angular-route/bower.json.  You will see a specific version of angular listed as a dependency ("1.2.3") and not a ~/"reasonably close" specifier" ("~1.2.3").  So you are trying to update just angular, but the farthest that bower can take your angular is the current version since you have other packages that depend on exactly that version.
If you do bower update then bower will have the opportunity to update all your packages, including angular-route and other packages that are holding angular back.  The updates to these packages will now allow bower to update angular while satisfying dependencies.  Also, I think if you identified all those packages depending on a specific angular version (you can see dependencies with bower list) and passed them as arguments like bower update angular angular-mocks angular-resource angular-route angular-sanitize... then bower could also perform the update.


text:
Q: How to dismiss AlertDialog.Builder without onClick methods of buttons? I have these 2 methods to create and destroy AlertDialog which only has progress bar.
public static AlertDialog.Builder showProgressAlertDialog(Context context, String title){
    AlertDialog.Builder builder;
    builder = new AlertDialog.Builder(context, R.style.AlertDialogTheme);
    builder.setTitle(title);
    ProgressBar progressBar = new ProgressBar(context);
    builder.setView(progressBar);
    builder.show();
    return builder;
}

public static void dismissProgressAlertDialog(AlertDialog.Builder builder){
    builder.show().cancel();
}

There are no errors while creating it. However, when I call the dismiss method, application throws the following exception: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Note that, I need to call this method and destroy the dialog from another class, therefore onClick method will not work for me.

A: Use Dismiss() on the instance variable of AlertDialog
private AlertDialog dialog;

onCreate() {
    dialog = createAlertDialog(context, title);
}

public static AlertDialog createAlertDialog(Context context, String title){
    final AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogTheme);
    builder.setTitle(title);
    ProgressBar progressBar = new ProgressBar(context);
    builder.setView(progressBar);
    return builder.create();
}

public static void dismissAlertDialog() {
    dialog.dismiss();
}

A: You should store instance of AlertDialog by a global Field in Class, Now you can access to AlertDialog object in all of the class
private AlertDialog alertDialog;

public void onCreate(){
  this.alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogTheme)
.create();
}

public void show(){
 this.alertDialog.show()
}

public void close(){
 this.alertDialog.dismiss()
}


text:
Q: REST request works with POSTMAN but not RestClient I want to use REST api to download orders from my magento websites.
I used https for my website, so when you requesting http, it automatically convert to https.
My REST request is pretty simple, just include token in the http request header, the request works fine with POSTMAN, but with my c# code, it fails consistently.
My RestClient library:
 public class RestClient
 {
    public string EndPoint { get; set; }
    public HttpVerb Method { get; set; }
    public string ContentType { get; set; }
    public string PostData { get; set; }
    public string Accept { get; set; }

    public RestClient(string endpoint, HttpVerb method, string postData, string contentType)
    {
        EndPoint = endpoint;
        Method = method;
        ContentType = contentType;
        PostData = postData;
    }

      public string MakeRequest(string parameters, Dictionary<string, string> headers,
        out HttpStatusCode httpStatusCode, out bool succeed)
     {
        httpStatusCode = HttpStatusCode.NotFound;
        succeed = false;

        var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);

        request.Method = Method.ToString();
        //request.ContentLength = 0;
        request.ContentType = ContentType;
        if (Accept!=null && Accept != "")
            request.Accept = Accept;

        foreach (var entry in headers)
        {
            request.Headers[entry.Key] = entry.Value;
        }

        if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT))
        {

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(PostData);
            }
        }

        try
        {
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;
                httpStatusCode = response.StatusCode;

                // grab the response
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }

                    }
                }

                succeed = true;
                return responseValue;
            }
        }
        catch (WebException ex)
        {
            var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
            return resp;
        }

        return "";
    }

My code:
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers.Add("Authorization", String.Format("Bearer {0}", credential.Token));

        String url = String.Format("{0}/rest/V1/orders?"
            +"searchCriteria[filter_groups][0][filters][0][field]=updated_at&"
            +"searchCriteria[filter_groups][0][filters][0][value]={1}&"
            +"searchCriteria[filter_groups][0][filters][0][condition_type]=from&"
            +"searchCriteria[filter_groups][1][filters][0][field]=updated_at&"
            +"searchCriteria[filter_groups][1][filters][0][value]={2}&"
            +"searchCriteria[filter_groups][1][filters][0][condition_type]=to",
            credential.WebsiteURL,
            updateStart.ToString(),
            updateEnd.ToString());

        RestClient client = new RestClient(url, HttpVerb.GET, "", "application/json");

        String respJson = null;
        HttpStatusCode code = HttpStatusCode.NotFound;
        bool succeed = false;
        try
        {
            respJson = client.MakeRequest("", headers, out code, out succeed);
        }
        catch (Exception ex)
        {
        }

Does anybody met with before? Thanks!

A: It looks as if you are never setting the Accept header anywhere. This is unlikely to cause a Not Authorized error but it's not your api so who knows.
Also you may wish to consider setting the authorization explicitly by passing the token in either the constructor or the MakeRequest method, and then using
request.Headers.Add("Authorization", myAuthorizationToken);


text:
Q: How to CONCATENATE the output of LSTM and One hot encoding values I'm working on a time series prediction using LSTM for used power. I could implement it with a pure LSTM. But i have categorical values which i one hot encoded.
Now, I want to concatenate the LSTM output and the one hot encoding value then pass it through a dense layer to get my output. Attached is a pics of the architecture i'm trying to implement.