text:
Q: Каким образом можно "подождать" пока данные не придут, и только после этого возвращать значение? В функции которая отправляет запрос и получает данные при помощи Retrofit, return отрабатывает быстрее чем приходят данные с сервера. И таким образом возвращаеться попросту пустое значение.
Вопрос: каким образом можно "подождать" и убедиться что данные успешно пришли, и только затем возвращать значение?
P.S. Я знаю что есть множество способов связанных с корутинами, AsynkTask, Callbacks и прочие. Однако какое решение в данном случае будет наилучшим?
(Приложение базируеться на паттерне MVP, в этом случае Model - это класс RetrofitHelper к которому Presenter обращаеться за данными).
class RetrofitHelper: MainContract.IWeatherModel {

    private val dataList: List<String>? = null

    private var dataTemp: Double? = null
    private var mainData: String? = null
    private var pressureData: Long? = null
    private var humidityData: Long? = null
    private var speedData: Double? = null
    private var sunriseData: Long? = null
    private var sunsetData: Long? = null

    val BASE_URL = "https://api.openweathermap.org/data/2.5/"
    val key = "(key)"
    val units = "metric"

    override fun getWeatherData(city: String): List<String>? {

        val retrofitBuilder = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .build()
            .create(APIService::class.java)

        val retrofitData = retrofitBuilder.getData(city, key, units)

        retrofitData.enqueue(object : Callback<Data> {
            override fun onResponse(call: Call<Data>, response: Response<Data>) {
                val responseBody = response.body()!!

                for (i in responseBody.weather) {
                    mainData = i.main

                }
                dataTemp = responseBody.main.temp
                pressureData = responseBody.main.pressure
                humidityData = responseBody.main.humidity
                speedData = responseBody.wind.speed
                sunriseData = responseBody.sys.sunrise
                sunsetData = responseBody.sys.sunset

                val dataList = listOf(
                    dataTemp.toString(),
                    mainData.toString(),
                    pressureData.toString(),
                    humidityData.toString(),
                    speedData.toString(),
                    sunriseData.toString(),
                    sunsetData.toString()
                )

            }

            override fun onFailure(call: Call<Data>, t: Throwable) {
                Log.d("Failure retrofit!", "$t")
            }
        })
        return dataList
    }
}

A: Корутины в языке Kotlin это очень мощный и удобный инструмент для работы с асинхронным кодом. AsyncTask это боль, устаревший способ, не рекомендуется к использованию.
Чтобы начать использовать Retrofit с корутинами, добавьте ключевое слово suspend в сигнатуру метода в интерфейсе Retrofit-сервиса и уберите обертку Call<Data>:
interface APIService {

    @GET("weather?q=Nuremberg")
    suspend fun getData(): Data

}

Теперь, чтобы иметь возможность выполнить suspend-метод и запустить корутину, имплементируйте CoroutineScope в классе MainActivity:
class MainActivity : AppCompatActivity(), CoroutineScope {

    private lateinit var retrofit: RetrofitHelper
    private lateinit var textView: TextView

    override val coroutineContext: CoroutineContext
        get() = Job() + Dispatchers.Main

    ...

    override fun onStart() {
        super.onStart()
        launch {
            val result = retrofit.getWeatherData()
            textView.text = "result: $result"
        }
    }

}

Главное преимущество корутин перед многими другими способами в том, что асинхронный код пишется последовательно. Нет вложенности из коллбеков.
Чтобы лучше разобраться с корутинами, почитайте в документации на русском, что такое coroutine context и dispatchers.


text:
Q: Add an empty column in WPF GridView I have a ListView (GridView) bound to a collection. For aesthetic reason, I want an empty column at the beginning. If I do
<ListView.View>
    <GridView>
        <GridViewColumn Width="100" />
        <GridViewColumn Header="Col 1" DisplayMemberBinding="{Binding P1}" />
        <GridViewColumn Header="Col 2" DisplayMemberBinding="{Binding P2}" />
        <GridViewColumn Header="Col 3" DisplayMemberBinding="{Binding P3}" />
    </GridView>
</ListView.View>

I get the .ToString() of the ItemSource in the first column. I just want an empty column, and I do not want to bind to an empty string property. Any idea?
I just hope it is not too obvious...

A: Maybe use an empty CellTemplate?
    <GridViewColumn Width="100">
        <GridViewColumn.CellTemplate>
            <DataTemplate />
        </GridViewColumn.CellTemplate>
    </GridViewColumn>

A: Or just don't specify anything...
<GridViewColumn Header="Col 3" Width="500" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++: both classes do not run concurrently its my first time here. My code is suppose to make two ultrasonic sensors function at the same time using an mbed. However, i cant seem to make both classes void us_right() and void us_left() in the code run concurrently. Help please :(
#include "mbed.h"
DigitalOut triggerRight(p9);
DigitalIn echoRight(p10);
DigitalOut triggerLeft(p13);
DigitalIn echoLeft(p14);
//DigitalOut myled(LED1); //monitor trigger
//DigitalOut myled2(LED2); //monitor echo
PwmOut steering(p21);
PwmOut velocity(p22);
int distanceRight = 0, distanceLeft = 0;
int correctionRight = 0, correctionLeft = 0;
Timer sonarRight, sonarLeft;

float vo=0;

// Velocity expects -1 (reverse) to +1 (forward)
void Velocity(float v) {
    v=v+1;
    if (v>=0 && v<=2) {
        if (vo>=1 && v<1) {                 //
            velocity.pulsewidth(0.0014);    // this is required to
            wait(0.1);                      //
            velocity.pulsewidth(0.0015);    // move into reverse
            wait(0.1);                      //
        }                                   //
        velocity.pulsewidth(v/2000+0.001);
        vo=v;
    }
}

// Steering expects -1 (left) to +1 (right)
void Steering(float s) {
    s=s+1;
    if (s>=0 && s<=2) {
        steering.pulsewidth(s/2000+0.001);
    }
}

void us_right() {
    sonarRight.reset();
    sonarRight.start();
    while (echoRight==2) {};
    sonarRight.stop();
    correctionRight = sonarLeft.read_us();
    triggerRight = 1;
    sonarRight.reset();
    wait_us(10.0);
    triggerRight = 0;
    while (echoRight==0) {};
  //  myled2=echoRight;
    sonarRight.start();
    while (echoRight==1) {};
    sonarRight.stop();
    distanceRight = ((sonarRight.read_us()-correctionRight)/58.0);
    printf("Distance from Right is: %d cm \n\r",distanceRight);
}

void us_left() {
    sonarLeft.reset();
    sonarLeft.start();
    while (echoLeft==2) {};
    sonarLeft.stop();
    correctionLeft = sonarLeft.read_us();
    triggerLeft = 1;
    sonarLeft.reset();
    wait_us(10.0);
    triggerLeft = 0;
    while (echoLeft==0) {};
  //  myled2=echoLeft;
    sonarLeft.start();
    while (echoLeft==1) {};
    sonarLeft.stop();
    distanceLeft = (sonarLeft.read_us()-correctionLeft)/58.0;
    printf("Distance from Left is: %d cm \n\r",distanceLeft);
}

int main() {
    while(true) {
        us_right();
        us_left();
    }
   if (distanceLeft < 10 || distanceRight < 10) {
            if (distanceLeft < distanceRight) {
                for(int i=0; i>-100; i--) {       // Go left
                    Steering(i/100.0);
                    wait(0.1);
                }
            }
            if (distanceLeft > distanceRight) {
                for(int i=0; i>100; i++) {       // Go Right
                    Steering(i/100.0);
                    wait(0.1);
                }
            }
    }
        wait(0.2);
}

A: You need to use some mechanism to create new threads or processes. Your implementation is sequential, there is nothing you do that tells the code to run concurrently.
You should take a look at some threads libraries (pthreads for example, or if you have access to c++11, there are thread functionality there) or how to create new processes as well as some kind of message passing interface between these processes.

A: Create two threads, one for each ultrasonic sensor:
void read_left_sensor() {
    while (1) {
        // do the reading
        wait(0.5f);
    }
}

int main() {
    Thread left_thread;
    left_thread.start(&read_left_sensor);

    Thread right_thread;
    right_thread.start(&read_right_sensor);

    while (1) {
        // put your control code for the vehicle here
        wait(0.1f);
    }
}

You can use global variables to write to when reading the sensor, and read them in your main loop. The memory is shared.

A: Your first problem is that you have placed code outside of your infinite while(true) loop. This later code will never run. But maybe you know this.
int main() {

    while(true) {
        us_right();
        us_left();
    } // <- Loops back to the start of while()

   // You Never pass this point!!!

   if (distanceLeft < 10 || distanceRight < 10) {
            // Do stuff etc.
   }
   wait(0.2);
}

But, I think you are expecting us_right() and us_left() to happen at exactly the same time. You cannot do that in a sequential environment.
Jan Jongboom is correct in suggesting you could use Threads. This allows the 'OS' to designate time for each piece of code to run. But it is still not truly parallel. Each function (classes are a different thing) will get a chance to run. One will run, and when it is finished (or during a wait) another function will get its chance to run.
As you are using an mbed, I'd suggest that your project is an MBED OS 5 project
(you select this when you start a new project). Otherwise you'll need to use an RTOS library. There is a blinky example using threads that should sum it up well. Here is more info.
Threading can be dangerous for someone without experience. So stick to a simple implementation to start with. Make sure you understand what/why/how you are doing it.
Aside: From a hardware perspective, running ultrasonic sensors in parallel is actually not ideal. They both broadcast the same frequency, and can hear each other. Triggering them at the same time, they interfere with each other.
Imagine two people shouting words in a closed room. If they take turns, it will be obvious what they are saying. If they both shout at the same time, it will be very hard!
So actually, not being able to run in parallel is probably a good thing.


text:
Q: How to numerically solve this non-linear ODE with initial guess function I have the following non-linear differential equation:
{r t''[r] + t'[r] - 1/r Sin[t[r]] Cos[t[r]] + (4 k)/\[Pi] Sin[t[r]]^2
 - h r Sin[t[r]] - r Sin[t[r]] Cos[t[r]] == 0,
 t[0] == \[Pi], t[Infinity] == 0}

with parameters k and h. Let's say for now k=2/3 and h=0. I know that the solution can be well approximated by
t0[r_, r0_] := 2 Pi - 2 ArcTan[Exp[(r - r0)]] - 2 ArcTan[Exp[(r + r0)]]

with some positive r0 on the order of 1. The function looks like this:

Also, one can probably replace the Infinity in the boundary conditions by some value >10.
How can I use this knowledge to (numerically) solve the DE?
So far, I tried replacing Infinity by 20 and using NDSolve with various simple (simple as in not requiring additional parameters) Methods. Sometimes I get a result, but they always look wrong, like this one:

I believe that the key here is to somehow use my knowledge of the approximate solution.

A: Problems like this usually are challenging, because they involve integrating along the separatrix of a nonlinear ODE, and doing so is numerically unstable.  Therefore, no matter how well the initial conditions are chosen, the integration eventually will depart from the desired result.  Nonetheless, integration over a reasonable distance certainly is possible.  For instance, with the parameters given in the question,
r0 = 10^-2; rmax = 10;
s = NDSolveValue[{r t''[r] + t'[r] - 1/r Sin[t[r]] Cos[t[r]] + (4 k)/π Sin[t[r]]^2 -
    h r Sin[t[r]] - r Sin[t[r]] Cos[t[r]] == 0, t[r0] == π,
    t[rmax] == 0} /. h -> 0 /. k -> 2/3, t, {r, r0, rmax}]
Plot[s[r], {r, r0, rmax}, PlotRange -> All, ImageSize -> Large,
    LabelStyle -> Directive[12, Bold, Black]]

However, integrating to r = 15 or so will show instability.  Furthermore, other parameters may show other instability behavior, so some experimentation may be required.  More powerful, but also more burdensome, approaches are available, if needed.
Addendum - Improved Boundary Condition
It often is helpful to solve the linearized ODE at large r.
(Series[(r t''[r] + t'[r] - 1/r Sin[t[r]] Cos[t[r]] + (4 k)/\[Pi] Sin[t[r]]^2 -
    h r Sin[t[r]] - r Sin[t[r]] Cos[t[r]])/r, {t[r], 0, 1}] // Normal) == 0
Flatten@DSolve[%, t[r], r, Assumptions -> r > 0];
cf[e_]:= 100 Count[e, _BesselJ, Infinity] + 100 Count[e, _BesselY, Infinity] + LeafCount[e]
FullSimplify[% /. C[2] -> I Pi C[2]/2 /. C[1] -> C[1] - Pi C[2]/2 /. C[1] -> I C[1],
    r > 0, ComplexityFunction -> cf]
(* (-1 - h - 1/r^2) t[r] + t'[r]/r + t''[r] == 0 *)
(* {t[r] -> BesselI[1, Sqrt[1 + h] r] C[1] + BesselK[1, Sqrt[1 + h] r] C[2]} *)

(The last two lines are needed to obtain an explicitly real solution.)  That the asymptotic solution contains BesselI is another indication that infinitesimal errors in numerical integration can cause the solution to diverge from the separatrix.  The asymptotic solution also can be used to obtain a more accurate boundary condition at large r.
asym = t[r] /. % /. C[1] -> 0;
bc = t'[r]/t[r] == D[asym, r]/asym /. r -> rmax
(* t'[rmax]/t[rmax] == (Sqrt[1 + h] (-BesselK[0, Sqrt[1 + h] rmax] -
   BesselK[2, Sqrt[1 + h] rmax]))/(2 BesselK[1, Sqrt[1 + h] rmax]) *)

Using bc instead of t[rmax] == 0 often permits good accuracy with smaller values of rmax.


text:
Q: Multiple variables in jquery selector I have a code like this
$(".class1 .class2").on('click', function(){
 //Do something
});

I am trying to somehting like this using variables:
var1=".class1";
var2=".class2"

$(var1 var2).on('click', function(){
   //Do something
});

I see var1 and var2 are set to right values, but everytime I try to use 2 variables as selector it fails. When I keep the click trigger unchanged and use var1 or var2 elsewhere in the code individually (just var1 or var2 but not in the same selector list) it works. Any tips?
I figure I use var3 concatenate var1 and var2, but I am trying to reduce another variable.

A: Another option would be to use jQuery objects as your variables. This would avoid having to declare a third variable, which is pretty trivial to do, but if you really want to, there is a way.
This is assuming you are trying to apply the function to any element that has either class, which is not what your existing code example shows ($(".class1 .class2").on) , but to me it seems like this is what you are actually asking for.

var var1 = $('.clickable');
var var2 = $('.anotherClass');

var1.add(var2).on('click', function() {
  console.log('button clicked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="clickable">Click 1</button>
<button class="anotherClass">Click 2</button>

A: You're missing the space. Without it, it becomes .class1.class2 which means the element has to have both classes, not get the descendant of the first one, etc.
var1 = ".class1";
var2 = ".class2";

$(var1 + ' ' + var2).on('click', function(){
   //Do something
});

Another option would be find()
$(var1).find(var2).on(...

Just doing $(var1 var2) would be the same as var fail = var1 var2; it's a syntax error.

A: Your sample code has a JavaScript syntax error (there should be a plus sign between var1 and var2, if you intend to concatenate them).  However, this would produce a selector ".class1.class2" which is not what you're looking for - this would find an element that has both classes, rather than elements that have either class1 or class2.
So, firstly, you need a plus sign to fix your syntax error. But then you'll need a comma between your class names to select the correct elements.
var1=".class1";
var2=".class2"

// Select ".class1,.class2" (either class1 or class2)
$(var1 + ',' + var2).on('click', function(){
   //Do something
});


text:
Q: twitter-node detecting connection end I'm using the twitter-node library for node.js and it works well, however I'm having some minor difficulty handling disconnects.
When twitter disconnects me (I'm connecting a second time from the same server to force a disconnect so I can make sure I'm handling these sorts of issues) it doesn't produce an error or an end event.I thought the following would handle it:
var twitter = new TwitterNode({
  user       : opts.account,
  password   : opts.password,
  track      : opts.hashtags,
  follow     : opts.follow
});

// omitted handlers for receiving tweets/deletes/limit info, but its there
twitter.addListener('error', function(error) {
  console.log('error occoured:'  + error.message);
}).addListener('end', function(resp) {
    sys.puts("wave goodbye... " + resp.statusCode);
}).stream();

However, I don't get either the message from 'end' or 'error' when I'm disconnected. Anyone familiar with this issue?

A: For anyone having this same issue:
There's no notification from twitter-node because it doesn't handle the https libraries close event - by going into the source and adding:
response.on('close', function() { twit.emit('close',this); }

The library now emits a close event when the connection is closed by the remote server (twitter) and you can handle it with a listener in your code like this:
twitterStreamReader = new TwitterNode({...});
twitterStreamReader.addListener('close', function(resp) {
  sys.puts('The server connection has been closed. You may want to do something about that.');
});


text:
Q: MAMP Pro 5.0.3 SSL Failure All sites work fine when SSL is not enabled. Once I enable it, it fails...
I installed MAMP Pro 5.0.3 today hoping that might change things. Tried SSL again, got a failure and this message from the log:
[Tue Aug 07 16:14:53 2018] [notice] Graceful restart requested, doing restart
(48)Address already in use: make_sock: could not bind to address 10.20.1.10:80
no listening sockets available, shutting down
Can anyone help me figure out what is going on here? (Oh, and how to fix it....) Thanks in advance...


text:
Q: this.props.fb is not a function Iam new to redux/react . Iam a doing a simple rest call to fetch some details by triggering an action . But iam getting the following error
BSC.js?d219:24 Uncaught TypeError:
this.props.fb is not a function.

My code is as follows
Actions-
export function fb(){
    return dispatch => {
        dispatch({
          type: SUCCESS,
          payload: {"key1":"value1","key2":"value2"}
         })
       }
}

Container -
import {connect} from 'react-redux';
import React, { Component } from 'react';
import {fb} from '../../actions/b/bSA';

export class BSC extends React.Component {

componentDidMount(){
  this.props.fb();
}

render(){
    return

}
}
export default connect(null, {fB})(BSC);

Reducer
  const initialState = {
  loading: true,
  error: null,
  };
export default function bSR(state = initialState, action) {

switch(action.type) {

  case SUCCESS:

    return {
      ...state,
      loading: false,

    };

    default:
    // ALWAYS have a default case in a reducer
    return state;
    }
    }

What could be the issue ?

A: Just spit balling, but I believe you are lacking a MapStateToProps function which would actually attach that function.

A: You need to declare this method in your container component file.
const mapDispatchToProps = dispatch => {
    return bindActionCreators({
        fb
    }, dispatch);
};

where bindActionCreators is:
import {bindActionCreators} from "redux";

Now pass it to connect method:
export default connect(null, mapDispatchToProps)(BSC);

What happens here is mapDispatchToProps function gets dispatch as function parameter and it has to be passed to action creator to actually dispatch the action. Here bindActionCreators calls your action creator method with the dispatch as parameter and you will be able to dispatch the required action there.


text:
Q: Log prints different outputs I'm having problems with the output of my log messages. I'm using logrus.
I'm developing with VS Code and when I debug my code the log output is:
time="2021-05-04T11:52:11+01:00" level=info msg=message

But when I'm running the app executable or use go run main.go the output is:
INFO[0007] message

I want the first output.
What is happening?
EDIT:
We need to set the formatter as stated in the logrus github.

A: We need to set the formatter as stated in the logrus github


text:
Q: How to fit more complex funtions with sklearn? I used sklearn in python to fit polynomial functions:

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

poly = PolynomialFeatures(degree=2, include_bias=False)
poly_reg_model = LinearRegression()
poly_features = poly.fit_transform(xvalues.reshape(-1, 1))

poly_reg_model.fit(poly_features, y_values)
final_predicted = poly_reg_model.predict(poly_features)
...

Instead of only using x^n parts, I want to incude a (1-x^2)^(1/2) part in the fit-function.
Is this possible with sklearn?
I tried to define a Feature which includes more complex terms but I falied to achieve this.

A: No idea whether it is possible within scikitlearn - after all polynomial fit is constrained to specific polynomial formulations from the mathematical stanndpoint. If you want to fit a formula with some unknown parameters, you can use scipy.optimize.curve_fit. First let us generate some dummy data with noise:
import numpy as np
from matplotlib import pyplot as plt

def f(x):
    return (1-x**2)**(1/2)

xvalues = np.linspace(-1, 1, 30)
yvalues = [f(x) + np.random.randint(-10, 10)/100 for x in xvalues]

Then, we set up our function to be optimized:
from scipy.optimize import curve_fit

def f_opt(x, a, b):
    return (a-x**2)**(1/b)

popt, pcov = curve_fit(f_opt, xvalues, yvalues)

You can of course modify this function to be more elastic. Finally we plot the results
plt.scatter(xvalues, yvalues, label='data')
plt.plot(xvalues, f_opt(xvalues, *popt), 'r-', label='fit')
plt.legend()

So now you can use f_opt(new_x, *popt) to predict new points (alternatively you can print the values and hard-code them). popt basically has the parameters that you specify in f_opt except x - for more details check the documentation I've linked!


text:
Q: How do I simplify $\frac{(bS)^{2}}{(bS)^{2} + y}$ to $\frac{1}{1+\left[\frac{y}{bS}\right]^{2}}$? As the above mentions I have the fraction $\frac{(bS)^{2}}{(bS)^{2} + y}$ and the next step in the equation I am following simply states "it works out to equal" $\frac{1}{1+\left[\frac{y}{bS}\right]^{2}}$.
I'm sure its simple but I am very rusty on my algebra, do I need to multiply by the conjugate?
I'd be very grateful for a worked example
Thanks in advance
edit: I accidentally wrote - when I meant to put + in both denominators. Below is a clarification of terms.
The initial expression was $\frac{M^{2}}{M^{2}+y}$, where M = bS
edit2: Having checked the paper the text I'm following is based on I have found that the initial expression should have been $\frac{M^{2}}{M^{2}+y^{2}}$, solving  the issues I was having.

A: As the good people in the comments suspected, it turns out that the reason I was struggling was because of a typo in the text I was following.
$\frac{(bS)^{2}}{(bS)^{2} + y}$ should have been $\frac{(bS)^{2}}{(bS)^{2} + y^{2}}$
Simplification is therefore a process of dividing both the numerator and denominator by $(bS)^{2}$ to end up with $\frac{1}{1 + [\frac{y}{bS}]^{2}}$


text:
Q: C3.js - stacked bar chart - can I make values to contain instead of stack each other? I'm using C3.js library to create a stacked bar chart (my current code is in jsfiddle on the bottom). The problem is that by default the columns are... stacked. Since I need to create columns with min, average and max values, I'd like the values to rather contain each other, not stack. E.g. if I have min = 10, average = 50 and max = 100, I'd like the bar to be of the height 100, not 160. Is there any built in way to support such behavior?
My current code:

Here is a jsfiddle with my code:
https://jsfiddle.net/gguej6n0/

A: Right, I'm adding this as another answer as it's completely different plus if I changed my original answer the comments would make no sense..
This time I'm taking advantage of err... feature (bug?) found in c3 that caused another user to unintentionally get the effect that you wanted.
c3.js generate a stacked bar from JSON payload
Basically, if you supply the data as json you can get the effect you want if you supply each datum as a separate point
e.g. doing this will overplot min and max on the same column even if they are meant to be stacked
        [{ "x-axis": "0",
            "min": 30
        },
        { "x-axis": "0",
            "max": 40
        }],

Whereas, this way will stack them:
        [{ "x-axis": "0",
            "min": 30,
            "max": 40
        }],

So what we need is a routine to turn the original column-based data into a json object where every datum is parcelled up separately:
http://jsfiddle.net/gvn3y0q6/5/
var data = [
                ['min', 10, 25, 15, 12],
                ['avg', 50, 33, 51, 24],
                ['max', 100, 75, 200, 76]
            ];

var json = [];
data.forEach (function (datum) {
    var series = datum[0];
    for (var i = 1; i < datum.length; i++) {
    var jdatum = {"x-axis": i-1};
    jdatum[series] = datum[i];
    json.push (jdatum);
  }
});

var chart = c3.generate({
    data: {
        x: "x-axis",
        json:json,
        keys: {
           x: "x-axis",
           value: ["max", "avg", "min"]
        },
        groups: [
           ['max', 'avg', 'min']
        ],
        type: 'bar',
    },
     bar: {
        width: {
            ratio: 0.95
        }
     },
     axis: {
       x: {
         padding: {
           left: 0.5,
           right: 0.5,
         }
       }
     },
     tooltip: {
         grouped: true,
         contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
             var data = this.api.data.shown().map (function(series) {
                var matchArr = series.values.filter (function (datum) {
                    return datum.value != undefined && datum.x === d[0].x;
                });
                matchArr[0].name = series.id;
                return matchArr[0];
             });

            return this.getTooltipContent(data, defaultTitleFormat, defaultValueFormat, color);
      }
     }
    });

This time, hiding a series doesn't affect the other series. There's still some tooltip jiggery-pokery needed though otherwise we only get one of the values reported in the tooltip when hovering over one of the 'stacks'. It looks like the data includes a lot of empty value points, which leads me to think this is  a bug of some sort I'm taking advantage of here..
So bearing in mind this might get fixed at some point in the future (or maybe left in, if someone points out it's useful for doing this sort of plot) - then this seems to do what you want

A: I'm not aware of anything built-in that will make the bars merge into one another as you describe, but could a side-by-side view help? If so, remove the grouping.
See https://jsfiddle.net/gguej6n0/1/
var chart = c3.generate({
    bindTo: '#chart',
    data: {
        columns: [
            ['min', 10, 25, 15],
            ['avg', 50, 33, 51],
            ['max', 100, 75, 200]
        ],
        type: 'bar'
    },
    bar: {
            width: {
                ratio: 0.3
        }
    }
});

A: I don't think c3 has an 'overplot' bars option, but you could massage your data...
Basically process the data beforehand so max is actually max - avg, and avg is actually avg  - min
Then the tooltip routine restores the correct totals for showing to a user
Just be careful if you pass the data onto anything else and remember the data has been changed and restore it (or keep a copy)
https://jsfiddle.net/gguej6n0/5/
var data = [
            ['min', 10, 25, 15],
            ['avg', 50, 33, 51],
            ['max', 100, 75, 200]
        ];

    for (var n = data.length-1; n > 0; n--) {
    for (var m = 1; m < data[n].length; m++) {
    data[n][m] -= data[n-1][m];
  }
}

var chart = c3.generate({
      bindTo: '#chart',
    data: {
        columns: data,
        type: 'bar',
        groups: [
            ['min', 'avg', 'max']
        ]
    },
    tooltip: {
      contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
                var dc = d.map (function (dd) {
                    return {value: dd.value, x: dd.x, id: dd.id, name: dd.name, index: dd.index};
            })
                for (var n= 1; n < dc.length; n++) {
                    dc[n].value += dc[n-1].value;
            }
            return this.getTooltipContent(dc, defaultTitleFormat, defaultValueFormat, color);
      }
  }
});


text:
Q: android emulator is start but window show blank screen when i run the andrioid application. emulator is start well, but screen doesn't show anything.

A: I know that this is an old thread, but it seems that when the name of the AVD contains numerals, the AVD will not "boot" at all. The window shows up, but it never even gets to the "A N D R O I D _" screen.
As soon as I recreated an AVD with the name containing only alphabet characters, it would start properly.

A: That seams a problem of 1.6
Upgrade to 2.1 and shall disappear.


text:
Q: How can I check which RAM replacement can I use in my laptop? I've a Nanya (NT2GT64U8HD0BN-AD) 2GB DDR2 SO-DIMM PC2-6400S, 200-pin, Notebook RAM I would like to use this RAM in my old laptop Samsung NC-10 I know that normally is upgraded with PC5300 667MHz SODIMM Memory Upgrade 4 Dell Latitude ATG (DDR2-667MHz) but how can I understand which RAM is suited for my laptop and so if I can use the Nanya? Which parameters I have to look at?

A: You state the laptop is damaged, but you don't mention if you can turn it on or off. I will assume you can still turn it on. If you can turn it on, I suggest you go to the website Crucial (search Crucial memory in a search engine)
They have a scanner which tells you what you have and what you can have.
In regards to parameters and compatibility, most motherboard manufacturer websites provide a compatible list. For example, this pages shows you a motherboard and lists the suitable options.  http://support.asus.com/QVL.aspx?SLanguage=en&p=1&s=39&m=P8Z77-V%20LK&os=&hashedid=J4TfLoZ8TXyFAkFb
However, this website shows the RAM is for your machine http://www.memory4less.com/m4l_itemdetail.aspx?itemid=1442036661


text:
Q: What is the reason for not being able to deduce array size from initializer-string in member variable? Consider the code:
struct Foo
{
    const char str[] = "test";
};

int main()
{
    Foo foo;
}

It fails to compile with both g++ and clang++, spitting out essentially

error: array bound cannot be deduced from an in-class initializer

I understand that this is what the standard probably says, but is there any particular good reason why? Since we have a string literal it seems that the compiler should be able to deduce the size without any problem, similarly to the case when you simply declare an out-of-class const C-like null terminated string.

A: As mentioned in the comments and as answered by @sbabbi, the answer lies in the details
12.6.2 Initializing bases and members [class.base.init]

*In a non-delegating constructor, if a given non-static data member or
  base class is not designated by a mem-initializer-id (including the
  case where there is no mem-initializer-list because the constructor
  has no ctor-initializer) and the entity is not a virtual base class of
  an abstract class (10.4), then

*

*if the entity is a non-static data member that has a brace-or-equal-initializer , the entity is initialized as specified in
  8.5;

*otherwise, if the entity is an anonymous union or a variant member (9.5), no initialization is performed;

*otherwise, the entity is default-initialized

12.6.2 Initializing bases and members [class.base.init]

*If a given non-static data member has both a
  brace-or-equal-initializer and a mem-initializer, the initialization
  specified by the mem-initializer is performed, and the non-static data
  member's brace-or-equal-initializer is ignored. [ Example: Given
struct A {
    int i = /∗ some integer expression with side effects ∗/ ;
    A(int arg) : i(arg) { }
    // ...
};

the A(int) constructor will simply initialize i to the value of arg,
  and the side effects in i's brace-or equal-initializer will not take
  place. — end example ]

So, if there is a non-deleting constructor, the brace-or-equal-initializer is ignored, and the constructor in-member initialization prevails. Thus, for array members for which the size is omitted, the expression becomes ill-formed. §12.6.2, item 9, makes it more explicit where we it specified that the r-value initializer expression is omitted if mem-initialization is performed by the constructor.
Also, the google group dicussion Yet another inconsitent behavior in C++, further elaborates and makes it more lucid. It extends the idea in explaining that brace-or-equal-initializer is a glorified way of an in-member initialization for cases where the in-member initialization for the member does not exist. As an example
struct Foo {
    int i[5] ={1,2,3,4,5};
    int j;
    Foo(): j(0) {};
}

is equivalent to
struct Foo {
    int i[5];
    int j;
    Foo(): j(0), i{1,2,3,4,5} {};
}

but now we see that if the array size was omitted, the expression would be ill-formed.
But then saying that, the compiler could have supported the feature for cases when the member is not initialized by in-member constructor initialization but currently for the sake of uniformity, the standard like many other things, does not support this feature.

A: The reason is that you always have the possibility to override an in-class initializer list in the constructor. So I guess that in the end, it could be very confusing.
struct Foo
{
   Foo() {} // str = "test\0";

   // Implementing this is easier if I can clearly see how big `str` is,
   Foo() : str({'a','b', 'c', 'd'}) {} // str = "abcd0"
   const char str[] = "test";
};

Notice that replacing const char with static constexpr char works perfectly, and probably it is what you want anyway.

A: If the compiler was allowed to support what you described, and the size of str was deduced to 5,
Foo foo = {{"This is not a test"}};

will lead to undefined behavior.


text:
Q: fit() method returns ValueError when using Keras subclassing API I am trying to tidy up my code by moving from the Keras functional API to the subclassing API. The class I came up with so far is below:
class FeedForwardNN(Model):
    def __init__(self, params):

        super().__init__()
        self.params = params
        self.layout = params['layout']

        # Define layers
        self.dense = Dense(units=params['layout'][1],
                           activation=params['activation'],
                           kernel_initializer=params['initializer'])

        self.output_layer = Dense(units=params['layout'][-1],
                            kernel_initializer=params['initializer'])

        self.dropout = Dropout(params['dropout'])
        self.batch_norm = BatchNormalization()

    def call(self, x):

        for layer in self.layout[1:-1]:
            x = self.dropout(self.dense(x))

            if self.params['batch_norm']:
                x = self.batch_norm(x)

        x = self.output_layer(x)

        return x

Where layout is a list of the neurons in each layer (including input and output layers).
However, when fitting the model, the following error is raised:
        ValueError: Input 0 of layer "dense" is incompatible with the layer: expected axis -1 of input shape to have value 5, but received input with shape (None, 100)

    Call arguments received:
      • x=tf.Tensor(shape=(None, 5), dtype=float32)

which seems to occur on the line:
x = self.dropout(self.dense(x))

I checked the shape of the training data X that is passed to the fit() method, and it appears to have the right shape i.e. (number of observations, number of predictors).
Does anyone have an idea of where my mistake is?

A: The problem is that you are using same self.dense layer over and over again in your for loops
for layer in self.layout[1:-1]:
    x = self.dropout(self.dense(x))

After the first loop, x has shape (batch, 100). Then in the second loop, instead of passing this x to the second Dense layer (which you don't seem to have created in the first place), you re-pass it to the first Dense layer, which expects shape (batch, 5), causing the error.
You can create a list of dense layer as follows in __init__
self.denses = [Dense(units=self.layout[i],
                   activation=params['activation'],
                   kernel_initializer=params['initializer']) for i in self.layout[1:-1]]

and call them in sequence
for dense_layer in self.denses:
    x = self.dropout(dense_layer(x))


text:
Q: How do I use LAST_INSERT_ID in a single query one-to-many relationship? I have two tables, questions and answers.
answers contains a key *question_id*
When I create a question, I insert one record to the questions table and several records into the answers table. Is it possible to use LAST_INSERT_ID() or similar to do all this in one query?
I.e. something like
INSERT INTO questions VALUES(NULL, 'My question');

INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 1');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 2');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 3');

Obviously, this query wouldn't work since LAST_INSERT_ID() changes after every statement. Is there anyway to make this work or will I have to break this up into two queries?

A: You can use bulk inserts like this :
INSERT INTO answers VALUES
          (NULL, LAST_INSERT_ID(), 'Answer 1') ,
          (NULL, LAST_INSERT_ID(), 'Answer 2') ,
          (NULL, LAST_INSERT_ID(), 'Answer 3');

A: Try to store de value into a variable
INSERT INTO questions VALUES(NULL, 'My question');
SET @id = (SELECT LAST_INSERT_ID());
INSERT INTO answers VALUES(NULL, @id, 'Answer 1');
INSERT INTO answers VALUES(NULL, @id, 'Answer 2');
INSERT INTO answers VALUES(NULL, @id, 'Answer 3');

I think there is another way to do it but maybe it will give you an idea.


text:
Q: How to populate data with haveInDatabase in _beforeSuite in Codeception What I am trying to do is to insert some data to the Database before the suite starts. The dump is a clean Db and I have multiple suites that will need different starting data.
this is my code right now
namespace Helper;

// here you can define custom actions
// all public methods declared in helper class will be available in $I

use Codeception\TestInterface;

class Contacts extends \Codeception\Module
{
    public $started = false;
    public function _beforeSuite($settings = [])
    {

        parent::_beforeSuite($settings); // TODO: Change the autogenerated stub
        $dba = $this->getModule('Db');

        $dba->haveInDatabase('table1',array('is_published'=>'1','created_by'=>'1',
            'created_by_user'=>'Automated User'));

    }

I don't get any errors but the data is not there when codeception starts

A: Have you got cleanup: true in parameters of Db modules?
It cleans data before each test, so in order to keep data inserted in _beforeSuite, you have to disable cleanup by changing it to cleanup: false.


text:
Q: File handling in C: can't fathom the output I compiled this (gcc compiler) :
#include< stdio.h>

 main() {

    unsigned char ch;
    FILE *fp;
    fp=fopen("trial","r");
    while((ch=getc(fp))!=EOF)
        printf("%c",ch);
    fclose(fp);
}

It gives the follwing:
Warning: comparison is always true due to limited range of the data type

On executing, an endless stream of characters is printed on terminal.
(Assuming I created a file named "trial" before compiling the program and wrote some text in the file.)
Kindly explain the warning.....

A: Because EOF is -1 and your ch is unsigned char which means ch will never become -1.
Instead use int ch;

A: getc() returns an int.  You're truncating (and changing the signedness) it to unsigned char with that assignment, so it will never match EOF.  Just change the type of ch to int and you'll be fine.

A: getc returns an integer for good reason.  The EOF indicator is outside the range of a normal char, because otherwise you could confuse a legitimate character with the EOF indicator.  However, you're assigning the results to a character which confines the answer to fall within the limits of a char value.  In short, you're never going to know when the end of the file has been reached this way.  Make "ch" an int type or assign result from call to getc to an unsigned char type after you compare it with EOF.

A: The EOF value in C is an int while ch here is a char.  The char type is smaller than int and hence can represent less values than int can.  EOF is one of the values which char simply can't ever represent and hence ch will never be equal to EOF.
In this scenario getc actually returns an int so it can represent EOF.  But you are immediately shrinking it to a char and losing that extra information.
Here's a way to properly write this.
int cur;
FILE *fp;
fp=fopen("trial","r");
while((cur = getc(fp))!=EOF) {
  unsigned char ch = cur;
  printf("%c",ch);
}
fclose(fp);


text:
Q: Conditional includes in ASP We have a number of categories with products in an ASP eCommerce site and, based on the category, would like a particular file to be included. For example, if URL is:
viewPrd.asp?idproduct=6&idcategory=18

then based on idCategory=18 I would like to include:
<!--#include file="menu18.asp"-->

If idCategory=19 then I would like to include:
<!--#include file="menu19.asp"-->

and so on. Any assistance would be appreciated.

A: I use a script taken from https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=9796&lngWId=4 (dynamic ASP inclusion)
So after including that script in your code, you just have to write:
myMenu = Request.Querystring("idCategory")
Include("menu"&myMenu&".asp")

A: Unfortunately, include files are a feature of IIS, not ASP. They are included before the page is sent to the ASP-processor that interprets your ASP code.
For this reason you can't have conditional includes.
The includes are already in place when the ASP code is executed.
To have conditional code in ASP you could use script components (WSC files), which you can include/load conditionally, or use big if...then or case.. constructions inside an include.
More info on the use of WSC's can be found here

A: As far i know its not possible on a "elegant way", but i suggest you to take a look in those links:
is it possible to issue dynamic include in asp-classic?
https://support.microsoft.com/en-us/kb/192144
Regards.

A: Yes, its possible. Just leave the include statements outside the <% %> code delimiters.
This is my quick and dirty solution and it works:
<% session("lang") = request.querystring("lang") %>

<%if (session("lang") = "es" or session("lang") = "") then %>
<!--#include file="espanol.asp"-->
<% else %>
<!--#include file="ingles.asp"-->
<% end if %>

<!--#include file="precios.asp"-->

IIS will include the two files, but ASP will use only the file that satisfies the if conditions.


text:
Q: Strange Parcelable implementation My code for saving instance in bundle is working but I don't understand how it is working.
Student's name after clicking on button saving in bundle if I rotate device.
Here is my class
package com.example.app;

import android.os.Parcel;
import android.os.Parcelable;

public class Student implements Parcelable {

   private String firstName;

   private String lastName;

   public Student(String firstName, String lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
   }

   public String getDisplayedName()
   {
       return lastName + " " + firstName;
   }

   @Override
   public int describeContents() {
       return 0;
   }

   @Override
   public void writeToParcel(Parcel dest, int flags) {

   }
}

You can see here that I don't write any code in method writeToParcel and don't create CREATOR field in class.
However it is working on all my devices include emulator device
Here is my activity code
package com.example.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends Activity {

private Student student;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button generateButton = (Button) findViewById(R.id.generate);
    generateButton.setOnClickListener(generateStudentName);
    if (savedInstanceState != null) {
        student = savedInstanceState.getParcelable("student");
        writeStudent();
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putParcelable("student", student);
    super.onSaveInstanceState(outState);
}

private void writeStudent() {
    final TextView studentName = (TextView) findViewById(R.id.student_name);
    studentName.setText(student.getDisplayedName());
}

private View.OnClickListener generateStudentName = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Random randomGenerator = new Random();
        student = new Student(String.valueOf(randomGenerator.nextInt(10000)), String.valueOf(randomGenerator.nextInt(10000)));
        writeStudent();
    }
};

}

Why it happens?


text: Q: Is the Info Hash of torrent file only generared by the file? Uploader usually post the info hash of torrent file on the webpage, is this the same to sha1, 2 ,256... hashsum which only direct to the original file?


text:
Q: how can i use function value in Domain filter I am getting current login user id by following function
    def _get_user_name(self, cr, uid, *args):
    user_obj = self.pool.get('res.users')
    user_value = user_obj.browse(cr, uid, uid)
    return user_value.id or False

and now i want to use its value in this field's Domain like ....
    x_trainer_id = fields.Many2one('res.partner', string='Trainer',domain=[('user_id.id','=','get_user_name')])

How is it possible? I'll be very thankful....

A: you can do it as below:
x_trainer_id = fields.Many2one('res.partner', string='Trainer',domain=lambda self: [('id', '=', self.env.uid)])

pass domain=lambda self: [('id', '=', self.env.uid)]


text:
Q: Animate UITableView change I have a two row tableview (username and password) and when the user hits enter it tries to login and switches the two cells to a single loading cell. While I am going from 2 to 1 cell, the new cell is twice as large (minus 1 px for the separator). I would like to fade between the two states.
How would I do this?

A: I think you should use two table views instead. And when user logs in fadeout the present tableview to show the tableview below it.
Well this is a suggestion only.


text:
Q: when i insert data in two tables in mysql the second table check that if pCode is already exist or not I have an html page that can be store ItemCode,ItemName,Quantity,Price. I have two tables in mysql (1)purchase(2)stock. i want to store data in both tables but in stock table i don't want to store duplicate value i want when in stock table have same pCode that is already exist in stock table then it can be update only quantity of that product. it works for only in one row when i entered more than one row which is already exist in stock table. it can only update tha quantity of last row.
HTML

        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

            <form action="newjsp.jsp" method="post">

        No.
        Item Code
        Item Name
        quantity
        price
        Action

        1
        <input type="text" class="inputs" name="itemcode_1" id="itemcode_1" />
        <input type="text" class="inputs" name="itemname_1" id="itemname_1" />
        <input type="text" class="inputs" name="quantity_1" id="quantity_1" />
        <input type="text" class="inputs lst" name="price_1"  id="price_1" />
        <input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/>

                <input type="submit" value="submit"/>
        </form>

JQuery

Insert JSP File
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page language="java"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@page import="java.util.Date"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" rel="stylesheet" href="Bootstrap/bootstrap.css"/>
        <title>JSP Page</title>

        <%

        try
        {
            String Itemcode=null;
           String Itemname=null;
           String quantity=null;
           String price=null;
           int cc=1;
           String qty=null;

           String count[]=request.getParameterValues("count");
           for(String c:count)
           {
           cc=Integer.valueOf(c);

           }

           out.println(cc+"
");

          String query = "INSERT INTO jquery ";
          String query1="INSERT INTO stock";
          for (int i = 1; i<=cc; i++)
          {
           Itemcode=request.getParameter("itemcode_" + i);
           Itemname=request.getParameter("itemname_" + i);
           quantity=request.getParameter("quantity_" + i);
           price=request.getParameter("price_" + i);
          if(Itemname!=null && quantity!=null && price!=null)
              {
           query += ((i == 1) ? "values" : ",") + "('"+Itemcode+"','"+Itemname+"','"+quantity+"','"+price+"')";

           query1 += ((i == 1) ? "values" : ",") + "('"+Itemcode+"','"+Itemname+"','"+quantity+"','"+price+"')";
              }
              else
              {

              }
          }
          Class.forName("com.mysql.jdbc.Driver");
          Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/atm","root","root");
          Statement st=con.createStatement();
          ResultSet rs;

          int o=st.executeUpdate(query);
          out.println("Success"+"
");

         rs=st.executeQuery("SELECT * FROM stock");
         while(rs.next())
         {
           qty=rs.getString("quantity");

         }
          if(qty!=null)
          {
          int q=st.executeUpdate("update stock set  quantity=quantity+'"+quantity+"', amount='"+price+"' where item_code='"+Itemcode+"'");
         }

          else
          {
        int p=st.executeUpdate(query1);

         }

          }
        catch(Exception e)
        {
          System.out.println(e);
        }

        %>


text:
Q: Inappropriate column size when using \multicolumn I have a column size problem when using \multicolumn, please see the following pic:

The size of the second column is bigger than the size of the first column, which should be balanced (like the rest of the columns).
The corresponding latex code:
\begin{table}[!t]
    \renewcommand\tabcolsep{5.5pt}
    \caption{Performance}
    \begin{center}
        \begin{tabular}{|c|c|c|c|c|c|c|c|c|}
            \hline
            \multirow{2}{*}{Method} & \multicolumn{2}{c|}{\emph{shapes\_translation}} & \multicolumn{2}{c|}{\emph{shapes\_6dof}}   & \multicolumn{2}{c|}{\emph{poster\_6dof}}   & \multicolumn{2}{c|}{\emph{slider\_depth}} \\ \cline{2-9}
            & AOR                 & AR                 & AOR              & AR               & AOR              & AR               & AOR                & AR            \\ \hline
            SiamFC\cite{bertinetto2016fully}                  & 0.812             & 0.940            & 0.835          & 0.968          & 0.830          & 0.956          & 0.909            & \textbf{1.000}       \\ \hline
            ECO\cite{danelljan2017eco}                     & 0.823               & 0.943              & 0.847            & 0.969            & 0.846            & 0.960            & \textbf{0.947}              & \textbf{1.000}         \\ \hline
            SiamRPN++\cite{Li_2019_CVPR}     & 0.790             & 0.942            & 0.779          & 0.972          & 0.753          & 0.899          & 0.907            & \textbf{1.000}       \\ \hline
            ATOM\cite{Danelljan_2019_CVPR}       & 0.815             & 0.945            & 0.803          & 0.974          & 0.835          & 0.961          & 0.897            & \textbf{1.000}       \\ \hline
            E-MS\cite{barranco2018real}                  & 0.675    & 0.768   & 0.612 & 0.668 & 0.417 & 0.373 & 0.447   & 0.350  \\ \hline
            RMRNet-TS                  & 0.491    & 0.564   & 0.467 & 0.509 & 0.504 & 0.558 & 0.814   & 0.993  \\ \hline
            RMRNet                  & \textbf{0.836}    & \textbf{0.951}   & \textbf{0.866} & \textbf{0.980} & \textbf{0.859} & \textbf{0.962} & 0.915   & \textbf{1.000}  \\ \hline
        \end{tabular}
    \end{center}
\end{table}

I have found that 'shapes_translation' is longer than the other titles (such as shapes_6dof), which makes the unbalanced column size. But I do not know how to fix it. Any help will be appreciated, thank you in advance.
Update:
I have modified the code according to Ben's answer in Table column widths disproportionate due to multicolumn cell being too long
The new table and the new code:

\newlength\widthSubTabTwo
\settowidth\widthSubTabTwo{shapes\_translation}
\newlength\lengthTwo
\setlength\lengthTwo{\dimexpr(\widthSubTabTwo+2\tabcolsep)/2-2\tabcolsep\relax}

\begin{table}[!t]
    \renewcommand\tabcolsep{5.5pt}
    \caption{Performance}
    \begin{center}
        \begin{tabular}{|c|*{2}{w{c}{\lengthTwo}}|c|c|c|c|c|c|}
            \hline
            \multirow{2}{*}{Method} & \multicolumn{2}{c|}{\emph{shapes\_translation}} & \multicolumn{2}{c|}{\emph{shapes\_6dof}}   & \multicolumn{2}{c|}{\emph{poster\_6dof}}   & \multicolumn{2}{c|}{\emph{slider\_depth}} \\ \cline{2-9}
            & AOR                 & AR                 & AOR              & AR               & AOR              & AR               & AOR                & AR            \\ \hline
            SiamFC\cite{bertinetto2016fully}                  & 0.812             & 0.940            & 0.835          & 0.968          & 0.830          & 0.956          & 0.909            & \textbf{1.000}       \\ \hline
            ECO\cite{danelljan2017eco}                     & 0.823               & 0.943              & 0.847            & 0.969            & 0.846            & 0.960            & \textbf{0.947}              & \textbf{1.000}         \\ \hline
            SiamRPN++\cite{Li_2019_CVPR}     & 0.790             & 0.942            & 0.779          & 0.972          & 0.753          & 0.899          & 0.907            & \textbf{1.000}       \\ \hline
            ATOM\cite{Danelljan_2019_CVPR}       & 0.815             & 0.945            & 0.803          & 0.974          & 0.835          & 0.961          & 0.897            & \textbf{1.000}       \\ \hline
            E-MS\cite{barranco2018real}                  & 0.675    & 0.768   & 0.612 & 0.668 & 0.417 & 0.373 & 0.447   & 0.350  \\ \hline
            RMRNet-TS                  & 0.491    & 0.564   & 0.467 & 0.509 & 0.504 & 0.558 & 0.814   & 0.993  \\ \hline
            RMRNet                  & \textbf{0.836}    & \textbf{0.951}   & \textbf{0.866} & \textbf{0.980} & \textbf{0.859} & \textbf{0.962} & 0.915   & \textbf{1.000}  \\ \hline
        \end{tabular}
    \end{center}
\end{table}

Then, the problem is solved, but I have a new problem. The red vertical line is missing. I am a newbie at this, please help.

A: Let us consider four versions of the table.

*

*The status quo, i.e., the current situation (while giving the table a more open "look" and leaving off the final three data rows for a more compact appearance). Observe the excessive width of 2nd data column.

*Table 2 is similar to Table 1, but with the first two data columns now having equal width and being jointly centered below the common header cell. Note that data columns 1 and 2 are noticeably wider than data columns 3 thru 8.

*In Table 3, we abbreviate shapes\_translation to shapes\_transl., allowing all 8 data columns to be equally wide.

*Table 4 uses a (much) smaller font size for \emph{shapes\_translation}, also allowing all 8 data columns to be equally wide.

Fine typography often requires us to make trade-offs.

*

*While we may readily conclude that Table 1 is problematic and Table 4 is no good (because of the minute font size used in one of the header cells), it's not clear that Table 2 is really all that much better than Table 1. Why?

*In Table 2, we've exchanged one typographic problem (the 2nd data column being much wider than the other 7) with another one (the widths of first two data columns are noticeably larger than the widths of the other six).

*Table 3, whose trade-off consists of abbreviating the header cell, may be best -- or, at least, "least bad" -- overall, as it allows the widths of the 8 data columns to be (very nearly) equal, giving the table a nicely balanced "look".

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{newtxtext,newtxmath}
\usepackage{booktabs}
\usepackage{array,calc,caption}
\captionsetup{skip=0.25\baselineskip}
\newlength\mylen
\setlength\mylen{\widthof{\emph{shapes\_translation}}/2}
\begin{document}

\begin{table}[!ht]

\setlength\tabcolsep{0pt} % let LaTeX figure out optimal amount of intercolumn whitespace

\caption{Status quo: 2nd data column much wider than the other 7}
\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}} l *{8}{c} }
\toprule
Method & \multicolumn{2}{c}{\emph{shapes\_translation}} &
         \multicolumn{2}{c}{\emph{shapes\_6dof}}   &
         \multicolumn{2}{c}{\emph{poster\_6dof}}   &
         \multicolumn{2}{c}{\emph{slider\_depth}} \\
\cmidrule{2-3} \cmidrule{4-5} \cmidrule{6-7} \cmidrule{8-9}
& AOR & AR & AOR & AR & AOR & AR & AOR & AR\\
\midrule
SiamFC\cite{bertinetto2016fully} & 0.812 & 0.940 & 0.835 & 0.968 & 0.830 & 0.956 & 0.909 & \textbf{1.000}       \\
ECO\cite{danelljan2017eco}       & 0.823 & 0.943 & 0.847 & 0.969 & 0.846 & 0.960 & \textbf{0.947} & \textbf{1.000} \\
SiamRPN++\cite{Li_2019_CVPR}     & 0.790 & 0.942 & 0.779 & 0.972 & 0.753 & 0.899 & 0.907 & \textbf{1.000}       \\
ATOM\cite{Danelljan_2019_CVPR}   & 0.815 & 0.945 & 0.803 & 0.974 & 0.835 & 0.961 & 0.897 & \textbf{1.000}       \\
%E-MS\cite{barranco2018real}      & 0.675 & 0.768 & 0.612 & 0.668 & 0.417 & 0.373 & 0.447 & 0.350  \\
%RMRNet-TS                        & 0.491 & 0.564 & 0.467 & 0.509 & 0.504 & 0.558 & 0.814 & 0.993  \\
%RMRNet                           & \textbf{0.836}& \textbf{0.951}& \textbf{0.866}& \textbf{0.980} &\textbf{0.859} &\textbf{0.962} & 0.915 & \textbf{1.000} \\
\bottomrule
\end{tabular*}

\bigskip
\caption{Center-set first two data columns}
\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}} l wc{\mylen}@{}wc{\mylen} *{6}{c} }
\toprule
Method & \multicolumn{2}{c}{\emph{shapes\_translation}} &
         \multicolumn{2}{c}{\emph{shapes\_6dof}}   &
         \multicolumn{2}{c}{\emph{poster\_6dof}}   &
         \multicolumn{2}{c}{\emph{slider\_depth}} \\
\cmidrule{2-3} \cmidrule{4-5} \cmidrule{6-7} \cmidrule{8-9}
& AOR & AR & AOR & AR & AOR & AR & AOR & AR\\
\midrule
SiamFC\cite{bertinetto2016fully} & 0.812 & 0.940 & 0.835 & 0.968 & 0.830 & 0.956 & 0.909 & \textbf{1.000}       \\
ECO\cite{danelljan2017eco}       & 0.823 & 0.943 & 0.847 & 0.969 & 0.846 & 0.960 & \textbf{0.947} & \textbf{1.000} \\
SiamRPN++\cite{Li_2019_CVPR}     & 0.790 & 0.942 & 0.779 & 0.972 & 0.753 & 0.899 & 0.907 & \textbf{1.000}       \\
ATOM\cite{Danelljan_2019_CVPR}   & 0.815 & 0.945 & 0.803 & 0.974 & 0.835 & 0.961 & 0.897 & \textbf{1.000}       \\
%E-MS\cite{barranco2018real}      & 0.675 & 0.768 & 0.612 & 0.668 & 0.417 & 0.373 & 0.447 & 0.350  \\
%RMRNet-TS                        & 0.491 & 0.564 & 0.467 & 0.509 & 0.504 & 0.558 & 0.814 & 0.993  \\
%RMRNet                           & \textbf{0.836}& \textbf{0.951}& \textbf{0.866}& \textbf{0.980} &\textbf{0.859} &\textbf{0.962} & 0.915 & \textbf{1.000} \\
\bottomrule
\end{tabular*}

\bigskip
\caption{Use abbreviation in header cell}
\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}} l *{8}{c} }
\toprule
Method & \multicolumn{2}{c}{\emph{shapes\_transl.}} &
         \multicolumn{2}{c}{\emph{shapes\_6dof}}   &
         \multicolumn{2}{c}{\emph{poster\_6dof}}   &
         \multicolumn{2}{c}{\emph{slider\_depth}} \\
\cmidrule{2-3} \cmidrule{4-5} \cmidrule{6-7} \cmidrule{8-9}
& AOR & AR & AOR & AR & AOR & AR & AOR & AR\\
\midrule
SiamFC\cite{bertinetto2016fully} & 0.812 & 0.940 & 0.835 & 0.968 & 0.830 & 0.956 & 0.909 & \textbf{1.000}       \\
ECO\cite{danelljan2017eco}       & 0.823 & 0.943 & 0.847 & 0.969 & 0.846 & 0.960 & \textbf{0.947} & \textbf{1.000} \\
SiamRPN++\cite{Li_2019_CVPR}     & 0.790 & 0.942 & 0.779 & 0.972 & 0.753 & 0.899 & 0.907 & \textbf{1.000}       \\
ATOM\cite{Danelljan_2019_CVPR}   & 0.815 & 0.945 & 0.803 & 0.974 & 0.835 & 0.961 & 0.897 & \textbf{1.000}       \\
%E-MS\cite{barranco2018real}      & 0.675 & 0.768 & 0.612 & 0.668 & 0.417 & 0.373 & 0.447 & 0.350  \\
%RMRNet-TS                        & 0.491 & 0.564 & 0.467 & 0.509 & 0.504 & 0.558 & 0.814 & 0.993  \\
%RMRNet                           & \textbf{0.836}& \textbf{0.951}& \textbf{0.866}& \textbf{0.980} &\textbf{0.859} &\textbf{0.962} & 0.915 & \textbf{1.000} \\
\bottomrule
\end{tabular*}

\bigskip
\caption{Use a smaller font size in header cell}
\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}} l *{8}{c} }
\toprule
Method & \multicolumn{2}{c}{\scriptsize\emph{shapes\_translation}} &
         \multicolumn{2}{c}{\emph{shapes\_6dof}}   &
         \multicolumn{2}{c}{\emph{poster\_6dof}}   &
         \multicolumn{2}{c}{\emph{slider\_depth}} \\
\cmidrule{2-3} \cmidrule{4-5} \cmidrule{6-7} \cmidrule{8-9}
& AOR & AR & AOR & AR & AOR & AR & AOR & AR\\
\midrule
SiamFC\cite{bertinetto2016fully} & 0.812 & 0.940 & 0.835 & 0.968 & 0.830 & 0.956 & 0.909 & \textbf{1.000}       \\
ECO\cite{danelljan2017eco}       & 0.823 & 0.943 & 0.847 & 0.969 & 0.846 & 0.960 & \textbf{0.947} & \textbf{1.000} \\
SiamRPN++\cite{Li_2019_CVPR}     & 0.790 & 0.942 & 0.779 & 0.972 & 0.753 & 0.899 & 0.907 & \textbf{1.000}       \\
ATOM\cite{Danelljan_2019_CVPR}   & 0.815 & 0.945 & 0.803 & 0.974 & 0.835 & 0.961 & 0.897 & \textbf{1.000}       \\
%E-MS\cite{barranco2018real}      & 0.675 & 0.768 & 0.612 & 0.668 & 0.417 & 0.373 & 0.447 & 0.350  \\
%RMRNet-TS                        & 0.491 & 0.564 & 0.467 & 0.509 & 0.504 & 0.558 & 0.814 & 0.993  \\
%RMRNet                           & \textbf{0.836}& \textbf{0.951}& \textbf{0.866}& \textbf{0.980} &\textbf{0.859} &\textbf{0.962} & 0.915 & \textbf{1.000} \\
\bottomrule
\end{tabular*}

\end{table}
\end{document}

A: The new LaTeX3 package tabularray has an option hspan=even for distributing extra space evenly:
\documentclass{article}

\usepackage{tabularray}
\usepackage{caption}

\begin{document}

\begin{table}[!t]
    \centering
    \caption{Performance}
        \begin{tblr}{
          colspec = |c|c|c|c|c|c|c|c|c|,
          cell{1}{1} = {r=2}{c}, % multirow
          cell{1}{even} = {c=2}{c}, % multicolumn
          hspan = even, % distribute extra space evenly
          colsep = 5.5pt,
        }
        \hline
          Method & \emph{shapes\_translation} & & \emph{shapes\_6dof} & & \emph{poster\_6dof} & & \emph{slider\_depth} & \\
        \cline{2-9}
                 & AOR & AR                     & AOR & AR              & AOR & AR              & AOR & AR \\
        \hline
            SiamFC\cite{bertinetto2016fully}
                 & 0.812  & 0.940               & 0.835    & 0.968      & 0.830   & 0.956       & 0.909 & \textbf{1.000} \\
        \hline
            ECO\cite{danelljan2017eco}
                 & 0.823  & 0.943 & 0.847  & 0.969 & 0.846   & 0.960  & \textbf{0.947}  & \textbf{1.000} \\
        \hline
            SiamRPN++\cite{Li_2019_CVPR}
                 & 0.790  & 0.942  & 0.779  & 0.972 & 0.753  & 0.899  & 0.907 & \textbf{1.000} \\
        \hline
            ATOM\cite{Danelljan_2019_CVPR}
                 & 0.815   & 0.945  & 0.803  & 0.974 & 0.835  & 0.961  & 0.897 & \textbf{1.000} \\
        \hline
            E-MS\cite{barranco2018real}
                 & 0.675    & 0.768   & 0.612 & 0.668 & 0.417 & 0.373 & 0.447   & 0.350  \\
        \hline
            RMRNet-TS
                 & 0.491    & 0.564   & 0.467 & 0.509 & 0.504 & 0.558 & 0.814   & 0.993  \\ \hline
            RMRNet
                 & \textbf{0.836} & \textbf{0.951} & \textbf{0.866} & \textbf{0.980} & \textbf{0.859} & \textbf{0.962} & 0.915   & \textbf{1.000}  \\
        \hline
        \end{tblr}
\end{table}

\end{document}


text:
Q: watson special character, repeat posts, and url handling in using watson personality insights API, i've already note some odd trends, including many scored at a mean value across dimensions (e.g. agreeableness with many around .27), making me thing it's imputing to something.
Upon review I've note a language misalign issue (i.e. if it thinks it's english, you could get weird results if it's, say spanish), which has lead me to ask, but not find answer to:
how does watson handle:
1) urls in the message (e.g. many twitter posts have urls)
2) repeat posts (many channels repeat post things many times)
3) special characters (many posts have a ton of random special characters)
My goal is to determine how much pre-processing I need to do to make watson most effective.

A: You are correct that if the language is mis-aligned then you will get incorrect results.
The Pi API determines the language first from the content-language header. If that is missing then if the content-type is json, then it looks at the language in the json content, selecting the language that has the highest number of occurrences, and finally, if that is missing it will default to the default language, namely English.
So in short, the recommendation (which will become required in a future update), is to always send in the content-language header.
Secondly, to your question on the content:
- URLs: the service will attempt to remove these. I won't guarantee that it removes every possible option as the url spec has some very esoteric options but we will remove the common formats.
- Repeat Posts: if you send in the same post twice, then it will be counted twice. We do no de-duplication in the text that is sent into the service.
- Special Characters; I'm assuming you are referring to emojis here. These are included in our processing as the underlying models were trained on data that included them as well, and thus they are one of the many signals the service uses.


text:
Q: System.ServiceModel.Security.SecurityNegotiationException: Could not establish trust relationship for the SSL/TLS secure channel with authority I am getting below error while trying to call webservice through UAT environment. However on my local it is working properly.  I see some comment as it might be due to dummy cert but could not get the answer so posting it here . Also i am beginner to WCF .
Please let me know how can i fix this .
what will be impact on production if i trust all by
//Trust all certificates
        System.Net.ServicePointManager.ServerCertificateValidationCallback =
            ((sender, certificate, chain, sslPolicyErrors) => true);

error says -
System.ServiceModel.Security.SecurityNegotiationException: Could not establish trust relationship for the SSL/TLS secure channel with authority . ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
binding is
  <basicHttpBinding>
    <binding name="GLEditServiceSOAP" closeTimeout="00:01:00" openTimeout="00:01:00"
      receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
      bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
      messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="Transport">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>

also wonder how it is working on my localhost.

A: You can refer to this post here. As mentioned in the post, returning always True in the certificate validation is safe if you trust the URL with SSL or if all of the components are hosted inside you company's intranet.


text:
Q: read json using javascript I am sending some request on a server and it's reply me this:
{
    "count": 100,
    "entries": [
        {
            "id": 7563,
            "application": "my-app",
            "user": "admin",
            "time": "2012-10-10T11:32:09.324+07:00",
            "values": {
                "/my-app/name": "4d79f56b-1a20-4b25-bff6-b5f1d7253790"
            }
        },
        {
            "id": 7561,
            "application": "my-app",
            "user": "admin",
            "time": "2012-10-10T11:32:08.687+07:00",
            "values": {
                "/my-app/name": "4d79f56b-1a20-4b25-bff6-b5f1d7253790"
            }
        }
}

I tried, but nothing seems to working for me!
 var my_JSON_object = {};
 var xmlhttp = new XMLHttpRequest();

 my_JSON_object = JSON.parse(xmlhttp.responseText);

 xmlhttp.open("GET",url,true);
 xmlhttp.sand();

Everything is fine. but values return null.
Any help would be appreciated!
[my code]

A: correct your code:
 xmlhttp.open("GET",url,false);
 xmlhttp.send();

 //get response after sending request
 my_JSON_object = JSON.parse(xmlhttp.responseText);

A:  alert(my_JSON_object.entries.id);

A: Easiest way is just to use jQuery to do it:
$.getJSON(url, function(data) {
    alert(data.count);
    ...
});


text:
Q: Dynamically adding component in relative layout I have an xml structure like,
<TextView
    android:id="@+id/txt1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="26dp"
    android:minWidth="20dp"
    android:text="05"
    android:background="@drawable/rounded_corners"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/txt2"
    style="android:textViewStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="false"
    android:layout_alignParentTop="true"
    android:layout_marginTop="26dp"
    android:layout_toRightOf="@+id/txt1"
    android:background="@drawable/rounded_corners"
    android:minWidth="20dp"
    android:text=""
    android:paddingLeft="5dp"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/txt3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="false"
    android:layout_alignParentTop="true"
    android:layout_marginTop="26dp"
    android:layout_toRightOf="@+id/txt2"
    android:background="@drawable/rounded_corners"
    android:minWidth="20dp"
    android:text=""
    android:paddingLeft="5dp"
    android:textAppearance="?android:attr/textAppearanceMedium" />
...

As I need this TextView to be dynamically added to View. I am trying to convert same in onCreate() method like below,
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Drawable rounded_corners = getResources().getDrawable(R.drawable.rounded_corners);

    RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.mainrelativeactivity);

    TextView tv = new TextView(this);
    RelativeLayout.LayoutParams rel = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    tv.setLayoutParams(rel);
    tv.setText("ABC");
    tv.setBackground(rounded_corners);
    relativeLayout.addView(tv);

    tv = new TextView(this);
    rel = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    tv.setLayoutParams(rel);
    tv.setText("DEF");
    tv.setBackground(rounded_corners);
    relativeLayout.addView(tv);

}

But I don't understand how to set layout_alignParentLeft,layout_marginTop and most concern is layout_toRightOf part?
If some one helpful to direct me to example like this then it will be great...

A: You'll have to add the rule with the RelativeLayout.LayoutParams to accomplish what u want..
Something like this
For aligning a view to right of an another view
rel.addRule(RelativeLayout.RIGHT_OF, tv.getId());

For aligning a view to the left in parent
rel.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

For giving margins
rel.setMargins(50, 10, 0, 0);


text:
Q: Where to specify a specific port number in spring boot service file in systemd? Need to know where can I specify the spring boot port aa when I check my service status I get this:
"Serverkt.log started at server-name with process id"
But I don't get the port number.
Also wanted to know where I can find the spring logs in the server

A: spring boot has its configuration file. I guess that you have it included in your jar/war file. So basically unzip that file and look inside it (try to search for application.properties or application.yaml|yml).
property server.port defines the port on which application is running. It defaults to 8080.
If you are using spring-boot 2 then with property logging.path you can change the path where output file will be placed. However I don't know if this works when you have logback/log4j/... configuration.
if you run your application you can override those properties specified in appplication.properties|yaml by providing command line properties. For example you can change the port with command java -jar your-boot.jar --server.port=9090

A: Since you're starting spring boot from a service file, you can set the port using command line arguments e.g.port 8083 would look like this:
ExecStart=/usr/bin/java -jar /opt/corda/spring.jar --server.port=8083


text:
Q: Following a listing and ellipses ... How should this sentence be punctuated? I'm trying to puncuate this sentence, and am not sure if I should use ellipses or an em dash, or simply put a period after the fragment and start a new sentence with "No one."
Job loss, major illness, family issues, natural disaster ... no one is immune from difficulties like these.
It's for a brochure for a nonprofit, so I'm straddling the line between advertising speak and journalistic style.

A: Typically an em dash is used in the same way as parentheses are or as commas are in an appositive or an aside, while ellipses are reserved for omitted text.
With that said, however, em dashes and ellipses are sometimes used interchangeably. That's a style choice. Neither is wrong grammatically. Someone writing in a stream of consciousness style would use an ellipsis there.
For a journalistic style, I'd probably go with the em dash, but this is my personal preference. I could see either being used in a brochure such as you describe (and in fact I've seen both used in pamphlets).

A: As you are adding related material, a colon could be used instead of em dash.  If you are going for a slightly more formal tone, a colon would be more preferable.

A: Personally, I would use an EM dash, as this makes the sentence clearer. Another option is to rearrange the sentence like this:

No one is immune to job loss, major illness, family issues and natural disaster.


text:
Q: android tabs strip changes dynamically based on arraylist values I want to add/remove android tab strips based on values of arrayList from server. Can anyone help me to do this?
Just want to get Categories of vegetables from server in to tab strip.


text:
Q: How do you rename the admin catalog Position label? How do you rename the admin catalog Position label?

A: Magento\Catalog\Block\Adminhtml\Category\Tab\Product class is responsible for generating this product's grid. We can rewrite the _prepareColumns method in this class to make changes in the grid. Please follow the example below:

app/code/MilanDev/CustomBlock/etc/adminhtml/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Block\Adminhtml\Category\Tab\Product" type="MilanDev\CustomBlock\Block\Adminhtml\Category\Tab\Product"/>
</config>

app/code/MilanDev/CustomBlock/Block/Adminhtml/Category/Tab/Product.php

<?php
namespace MilanDev\CustomBlock\Block\Adminhtml\Category\Tab;

class Product extends \Magento\Catalog\Block\Adminhtml\Category\Tab\Product
{
    /**
     * @return $this
     */
    protected function _prepareColumns()
    {
        parent::_prepareColumns();

        $this->addColumn(
            'position',
            [
                'header' => __('Your Text'),
                'type' => 'number',
                'index' => 'position',
                'editable' => !$this->getCategory()->getProductsReadonly()
            ]
        );

        return $this;
    }
}


text:
Q: "[object Object]" instead of Object is passed to ng-model for  when I select an option with Object I use an example from Angular documentation: https://docs.angularjs.org/api/ng/directive/select
"Using ngValue to bind the model to an array of objects" section.
index.html:
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-select-ngvalue-production</title>

  <form name="myForm">
     ngvalue select:
    <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
      <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
    </select>
  </form>

model = {{data.model | json}}

app.js:
(function(angular) {
  'use strict';
angular.module('ngvalueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
          {value: 'myString', name: 'string'},
          {value: 1, name: 'integer'},
          {value: true, name: 'boolean'},
          {value: null, name: 'null'},
          {value: {prop: 'value'}, name: 'object'},
          {value: ['a'], name: 'array'}
     ]
    };
 }]);
})(window.angular);

Plunker: https://plnkr.co/edit/aHgqeK1pQHS5zfiIjyZv?p=preview
The problem: Every <option> represents object. I select an item and "[object Object]" is assigned to ng-model of <select> instead of object.
Angular recommends to use ng-options instead of repeater with options but I need to use some extra logic for every option like ng-style (different for every option).
The question is: how to make object be passed as Object instead of String in ng-model of <select> when user select an option from select.

A: Why not ng-options?
<select size="6" name="ngvalueselect" ng-model="data.model" ng-options="item.value as item.name for item in data.availableOptions" multiple></select>

Working plunker https://plnkr.co/edit/zVzTI6sR6LywC9vcZRkn

A: I believe your select should look something like this:
<select size="6" name="ngvalueselect" ng-model="data.model" ng-options="option.value as option.name for option in data.availableOptions" multiple>

So there should not be any individual option item

A: $(this).find(":selected").data("value")
<form name="myForm">
     ngvalue select:
    <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
      <option ng-repeat="option in data.availableOptions" data-option="{{option.value}}">{{option.name}}</option>
    </select>
  </form>

model = {{data.model | json}}

and if jquery use:
$(document).on("change","select",function(){
    var objectOrStringReturend = $(this).find(":selected").data("value");
});


text:
Q: How to get value stored in a register, using gdb? "p/x $ebx" fails with "No registers." suppose the following is the asm code
 8048deb:       e8 41 05 00 00          call   8049331 <explode_bomb>
 8048df0:       03 73 f4                add    -0xc(%ebx),%esi
 8048df3:       83 c3 04                add    $0x4,%ebx
 8048df6:       8d 45 f8                lea    -0x8(%ebp),%eax
 8048df9:       39 c3                   cmp    %eax,%ebx
 8048dfb:       75 e7                   jne    8048de4 <phase_2+0x22>

I set a breakpoint at the last line, by this time, i am expecting both %eax and %ebx to have something stored in them.
In gdb, i do
p/x $ebx

and get:
No registers.

What does this error mean? How can i get the current content stored in a register?

A: Just do
 info register

It will give you the registers and their current values.
I do not believe there is a way to print/get just the value of ebx, eax, ecx, etc. You can, however print the value of the frame pointer, program counter, process status, and stack pointer registers using
p $fp
p $pc
p $ps
p $sp

A: p/x $ebx works just fine for me. (Or rather, p/x $rbx, because i'm testing in a 64-bit OS, but I imagine that p/x $ebx would work in 32-bit.) The application must be running. If I try to do p/x $rbx when the application has not started or has already exited, I do get "no registers". Are you sure that the breakpoint is hit?


text:
Q: How to preserve exit code when ending ssh session with a DigitalOcean droplet? I have a DigitalOcean droplet mydroplet that I'm accessing remotely via a bash script with the DigitalOcean CLI doctl. When the ssh connection terminates, I need to access the exit code of the last command that ran on the droplet, i.e. $?. However, DigitalOcean seems to aggregate all ssh exit codes >0 to 1. Is there a way I can preserve the original exit code?
For example:
>> doctl compute ssh mydroplet --ssh-command "exit 12"
>> echo $?
1 # how can I make this 12?

A: I know nothing about doctl but as a workaround you can do like this:
doctl compute ssh mydroplet --ssh-command 'rc=12; echo DOCTL_EXIT=$rc; exit $rc'

The you can parse the doctl's output and get the exit code you want.


text:
Q: Use int instead of char in char array and mask In the bit-shifting example shown
here:
 unsigned long int longInt = 1234567890;
 unsigned char byteArray[4];

 // convert from an unsigned long int to a 4-byte array
 byteArray[0] = (int)((longInt >> 24) & 0xFF) ;
 byteArray[1] = (int)((longInt >> 16) & 0xFF) ;
 byteArray[2] = (int)((longInt >> 8) & 0XFF);
 byteArray[3] = (int)((longInt & 0XFF));

Three questions:

*

*Why is it (int) instead of (unsigned char)? I tried it with unsigned char and it seems to compile just fine.

*Is 0XFF necessary? Isn't the new bit shifted-in 0 because Wikipedia says C uses logical shifting and logical shifting shifts in 0? (EDIT: at least it doesn't seem necessary on one with >> 24?)

*Can't I just do a memcpy() to copy longInt to a unsigned char buffer? Is it not so because of issue with Endianness? Is there any other reason?

A: 1.
((longInt >> 24) & 0xFF) expression is of type unsigned long int. With the cast to int the expression is first converted to int then to  unsigned char. If you don't cast to int the expression is not first converted to int. There are no difference in the two situations and the cast is superfluous.
2.
The 0xff is not necessary. The conversion to unsigned char actually performs the same.
3.
You can use memcpy but it is not portable because it depends on the endianness of the system. It will give different results if the system is big endian or little endian while the bitwise shift solution will give the same results.


text:
Q: how to move the code-behind Assemblies/DLLs to a different folder than /BIN with ASP.NET How can I move the code-behind Assemblies/DLLs to a different folder than /BIN with ASP.NET or group/merge those DLLs in /Bin to one DLLs file? I want to separate DLLs files as its purpose.

A: You can use ILMerge to merge all your DLL files into one. http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx

A: Take a look at this question inre to storing the DLL outside of the BIN folder:
Reference DLLs in ASP.NET without \Bin or GAC


text:
Q: Selenium - How to check and increment dropdown value if it is already present? I am trying to automate an application using Selenium Webdriver (Java). My web application has an Add button. Once the add button is clicked, a dropdown will enabled. If it is clicked again, a second dropdown will be enabled. Each subsequent dropdown's ID would be page1, page2, page3.. and so on..
What I want to do is when I open the page, I need to find out if any dropdown is already present in the page, if yes, then select the next dropdown value, and then select a value from the dropdown.
This is my current code, where I am manually selecting each dropdown and selecting their respective values.:
driver.findElement(By.id("addPage")).click();
new Select(driver.findElement(By.id("page0"))).selectByVisibleText("ABCD");
driver.findElement(By.id("addPage")).click();
Thread.sleep(1000);
new Select(driver.findElement(By.id("page1"))).selectByVisibleText("CDEF");
driver.findElement(By.id("addPage")).click();
Thread.sleep(1000);
new Select(driver.findElement(By.id("page2"))).selectByVisibleText("EFGH");
driver.findElement(By.id("addContact")).click();

A: I would try doing something along the lines of the following, assuming that you will have no other drop down elements present in the page (which I assume from your question is the case).
try {
driver.findElement(By.tagName("select"))
} catch (NoSuchElementException e) {
//create first dropdown
}

You could try and fill an array with the id of every select element on the  page and search for presence of one which matches the pattern "page\d" and go from there.

A: I think you can locate any select element with id starting with page, get the id attribute value and click the dropdown with the next page. Sample implementation:
WebElement existingPage = driver.findElement(By.cssSelector("select[id^=page]"));

String nextPageID = Integer.toString(Integer.parseInt(existingPage.getAttribute("id").replaceAll("\\D+", "")) + 1);
Select nextPage = new Select(driver.findElement(By.id("page" + nextPageID)));

And, as @Iridann correctly pointed out, to check the presence, catch the NoSuchElementException exception:
try {
    WebElement existingPage = driver.findElement(By.cssSelector("select[id^=page]"));
    // ...
} catch (NoSuchElementException e) {
    // no pages found
}


text:
Q: Model Hypothesis testing using R I am currently trying to test a hypothesis in R using two mutual funds that have almost identical alpha values over a 5 year period.
here's the model. I was wondering if anybody could give me a good starting point to do this?


text:
Q: Silverlight: Events in datatemplate for listboxes The functionality I want is to have a remove button beside each item of a listbox so when the user clicks it, that specific item gets removed from the list.
I am thinking about putting it in the data template but how would I wire up an even to that?
Thanks,
Shawn Mclean

A: Here is one way to approach this issue.  Create an ObservableCollection and set you ItemsSource equal to that Collection.  Then your Button click handler can just remove the item.
using System;
using System.Collections.ObjectModel;
using System.Windows.Controls;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        private ObservableCollection<string> _customers;

        public MainPage()
        {
            InitializeComponent();

            _customers = new ObservableCollection<string>() { "Bob", "Mark", "Steve" };
            this.DataContext = _customers;
        }

        public void remove_Click(object sender, EventArgs e)
        {
            var button = sender as Button;
            if (button == null)
                return;

            var name = button.DataContext as string;
            if (string.IsNullOrEmpty(name))
                return;

            _customers.Remove(name);
        }
    }
}

In this sample your XAML would look like this:
<Grid x:Name="LayoutRoot">
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" >
                    <TextBlock Text="{Binding}" />
                    <Button Content="Remove" Click="remove_Click" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

A: Bind ItemsSource of your ListBox to ObservableCollection.
Put a delete button into data template.
Click event handler for the button can be something like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    if (button != null)
    {
        var yourObject = button.DataContext as YourObject;
        if (yourObject != null)
        {
            YourObjectsObservableCollection.Remove(yourObject);
        }
    }
}

So you can retrieve the object which is bound to ListBoxItem from buttons DataContext.


text:
Q: "I am having fun with my stay in Japan." Does this phrase sound natural? I am wondering if this phrase sounds natural.
Also, how about the phrase below?
 "I am having a good time with my stay in Japan."
Do these sentences mean almost the same as "I'm enjoying my stay in Japan." ?
Thx


text:
Q: Nuxt nested route not navigating properly I have a simple navigation in my nuxt app. My folder structure in the pages folder looks like
 - pages
   - auth
     - signup.vue
       - index.vue

In my index.vue I have the following:
<template>
  <div>
    <nuxt-child/>
  </div>
</template>

I have a global navbar component in the components folder used by the default component in the layouts folder. So in my navbar I have nuxt-link that looks like:
<nuxt-link
    to="auth/signUp"
  >
    <v-btn class="hidden-sm-and-down white--text" text>Signup</v-btn>
  </nuxt-link>

This works fine when I click signup the first time and takes me to the signup page but if I click signup when I am in the signup page it takes me to auth/auth/signup. I tried moving the index.vue page out of the auth folder and placing it in the pages folder and renaming it to auth.vue. But it is still the same. Any help would be appreciated.Thanks in advance

A: After a few trials I found the problem was I didn't add a / before auth/signup. Changing this to /auth/signup fixed the problem.


text:
Q: Carousel view for Android I am working on a 3D carousel view for Android and I am running into various issues. Any help is greatly appreciated.
I tried Renderscript using this carousel as an example but noticed some classes were now deprecated i.e. RenderScriptGL.SurfaceConfig. I searched but could not find any information on what to use instead.
Does anyone know and/or can point me to documentation?

A: RenderScript as a graphic's component has been deprecated all together moving forward. So I would highly advise against using it. However, it is still being used as a compute language.
This looks like a pretty good open sourced library. I would start here.
http://www.codeproject.com/Articles/146145/Android-3D-Carousel


text:
Q: Send and Receive from and to different ports simultaneously python
I have 3 programs(clientA.py, ClientB.py, Server_X.py) in first machine and 1 program (machine_Y.py) in 2nd machine.
I need to connect as a picture and send data simultaneously from two clients to the server on host Y, modify this data and send to the server in host X.

Cant connect to machine more than one socket at a time. says connection refused.

I tested my code on localhost which in this case two machines is same.
Can you advise some solution to this problem?

Client A

import socket
import time
import threading
def client_cam():
    # create socket and bind host
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(('localhost', 9000))
    connection = client_socket.makefile('wb')
    try:
        count=1
        while True:
            data = 'from CAMERA: '
            client_socket.send(b'Camera')
            time.sleep(1)
            count+=1
    finally:
        connection.close()
        client_socket.close()

if __name__ == '__main__':
    client_cam()

Client B is same above except port number

machine_Y.py

....# here some handlers for VideoStreamHandler , SensorDataHandler
class ThreadServer(object):

    def server_thread(host, port):
        server = SocketServer.TCPServer((host, port), VideoStreamHandler)
        server.serve_forever()

    def server_thread2(host, port):
        server = SocketServer.TCPServer((host, port), SensorDataHandler)
        server.serve_forever()

    def motor_client(host,port):
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect((host, port))
        connection = client_socket.makefile('wb')
        try:
            count = 1
            while True:
                data = 'from Motor: '
                client_socket.send(b'motor')
                time.sleep(1)
                count += 1
        finally:
            connection.close()
            client_socket.close()

    motor_thread = threading.Thread(target=motor_client('localhost',9003))
    video_thread = threading.Thread(target=server_thread('localhost', 9000))
    distance_thread = threading.Thread(target=server_thread2('localhost', 9001))

    video_thread.start()
    distance_thread.start()
    motor_thread.start()

if __name__ == '__main__':
    ThreadServer()

Server_X.py

import SocketServer
import threading

class MotorStreamHandler(SocketServer.BaseRequestHandler):

    data = " "

    def handle(self):

        try:
            while self.data:
                self.data = self.request.recv(1024)
                print(self.data)
        finally:
            print("Connection closed on thread Motor")
class ThreadServer(object):
    def server_thread(host, port):
        server = SocketServer.TCPServer((host, port), MotorStreamHandler)
        server.serve_forever()
    motor_thread = threading.Thread(target=server_thread('localhost',9003))
    motor_thread.start()

if __name__ == '__main__':
    ThreadServer()


text:
Q: Why have the X server configuration files moved from /etc/Xorg to /usr/share/Xorg? It used to be the case (since the XFree86 days and maybe earlier) that X server configuration files are to be found under /etc; namely in /etc/Xorg. However, recent distributions (at least, recent Arch and Debian) put it under /usr/share/X11. Why is that? Doesn't host-level configuration belong under /etc ?

A: From man 5 xorg.conf, after describing a whole lot of locations under /etc:
   Finally, configuration files will also be searched for in  a  directory
   reserved  for system use.  This is to separate configuration files from
   the vendor or 3rd party packages from those  of  local  administration.
   These files are found in the following directory:

       /usr/share/X11/xorg.conf.d

So if you want to make a local adjustment, copy a file from /usr/share/X11 to its appropriate place under /etc. If these files would be updated from your vendor, your local, system wide configuration will not be overridden.


text:
Q: Condition for Being Galois I am thinking about the following excerpt of Patrick Morandi's "Field and Galois Theory" from chapter 1 section 2, page 21:

Here, $K$ is a field, and $\mathcal{F}(G)$ denotes the subfield $\{ x \in K : \sigma (x) = x\ \forall x \in G \}$ of $K$. $\text{Gal}(K/F)$ is the set of automorphisms of $K$ which fix $F$, which is also a subgroup of $\text{Aut}(K)$.
I understand the proof but I am looking for some insight in to the way it works. This could include a (categorical or representation-theoretical) generalization of the result, or context surrounding it, or possibly a reference where I could read about this generalized viewpoint.
To be completely specific about what I am asking for in terms of a categorical viewpoint, I was thinking something along the following lines: there is a contravariant adjoint correspondence between $\mathcal{F}$ and $\text{Gal}(K/-)$, so that for a group $G \subset \text{Gal}(K/F)$ and a field $L \subset K$ containing $F$, we have $L \subset \text{Fix}(G)$ if and only if $G \subset \text{Gal}(K/L)$. One can ask when this correspondence is a contravariant poset isomorphism. It shouldn't be too hard to show that $F = \mathcal{F} ( \text{Gal}(K/F))$ is a necessary and sufficient criterion. The proposition above therefore gives another such criterion.
In light of the above remark, consider the following situation: let $G$ be a group and let $\mathcal{C}$ be a category. View $G$ as a category $\mathcal{C}_G$ in the ordinary way, and identify $G$ with the unique object in $\mathcal{C}_G$. Consider a functor $\Phi: \mathcal{C}_G \rightarrow \mathcal{C}$ (an action of $G$ on $\mathcal{C}$), and set $\Phi (G) = K$ for $K \in \mathcal{C}$. We say that an element $g \in G$ fixes a subobject $L \stackrel{l}{\rightarrow} K$ if the following diagram commutes:
$\require{AMScd}$
\begin{CD}
K @>{\Phi(g)}>> K \\
@A{l}AA @A{l}AA\\
L @>{\text{Id}_L}>> L
\end{CD}
Let $F \stackrel{f}{\rightarrow} K$ be the sum of the subobjects of $K$ fixed by all $g \in G$. Let $\mathcal{G}$ be the category of subgroups of $G$ and $\mathcal{K}$ be the category of subobjects $l : L \rightarrow K$ of $K$ such that $f \leq l$.
We then have a pair of contravariant right adjoint functors $\mathcal{Fix} : \mathcal{G} \rightarrow \mathcal{K}$ and $\mathcal{Gal} : \mathcal{K} \rightarrow \mathcal{G}$, where $H \subset G$ is sent to the sum of subobjects $L$ in $\mathcal{K}$ fixed by $H$ and a subobject $L$ of $\mathcal{K}$ is sent to the set of elements of $G$ which fix $L$.
The question becomes, what properties applicable to the situation above can be required of $\mathcal{Fix}$ and $\mathcal{Gal}$ so that they form an inclusion reversing poset isomorphism? (Is $\mathcal{Fix} (\mathcal{Gal} (F)) = F$ enough? is there then a condition analogous to the proposition in question?).