text:
Q: Symofny -'password' cannot be null I have implemented function to check my password length in register api call like..
if($password){
    $this->validatePassword($password);
    }

from other api call..
public function validatePassword($password)
{
    if (strlen($password) < 6)
    {
        throw new PasswordLength('Password must be minimum 6 characters long!');
    }
}

and in my postman I am not returning an empty field but I keep getting error

Integrity constraint violation: 1048 Column 'password' cannot be null

A: In symfony, the plainPassword field is purely used to carry the users 'new' password into a method that would encode it and set it to password.
After the password field is populated, then the plainPassword field is blanked so that no plain text credentials are saved to the db.  This is done by calling the implemented eraseCredentials method (found in the required UserInterface).  Or, you can make the plainPassword method non-persistent in the user class.
Have a look here at the docs to see how to go about it all.
The docs show an extract from what should be a user manager utility class. Use this to set and update passwords as well as creating new users.
Theres a more complete explination here where the whole process is explained from end-to-end.

A: Solved!
if($password){
    $this->validatePassword($password);
}

$user->setPassword($password);


text:
Q: When is it illegal in Stata to call el(s,i,j) for valid in-range integers i and j? I use matrix list to show a matrix P that I have in a program:
P[1,6]
    c1   c2   c3   c4   c5   c6
r1   0    0    0    0    0    0

I expect the el() function to return the i,j element of my matrix P and I am trying to display this value (i.e. to print "0") using:
noi: di el(P,1,1)

However, Stata 15.1 comes back at me with:
  - noi: di el(P,1,1)
type mismatch

Why is this happening?

EDIT:
Reduced to a simple program:
program define MyProgram
matrix P = J(1,6,0)
noi: matrix list P
noi: di el(P,1,1)
end

And the resulting output:
MyProgram

P[1,6]
c1  c2  c3  c4  c5  c6
r1   0   0   0   0   0   0
type mismatch
r(109);

A: As i said in my comment, you did not tell us that this was part of an ado file. Sometimes error messages like the one you report arise from conflicts between variables with the same names.
At first, this appears to be a bug:
. clear

. set obs 1
number of observations (_N) was 0, now 1

.
. generate P = 0

.
. program define MyProgram
  1. matrix P = J(1,6,0)
  2. noi matrix list P
  3. noi di el(P,1,1)
  4. end

.
. MyProgram

P[1,6]
    c1  c2  c3  c4  c5  c6
r1   0   0   0   0   0   0
type mismatch
r(109);

Indeed, if you get rid of the variable P, it works as expected:
. drop P

.
. MyProgram

P[1,6]
    c1  c2  c3  c4  c5  c6
r1   0   0   0   0   0   0
0

However, appearances can be deceiving. As the Stata manual states:

"...A matrix might have the same name as a variable in the  dataset, and if it  does, Stata might  appear  confused  when  evaluating  an expression  (an exp).
  When the names conflict, Stata uses the rule that it always takes the data-variable interpretation..."

Thus, when evaluating expressions, one must override this behaviour by explicitly telling Stata that it is dealing with a matrix. This can be done using the matrix() function.
In this case, line 3 in MyProgram should change to:
noi: di el(matrix(P),1,1)

A: So it turns out this behavior is not a bug: in Stata the name space for variables, matrices and scalars collide (with variable names having priority).
In order to specify that a name is a matrix in function expecting such while avoiding collisions one can make the name explicitly a matrix thus:
program define MyProgram
matrix P = J(1,6,0)
noi matrix list P
noi di el(matrix(P),1,1)
end

And then the output that results, even with variables loaded in memory starting with "P":
. gen P = 0

. MyProgram

P[1,6]
c1  c2  c3  c4  c5  c6
r1   0   0   0   0   0   0
0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing a CRC algorithm I'm trying to implement a CRC algorithm as defined in some video interface standards:

*

*SMPTE296M-2001

*BT.1120-9:2017
The raw data is 10 bit words that are squashed into 8 bit bytes which I have no issues extracting and working with in numpy.
the CRC has polynomial:
CRC(X) = X^18 + X^5 + X^4 + 1

I believe this gives me the constant:
POLY = 0x40031

I've tried a few different implementations and nothing I generate matches my sample data.
this implementation was inspired by this
MASK = 0x3FFFF
class MYCRC:
    crc_table = []
    def __init__(self):
        if not self.crc_table:
            for i in range(1024):
                k = i
                for j in range(10):
                    if k & 1:
                        k ^= POLY
                    k >>= 1
                self.crc_table.append(k)

    def calc(self, crc, data):
        crc ^= MASK
        for d in data:
            crc = (crc >> 10) ^ self.crc_table[(crc & 0x3FF) ^ d]
        return crc ^ MASK

then there is this implementation I pulled from somewhere (not sure where)
def crc_calc(crc, p):
    crc = MASK & ~crc
    for i in range(len(p)):
        crc = (crc ^ p[i]) # & BIG_MASK
        for j in range(10):
            crc = ((crc >> 1) ^ (POLY & -(crc & 1))) # & BIG_MASK
    return MASK & ~crc

I also looked at using this library which has support for using custom polynomials, but it appears to be built to work with 8 bit data, not the 10 bit data I have.
I'm not sure how best to share test data as I only have whole frames which if exported as a numpy file is ~5MB.
I'm also unclear as the the range of data I'm supposed to feed to the CRC calculation. I think from reading it, it should be from the first active sample on one line, up to the line count of the line after, then the checksum calculated over that range. This makes the most sense from a hardware perspective, but the standard doesn't read that clearly to me.
edit:
pastebin of 10 lines worth of test data, this includes the embedded checksum.
within a line of data, samples 0-7 are the EAV marker, 8-11 are the line number,12-16 are the two checksums. the data is two interleaved streams of video data (luma channel and CbCr channel).
the standards state the checksums are run from the first active sample to the end of the line data, which I interpret to mean that it runs from sample 740 of one line to sample 11 of the next line.
As per section 5 of SMPTE292M the data is 10 bit data which cannot go below 0x3 or above 0x3FC. as per table 4 the result of the CRC should be 18 bits which get split and embedded into the stream as two words (with one bit filled in with the not of another bit) Note that there is one checksum for each channel of data, these two checksums are at 12-16 on each line
edit 2
some longer test data that straddles the jump from blanking data to active frame data

A: The CRC calculation must be done reflected. (Clue in note on Table 9: "NOTE – CRC0 is the MSB of error detection codes.")
This C routine checks the CRCs in your example correctly:
// Update the CRC-18 crc with the low ten bits of word.
// Polynomial = 1000000000000110001
// Reflected (dropping x^18) = 10 0011 0000 0000 0000 = 0x23000
unsigned crc18(unsigned crc, unsigned word) {
    crc ^= word & 0x3ff;
    for (int k = 0; k < 10; k++)
        crc = crc & 1 ? (crc >> 1) ^ 0x23000 : crc >> 1;
    return crc;
}

Indeed the span of the check is from the start of the active line through the line numbers, up to just before the two CRCs in the stream. That calculation matches those two CRCs. Each CRC is calculated on alternating words from the stream. The CRCs are initialized to zero.


text:
Q: Требуемый адрес для своего контекста неверен. Python Смотрел обучающее видео по библиотеке socket питона с применением TCP  и столкнулся с проблемой. Я запускаю отладчик сервера до момента принятия сообщения, сервер готов к приему. Однако после попытки соединения клиентом, у меня вылезает ошибка:
   Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.3.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1483, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.3.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/*/PycharmProjects/socket/socket_TCP_client.py", line 4, in <module>
    sock.connect(('', 8888))
OSError: [WinError 10049] Требуемый адрес для своего контекста неверен

У автора полностью идентичный код, ошибок не выдает, давность видео 2 года. Я пробовал менять порты и адреса("0.0.0.0", "") и у клиента, и у сервера, однако ошибка во всех случаях одна и та же. Подскажите, пожалуйста, в чем я неправ.
Код сервера:
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 8888))
sock.listen(5)

while True:
    try:
        client, addr = sock.accept()
    except KeyboardInterrupt:
        sock.close()
        break
    else:
        result = client.recv(1024)
        client.close()
        print('Message is', result.decode('utf-8'))

Код клиента:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 8888))
sock.send(b'funny message')
sock.close()

Спасибо

A: Для connect адрес должен быть указан, например:
sock.connect(('127.0.0.1', 8888))

Кст, а вот для bind можно и не указывать, так будет работать:
sock.bind(('', 8888))


text:
Q: How to disable direct input in Textfield with DropdownMenu composable? While using a DropdownMenu composable with a Textfield, how do I prevent the user from directly typing into the Textfield?
Setting the field's enabled parameter to false completely deactivates the field which is not desired.

A: TextField has a parameter called readOnly, you can set it to true to prevent it from being modified.

readOnly controls the editable state of the TextField. When true, the text
field can not be modified, however, a user can focus it and copy text
from it. Read-only text  fields are usually used to display pre-filled
forms that user can not edit


text:
Q: How to prevent programmatically changing RadioButton.Checked from removing control from TabOrder? I have a couple of RadioButtons on a C# Winforms project.
I want to provide a "clear form" button which should reset the radiobuttons.
Currently I just set the RadioButton.Checked values to false and it appears to be fine.
rdbBlockRelease.Checked = false;
rdbRegularRelease.Checked = false;

The issue is when you start to tab through the form after clearing it.
Before you tab through the form, the tab order works as expected. If you check a radiobutton and then clear the form the radiobuttons appear to be removed from the taborder.
I believe this is because of how radiobuttons and tab orders work. In a radio button group, if all radio buttons are unchecked, the radio button with the lowest taborder in the group will gain focus when you tab to it.
If you check a radio button and then tab to the group, unchecked radio buttons appear to be skipped; the focus goes to the checked radio button.
Keeping this in mind, I believe what is happening the form thinks the radio button group still has a checked radio button and changing the radiobutton.checked values doesn't appear to affect that. So when the user tries to tab to the radio button group after clearing the form, the form says something like:
"Oh, okay. Give focus to the selected radio button. Oh, there's no selected radio button. Give focus to the next item in tab order."
Now comes my question. How do I prevent this? How do I make the user able to tab to the radio button group after clearing a form?
I'm using Visual Studio 2017.

A: They have written code to implement this feature, but the code has some bug:
When using tab key to move between group of radio buttons, it tries to select the first checked radio button. But when there is no checked radio button, it neglects the group.
There are some methods in RadioButton source code like PerformAutoUpdates and WipeTabStops which are responsible to implement the behavior of that Tab key. Those methods check for AutoCheck and they work only in case AutoCheck is true.
So if you want to change the behavior, it's enough to set AutoCheck property to false and handle click event of all radio buttons yourself and revert the Checked property yourself.
Yes, I know it seems irrelevant at first glance! But that's it.
private void radioButton_Click(object sender, EventArgs e)
{
    var radio = (RadioButton)sender;
    radio.Checked = !radio.Checked;
}

Note: Instead of above event handler, you also can create your own radio button deriving from RadioButton and set AutoCheck to false and override OnClick and set Checked= !Checked.

A: While Reza's answer will allow you have no default value selected for a radio button group, you should still consider just having a default value.
As Craig W. mentioned, before deleting his comment, most forms will have one of the radio buttons selected by default. By doing like most, this problem can be prevented.


text:
Q: How to make the top bar menu always visible? I just recently started working on Ubuntu, coming from OSX. I work a lot with the computer so I naturally want everything to look and work the way I want it to.
Ubuntu has not let me down yet, but the auto-hiding menu is driving me nuts. How do you deal with it? Is there an easy work-around?
I managed to display the menu for only 10 seconds. I want this menu to be visible at all times
I'm using Ubuntu 13.04 64-bit if that's any help.


text:
Q: How to integrate Okta SignIn widget and SAML SSO with a Angularjs SPA? I've been trying to implement Okta SSO using SAML with my AngularJS SPA (using the Okta Sign-in widget) with no success.
The widget works OK by itself (without the SAML integration, just the widget). I'm able to authenticate my user's credentials, set the session cookie and redirect to my app homepage.
I followed the instructions from this link (Okta SignIn Widget with SAML) to integrate SAML with no luck.
The widget is able to authenticate my user's credentials but when the IDP (in this case the Okta site) redirects to my app using the "App Embed Link" I got a blank screen and I can see a POST to my app URL with the SAML assertion as a parameter with status 405 (method not allowed).
I'm really lost about this, and the Okta documentation is kind of loose around this matter. Some of my doubts are:

*

*When configuring my app in the Okta admin: What should I put on the
"Single sign on URL" field? my app login page URL?, or, an endpoint
URL on my backend in charge of processing the SAML assertion?

*Where should I place my Okta app's X.509 Certificate and IDP login URL?

A: While it is possible to get SAML to work with a JavaScript Single Page Application, it isn't the ideal way to implement Single Sign-On.
I suggest using OpenID Connect to add SSO capabilities to your AngularJS app. Here is a sample project showing how to use Okta's Sign-In Widget with AngularJS.
Unfortunatly, (and confusingly) the StackOverflow question you were looking at was about how to use the Okta Sign-In Widget to log in to an existing SAML application. It isn't possible to use the Okta Sign-In Widget to support SAML.
If you have to implement SAML in your AngularJS app, then you will need to add SAML support to the backend for your AngularJS app. The flow would look something like this:

*

*After authenticating with Okta, your browser will POST the SAMLResponse to your backend.

*Your backend will validate the SAMLResponse.

*If the SAMLResponse is valid, your backend will establish a session with your AngularJS app.


text:
Q: Bash using source to load config file I need to use a configuration file (which simply has some variable settings) which will be used by the sh script. I'm using source to do it, like so:
cmd.config file:
CUSTOM_JAVA_HOME=
JAVA_FLAGS=-server -Xmx2048M

program.sh file:
#!/bin/sh
if [ -f "cmd.config" ]; then
    source "cmd.config"
fi

[ -z "$CUSTOM_JAVA_HOME" ] && JAVA_BIN="java" || JAVA_BIN="$CUSTOM_JAVA_HOME""/bin/java"

The idea is to load the file only if it exists and then use those variables.
However I always get:

xxxx@ubuntu:~/Desktop/program$ ./program.sh live
  ./program.sh: 3: ./program.sh: source: not found

then the program starts using the defaults (cmd.config is not loaded).
Am I missing something?

A: source is a bash extension. If you want to use bash syntax, you need to start the script with:
#!/bin/bash

instead of
#!/bin/sh

Or you could use . instead of source to execute the script, this is portable to all POSIX-conforming shells.
Also, the config file needs to use the correct syntax to set shell variables. The line:
JAVA_FLAGS=-server -Xmx2048M

tries to execute a command named -Xmx2048M while setting the environment variable JAVA_FLAGS=-server. To make the whole thing the value of the variable, it needs to be quoted:
JAVA_FLAGS='-server -Xmx2048M'

And if these are supposed to be environment variables rather than just shell variables, you need to export them:
export JAVA_FLAGS

A: source function cannot load a standard file, you need to make the file a system file by adding . in front of the file name.
#!/bin/bash
if [ -f ".cmd.config" ]; then
    source ".cmd.config"
fi

[ -z "$CUSTOM_JAVA_HOME" ] && JAVA_BIN="java" || JAVA_BIN="$CUSTOM_JAVA_HOME""/bin/java"


text:
Q: User Defined Html tag I created a filterable DropDown list Using JavaScript. I designed this control using input field, button (Down Arrow) and Select Box with fixed size. If i click down arrow button i'll place the select box  under the Input Field. But i want to create the whole controls as a single control. I want to create a own tag for this dropdown list. To show this dropdown list i need to simple call my own tag like
<dropcombo id="xxx" >
   <op>1</op>
   <op>2</op>
</dropcombo>

Here Dropcombo tag is a user defined control.
Is there a way to create a own tag for this dropdown combo ?

A: The problem with custom HTML tags is that you'll need to use CSS to tell the browser how to render them (as the browser is unaware of how they should look).
<html>
<body>
    <customTag>This is my custom tag</customTag>
</body>

will render as:
This is my custom tag

See https://stackoverflow.com/questions/211394/when-to-use-custom-html-tags for further approaches to solving this problem.
Also, jQuery UI has an .autocomplete() ui extender which I recommend you check out.

A: create your tag
dropcombo
{
display:block;
text-align:left;
/* ADD CSS PROPERTY ACCORDING TO YOUR REQUIRDMENT */
}
op
{
/* SAME HERE CSS PROPERTY */
}


text:
Q: In R, how can I reference an S4 class from another package in my class definition? Suppose I have two packages PackageA and PackageB. I have an S4 class, ClassA, in PackageA that I would like to use as a base class for ClassB in PackageB:
setClass(
    "ClassB",
    slots = c(),
    validity = function(object) {

        T
    }
    contains = "ClassA")

However, when I build I get the error:

no definition found for superclass "ClassA"

I have tried adding a reference to the PackageA with devtools:
devtools::use_package("PackageA")

Perhaps I need to use an roxygen directive?

A: Turns out that ClassA was not being imported properly. Adding the correct roxygen directive solved the problem:
#' @import PackageA
setClass(
    "ClassB",
    slots = c(),
    validity = function(object) {

        T
    }
    contains = "ClassA")


text:
Q: interpret the histogram (generated in excel) I have generated and attached the histogram here for reference. On X-axis it's time in hour

*

*Considering, mean=7.52, SD=1.71, upper bound =7.76, lower bound=7.28, confidence interval=96% - What is the interpretation of this graph ?

Can I predict it is a normal distribution? .

A: Well, since the sample size is greater than 30 (CLT), and it is relatively symmetric, cause it is obviously not the population SD, technically yes. I would do a box plot to check for symmetry. And what do you mean by interpretation?


text:
Q: What is meaning of error: Uncaught Error: [$injector:nomod] I have this error:
Uncaught Error: [$injector:nomod] http://errors.angularjs.org/1.3.15/$injector/nomod?p0=sensorManagement

sensorManagement is my module name.
Any idea what the error above mean?

A: possible causes:
1) In essence you are creating the same module more than once.
   I think you probably have this somewhere in your code multiple times:
angular.module('sensorManagement',[])

if you want to use the module do
angular.module('sensorManagement'). //chain whatever controller/filter/service/factory

2) you have forgotten to load the script where you declared the module so probably in your index.html you are missing
<script src="your/modules/sensorManagement.js"/>

which would contain your declaration:
angular.module('sensorManagement',[])

A: If you follow the link you'll see:

Module 'sensorManagement' is not available! You either misspelled the
  module name or forgot to load it. If registering a module ensure that
  you specify the dependencies as the second argument.

That means you did not declare the module, which you can fix like so:
angular.module('sensorManagement', []);

It's also possible that you have the problem as answered by Amo_Geismar, and you have the above multiple times (or forgot to load the js file).
To work with a module after declaring it, you leave out the array.
sensorManagement.module.js
angular.module('sensorManagement', []);

someService.service.js
angular.module('sensorManagement') // Notice the lack of ', []' here
    .factory('yourService', function() {
        // Code here...
    });


text:
Q: Can´t connect Url with HttpUrlconnect This is my code in java:
Button conect = (Button) findViewById(R.id.btconect);
    conect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String userAgent = "Mozilla/5.0";
            String address = "http://192.168.20.110:8080/Proteos/http.php";
            String forSending = "Batman";
            String charset = "UTF-8";

            try {
                URL URL = new URL(address);
                HttpURLConnection connection = (HttpURLConnection)URL.openConnection();
                connection.setRequestProperty("User-Agent", userAgent);
                String stringToSend = URLEncoder.encode(forSending, charset);
                //Para poder escribir datos a la URL
                connection.setDoOutput(true);
                connection.setDoInput(true);

                // Indicamos el tipo de request, POST en este caso
                connection.setRequestMethod("POST");

                // Indicamos un timeout de 10 segundos
                connection.setReadTimeout(10*1000);

                OutputStreamWriter out = new OutputStreamWriter(
                        connection.getOutputStream());
                out.write("nombre=" + stringToSend);
                out.close();

                BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                                connection.getInputStream()));
                String response;
                while((response = in.readLine()) != null)
                    System.out.println(response);
                in.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

My manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bmprietoc.httpconect">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I've tried to make useful the code but i can´t get the failure. The application stop always right in here:
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

I change my code but the result is the same
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.
                Builder().permitNetwork().build());

        Button conect = (Button) findViewById(R.id.btconect);
        conect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new connection().execute();

            }
        });

    }

    private class connection extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            String userAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0";
            String address = "http://localhost/form.php";
            String forSending = "Batman";
            String charset = "UTF-8";

            // El metodo encode() de URLEncoder se encarga de encodear la cadena que enviaremos
            // al servidor, sustituyendo espacios y caracteres especiales
            String stringToSend = null;
            try {
                stringToSend = URLEncoder.encode(forSending, charset);
                // 1. Creamos objeto URL
                URL URL = new URL(address);
                // 2. Obtenemos el objeto URLConnection llamando a openConnection() en URL
                URLConnection connection = URL.openConnection();
                // Establecemos algunas propiedas de envió, como es el User-Agent
                connection.addRequestProperty("User-Agent", System.getProperty("http.agent"));

                // 3. Esto es importantisímo, es aqui donde establecemos la capacidad de envió.
                connection.setDoOutput(true);

                // 4. Abrimos una conexión al recurso para poder escribir/enviar datos al formulario
                // Nota que no se llama explícitamente a connect() porque llamados a getOutputStream()
                OutputStreamWriter out = new OutputStreamWriter(
                        connection.getOutputStream());
                out.write("nombre=" + stringToSend); // "nombre" es el campo del formulario web
                out.close();

                // Aquí leemos el resultado que nos devolvió el servidor, en efecto, lo que
                // respondió form.php y luego de enviar los datos
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                                connection.getInputStream()));
                String response;
                while ((response = in.readLine()) != null)
                    System.out.println(response);
                in.close();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

    }
}

I change my code again like this.
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.
            Builder().permitNetwork().build());

    Button conect = (Button) findViewById(R.id.btconect);
    conect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new connection().execute();

        }
    });

}

private class connection extends AsyncTask <Void,Void,String> {

    @Override
    protected String doInBackground(Void... voids) {
        String userAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0";
        String address = "http://10.0.2.2/Proteos/http.php";
        String forSending = "Batman";
        String charset = "UTF-8";

        // El metodo encode() de URLEncoder se encarga de encodear la cadena que enviaremos
        // al servidor, sustituyendo espacios y caracteres especiales
        String stringToSend = null;
        try {
            stringToSend = URLEncoder.encode(forSending, charset);
            // 1. Creamos objeto URL
            URL URL = new URL(address);
            // 2. Obtenemos el objeto URLConnection llamando a openConnection() en URL
            URLConnection connection = URL.openConnection();
            // Establecemos algunas propiedas de envió, como es el User-Agent
            connection.addRequestProperty("User-Agent", userAgent);

            //System.getProperty("http.agent")

            // 3. Esto es importantisímo, es aqui donde establecemos la capacidad de envió.
            connection.setDoOutput(true);
            //connection.setConnectTimeout(50000);

            // 4. Abrimos una conexión al recurso para poder escribir/enviar datos al formulario
            // Nota que no se llama explícitamente a connect() porque llamados a getOutputStream()
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream());
            out.write("nombre=" + stringToSend); // "nombre" es el campo del formulario web
            out.close();

            // Aquí leemos el resultado que nos devolvió el servidor, en efecto, lo que
            // respondió form.php y luego de enviar los datos
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            connection.getInputStream()));
            String response;
            while ((response = in.readLine()) != null)
                System.out.println(response);
            in.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

}
And the logcat is
09-20 18:23:31.887 1465-1675/com.example.bmprietoc.httpconect W/System.err: java.net.ConnectException: failed to connect to /10.0.2.2 (port 80): connect failed: ETIMEDOUT (Connection timed out)

It can't connect to the local host. I cant figure the problem out.
Please help me.

A: The code below work fine for me.
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.
            Builder().permitNetwork().build());

    Button conect = (Button) findViewById(R.id.button);
    conect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new connection().execute();

        }
    });

}

private class connection extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String userAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0";
        String address = "http://private-a1505-mmcapi.apiary-mock.com/notes/id";
        String forSending = "Batman";
        String charset = "UTF-8";

        // El metodo encode() de URLEncoder se encarga de encodear la cadena que enviaremos
        // al servidor, sustituyendo espacios y caracteres especiales
        String stringToSend = null;
        try {
            stringToSend = URLEncoder.encode(forSending, charset);
            // 1. Creamos objeto URL
            URL URL = new URL(address);
            // 2. Obtenemos el objeto URLConnection llamando a openConnection() en URL
            URLConnection connection = URL.openConnection();
            // Establecemos algunas propiedas de envió, como es el User-Agent
            connection.addRequestProperty("User-Agent", System.getProperty("http.agent"));

            // 3. Esto es importantisímo, es aqui donde establecemos la capacidad de envió.
            connection.setDoOutput(true);

            // 4. Abrimos una conexión al recurso para poder escribir/enviar datos al formulario
            // Nota que no se llama explícitamente a connect() porque llamados a getOutputStream()
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream());
            out.write("nombre=" + stringToSend); // "nombre" es el campo del formulario web
            out.close();

            // Aquí leemos el resultado que nos devolvió el servidor, en efecto, lo que
            // respondió form.php y luego de enviar los datos
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            connection.getInputStream()));
            String response;
            while ((response = in.readLine()) != null)
                System.out.println(response);
            in.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
}

A: I'm getting a NetworkOnMainThreadException when I run your code. You will have to create an AsyncTask to perform this operation.
An AsyncTask with your logic might look something like this (although you will need to change the parameters in the <Void, Void, Void> field if you wish to change your input and return parameters.
private class NetTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... voids) {
        String userAgent = "Mozilla/5.0";
        String address = "http://192.168.20.110:8080/Proteos/http.php";
        String forSending = "Batman";
        String charset = "UTF-8";

        try {
            URL URL = new URL(address);
            HttpURLConnection connection = (HttpURLConnection)URL.openConnection();
            connection.setRequestProperty("User-Agent", userAgent);
            String stringToSend = URLEncoder.encode(forSending, charset);
            //Para poder escribir datos a la URL
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // Indicamos el tipo de request, POST en este caso
            connection.setRequestMethod("POST");

            // Indicamos un timeout de 10 segundos
            connection.setReadTimeout(10*1000);

            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream());
            out.write("nombre=" + stringToSend);
            out.close();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            connection.getInputStream()));
            String response;
            while((response = in.readLine()) != null)
                System.out.println(response);
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

Then just execute the asyncTask in your onClick like this:
public void onClick(View v) {
    new NetTask().execute();
}


text:
Q: Multiple references to a single table I have two separate tables which refer to different country ID's and one country table. I'm having trouble reporting both of the country names. I know this is pretty basic but i'm pretty stuck so please help!
I have the following tables and columns:
Names
Reference_no    |Name   |Main_Country_ID
12345           |Name1  |1
12346           |Name2  |2
12347           |Name3  |1

Jobs
Reference_no    |Job      |Local_Country_ID
12345           |Job1     |3
12345           |Job2     |4
12346           |Job1     |1
12347           |Job1     |1

Country
Country_ID  |Country_Name
1           |UK
2           |US
3           |France
4           |Germany

I'm trying to achieve this:
Reference_no    |Name   |Main_Country_ID    |Country_Name   |Job        |Local_Country_ID   |Country_Name
12345           |Name1  |1                  |UK             |Job1       |3                  |France
12345           |Name1  |1                  |UK             |Job2       |4                  |Germany
12346           |Name2  |2                  |US             |Job1       |1                  |UK
12347           |Name3  |1                  |UK             |Job1       |1                  |UK

I have the following so far:
select n.reference_no,
       n.name,
       n.reference_no,
       c.country_name,
       j.job,
       j.local_country_id
       c2.country_name
from names n
join jobs j on n.reference_no=j.reference_no
join country c on n.main_country_id=c.country_id
join country c2 on j.local_country_id=c2.country_id

This SQL doesn't work as it doesn't like the 'c2' reference. Can anyone help me create this query?

A: select n.reference_no,
       n.name,
       n.reference_no,
       c.country_name,
       j.job,
       j.local_country_id,
       c2.country_name
from names n
join jobs j on n.reference_no=j.reference_no
join country c on n.main_country_id=c.country_id
join country c2 on j.local_country_id=c2.country_id

Maybe you are missing the c2 in your join:


text:
Q: The system cannot find the file specified during webhosting I am using asp.net identity with EF data first approach. I have hosted my website on appharbor. All of my controllers actions and webapi is working fine except AccountController. When a user tries to signup it gives the Internal server error. The details of error is:

My AccountController is:
[Authorize]
    public class AccountController : Controller
    {
        private Entities db = new Entities();
        public AccountController()
            : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        {
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<JsonResult> RegisterUser(string email, string password = "aa")
        {

            var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

            if (!roleManager.RoleExists("Admin"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);

            }

            var ab = email.Split('@');

            var user = new ApplicationUser() { UserName = email };
            user.Email = ab[0];
            UserManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = -1
            };
            var result = await UserManager.CreateAsync(user, password);
            if (result.Succeeded)
            {
                var currentUser = UserManager.FindByName(user.UserName);

                var roleresult = UserManager.AddToRole(currentUser.Id, "Admin");

                try {
                await SignInAsync(user, isPersistent: true);
                }
                catch (Exception e)
                {
                    string s = e.ToString();
                }
                var id = user.Id;
                var data =await db.AspNetUsers.FindAsync(id);
                if (password == "aa")
                {
                    data.IsPasswordSaved = false;
                }
                else
                {
                    data.IsPasswordSaved = true;
                }
                db.Entry(data).State = System.Data.Entity.EntityState.Modified;
                await db.SaveChangesAsync();
                return Json("Done", JsonRequestBehavior.AllowGet);
            }
            return Json("Error", JsonRequestBehavior.AllowGet);
        }
    }

I have tried to enable remote connections from this answer. But in SQL Server Configuration Manager the SQL Server Network Configuration does not has the option Protocols for SQLEXPRESS. How can I tackle this issue?


text:
Q: JSON.parse SyntaxError: Invalid or unexpected token Trying to parse this data:
{ id: 'abc',
    name: 'abc',
    '24h_total': '370029.0',
    last_updated: '1501633446' }

Trying to run this code on the above rest api response.....
var jsondata =  JSON.parse(body);
var values = [];
console.log(jsondata);

for(var i=0; i< jsondata.length; i++){
     //how do i access this property?
     console.log(jsondata[i].24h_total);
}

at the moment i get an error
    jsondata[i].24h_total,
               ^^^

SyntaxError: Invalid or unexpected token
I am sure it's due to the fact that this field name starts with a number.
thanks in advance.

A: You need to access the property like so, because it's not a valid javascript identifier:
console.log(jsondata[i]['24h_total']);

A: Access that property like so:
jsondata[i]['24h_total']
This will fix the error.


text:
Q: Consecutive SSH connections with Eclipse RSE I want to develop remotely in PHP on a development server. Eclipse RSE is great for this. But the only way to access my development server is by establishing a SSH connection to a firewall and then to the virtual server. Is there anyway to set up Eclipse RSE to do this?

A: i do the same using netbeans remote option over SFTP
u can also coos ftp
works fine for me.


text:
Q: RODBC and MYSQL procedure parameters I would like to repeatedly query a MySQL database from inside R with the RODBC package.
I have a MySQL procedure that I normally call like this:
CALL`myDB`.`myProc`(x,y)

If I use RODBC, how can I pass x and y to the function efficiently?
Am I stuck using paste() as in:
sqlQuery(channel,paste("CALL`myDB`.`myProc`(",x,",",y,")"))

A: Yes, use paste just like that, except consider using sep=""


text:
Q: If I Regenerate Thumbnails, would WordPress delete the existing Thumbnails and replace them with 'new copies'? I am currently working on a website, which has 1,000's of Product Images.  All of these images were uploaded, without being optimized accordingly.  For instance, most of the Product Images were uploaded with 5000px by 3000px dimensions which is far too large.
I have downloaded these Product Images to my computer, to start resizing them.  Rather than manually do this, as it would simply take forever, I have setup my Photoshop to automate all of the resizing for me.
Furthermore, it would take forever to sift through the various Folders, as to pull out the original images to resize.
Instead, I was hoping to simply get Photoshop to resize every single Product Image in all of the Folders by 600px by 400px.  Of course, this would also resize the various Thumbnail Images as well as the other image sizes WordPress creates upon the original image being uploaded.
Could I simply use the above approach, transfer the images back to WordPress via FTP and as long as I keep the file names the same for the various resizes images that WordPress creates, could I simply select 'Regenerate Thumbnails' and would WordPress delete their own resized images (which would now be 600px by 400px) and then replace them all with the correct sizes of 150px by 150px and 250px by 250px etc?

A: Here's what you can do:
Delete the Old Thumbnails
Download and install the Thumbnail Cleaner plugin. This plugin will delete all of your current thumbnails. You can do this manually by writing a PHP snippet that detects thumbnails and deletes them, but it's not really that necessary.
Resize the Original Images
Once you have deleted the thumbnails, copy what remains of your uploads to your computer. Then, use PhotoShop's automate feature to resize them all. Upload the folder back to your host, and overwrite everything. Ofcource, make a back-up first.
Regenerate New Thumbnails
After all the above is done, download and install the Regenerate Thumbnails by Viper00Bond, and create fresh thumbnails of your images.
Note:
Neither WordPress nor WooCommerce use the original images as product images or thumbnails. Unless you have no thumbnail at all ( which results in the original image being loaded ), there is no need to resize the original images.


text:
Q: zero byte file on FluentFTP upload I try to upload files and wrote the following code with the help of FluentFTP:
      clientFluentFTP = new FtpClient(hostname,
                                       username,
                                       password);

      clientFluentFTP.LoadProfile(new FtpProfile
      {
        Host = hostname,
        Credentials = new NetworkCredential(username, password),
        Encryption = FtpEncryptionMode.Explicit,
        Protocols = SslProtocols.Tls12,
        DataConnection = FtpDataConnectionType.PASV,
        Encoding = Encoding.UTF8,
      }) ;

      clientFluentFTP.ValidateAnyCertificate = true;
      clientFluentFTP.Connect();
      clientFluentFTP.UploadFile(localfile, requestname, FtpRemoteExists.Overwrite,false,FtpVerify.Throw);

I test with my first file (UTF8 encoded) and the result is a zero byte file.
No exception is thrown so I assume it is able to verify the transfer. Apparently the transfer is not closed off correctly. And yes, with commandline FTP clients I can transfer the file without problems. No  message, no error. Just a zero byte file.
What do I do wrong?
The Log from the code is below.
# Connect()
Status:   Connecting to 46.235.40.106:21
Response: 220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
Response: 220-You are user number 3 of 50 allowed.
Response: 220-Local time is now 11:54. Server port: 21.
Response: 220-This is a private system - No anonymous login
Response: 220-IPv6 connections are also welcome on this server.
Response: 220 You will be disconnected after 15 minutes of inactivity.
Status:   Detected FTP server: PureFTPd
Command:  AUTH TLS
Response: 234 AUTH TLS OK.
Status:   FTPS Authentication Successful
Status:   Time to activate encryption: 0h 0m 0s.  Total Seconds: 0,1315097.
Command:  USER ***
Response: 331 User ftp_meteo_wagenborgen.nl OK. Password required
Command:  PASS ***
Response: 230-Your bandwidth usage is restricted
Response: 230 OK. Current restricted directory is /
Command:  PBSZ 0
Response: 200 PBSZ=0
Command:  PROT P
Response: 200 Data protection level set to "private"
Command:  FEAT
Response: 211-Extensions supported:
Response: EPRT
Response: IDLE
Response: MDTM
Response: SIZE
Response: MFMT
Response: REST STREAM
Response: MLST type*;size*;sizd*;modify*;UNIX.mode*;UNIX.uid*;UNIX.gid*;unique*;
Response: MLSD
Response: AUTH TLS
Response: PBSZ
Response: PROT
Response: UTF8
Response: ESTA
Response: PASV
Response: EPSV
Response: SPSV
Response: ESTP
Response: 211 End.
Status:   Text encoding: System.Text.UTF8Encoding
Command:  OPTS UTF8 ON
Response: 200 OK, UTF-8 enabled
Command:  SYST
Response: 215 UNIX Type: L8

# UploadFile("utils/systeminfoTable.txt", "/web/systeminfoTable.txt", Overwrite, False, Throw)

# FileExists("/web/systeminfoTable.txt")
Command:  SIZE /web/systeminfoTable.txt
Response: 213 1467

# DeleteFile("/web/systeminfoTable.txt")
Command:  DELE /web/systeminfoTable.txt
Response: 250 Deleted /web/systeminfoTable.txt

# OpenWrite("/web/systeminfoTable.txt", Binary)
Command:  TYPE I
Response: 200 TYPE is now 8-bit binary

# OpenPassiveDataStream(PASV, "STOR /web/systeminfoTable.txt", 0)
Command:  PASV
Response: 227 Entering Passive Mode (46,235,40,106,168,24)
Status:   Connecting to 46.235.40.106:43032
Command:  STOR /web/systeminfoTable.txt
Response: 150 Accepted data connection
Status:   FTPS Authentication Successful
Status:   Time to activate encryption: 0h 0m 0s.  Total Seconds: 0,1381567.
Status:   Disposing FtpSocketStream...
Status:   File Verification: PASS

# Dispose()
Status:   Disposing FtpClient object...
Command:  QUIT
Status:   Disposing FtpSocketStream...
Status:   Disposing FtpSocketStream...

A: Ah... The default setting is binary and should be ascii.
So I added:
  clientFluentFTP.UploadDataType = FtpDataType.ASCII;

Problem solved.See my comment under the problem description
It had nothing to do with coding.
I changed provider because of a configuration issue and the problem was gone.


text:
Q: Confusion about bsr and lzcnt I'm a bit confused about both instructions. First let's discard the special case when the scanned value is 0 and the undefined/bsr or bitsize/lzcnt result - this difference is clear and not part of my question.
Let's take the binary value 0001 1111 1111 1111 1111 1111 1111 1111
According to Intel's spec the result for lzcnt is 3
According to Intel's spec the result for bsr is 28
lzcnt counts, bsr returns the index or distance from bit 0 (which is the lsb).
How can both instructions be the same and how can lzcnt be emulated as bsr in case there's no BMI on the CPU available? Or is bit 0 in case of bsr the msb? Both "code operations" in Intel's spec are different too, one counts or indexes from the left, the other from the right.
Maybe someone can shed some light on this, I have no CPU without BMI/lzcnt instruction to test if the fallback to bsr works with the same result (as the special case of value 0 to scan never happens).

A: LZCNT gives the number of leading zero bits. BSR gives the bit index of the most significant 1 bit. So they do effectively the same thing for the non-zero case, except the result is interpreted differently. Therefore you can just subtract the BSR result from 31 to get the same behaviour as with LZCNT, i.e. LZCNT == (31 - BSR).

A: To be clear, there is no working fallback from lzcnt to bsr. What happened is that Intel used the previously redundant sequence rep bsr to encode the new lzcnt instruction. Using a redudant rep prefix for bsr was generally defined to be ignored, but with the caveat that it may decode differently on future CPUs1.
So if you happen to execute lzcnt on a CPU that doesn't support it, it will execute as bsr. Of course, this fallback is not exactly intentional, and it gives the wrong result (as Paul R points out they look at the same bit but report it differently): it is just a consequence of the way the new instruction was encoded and how pointless rep prefixes were treated by prior CPUs. So the world fallback is pretty much entirely inappropriate for lzcnt and bsr.
The situation is more subtle for the case of tzcnt and bsf. It uses the same encoding trick: tzcnt has the same encoding as rep bsf, but here the "fallback" mostly works since tzcnt returns the same value as bsf for all inputs except zero. For zero inputs tzcnt returns 32, but bsf leaves the destination undefined.
You can't really use even this fallback though: if you never have zero inputs you might as well just use bsf, saving a byte and being compatible with a couple decades of CPUs, and if you do have zero inputs the behavior differs.
So the behavior is perhaps better classified as trivia than a fallback...

1 Normally this would more or less be esoterica, but you could for example use rep prefixes are where they have no functional effect to lengthen instructions to help align subsequent code without inserting explicit nop instructions. Given the "may decode differently in the future" this would be dangerous when compiling code which may run on any future CPU.


text:
Q: Windows wget UTF-8 names i'm trying to create a batch script that connects to my ftp server (windows server 2012 R2) and downloads a tree of directories.
I'm using GNUWin32's wget with the following commands:
"C:\Program Files (x86)\GnuWin32\bin\wget.exe" --ftp-user=foo --ftp-password=foo ftp://ip.ip.ip.ip/directory/directory --level=0 --no-glob --continue --timestamping --tries=0 --recursive

The problem is that even if on my ftp server and on the database (postgres) everything is saved as UTF-8 and displayed correctly. when i download the directory tree with wget the things downloaded don't have the correct encoding (E.G. ü becomes ü)
Is there a way to make it so the downloaded folders will have the same name as the ones on the server? I've been trying to achieve this for 3 days with no avail
P.S. I've tried downloading the files with Filezilla forcing UTF-8 and they end up having the correct name but i need a solution that will work unattended and filezilla doesn't support that from what i understood

A: I managed to do it, i used the following wget command
wget --ftp-user=%ADMIN% --ftp-password=%PASSWORD% ftp://%IP% --level=0 --no-glob --continue --tries=0 --recursive --restrict-file-names=ascii

to donload the files forcing the ASCII encoding and then this powershell script to convert them back to UTF-8
Add-Type -AssemblyName System.Web;

# Get the filenames and order them to have the files first
$data = get-childitem %PATH_TO_FOLDER% -recurse | Sort-Object FullName -descending;

# Cycle every file
ForEach($dat in $data){
 # Get the decoded UTF-8 name
 $decoded = [System.Web.HttpUtility]::UrlDecode($dat.name);

 # Rename the file if the decoded name is different than the current one
 if ($dat.name -ne $decoded){ren $dat.FullName $decoded}

}

It could probably be made better but i don't know enough about powershell to do so and this works nicely for my needs anyway


text:
Q: Why does this list implementation take more space than stl list? I'm using IAR as compiler for embedded project. I'm trying to introduce some templates for basic types like list, but each STL list object created increases code size by about 200 bytes relatively to our current C style implementation.
I tried to implement a small portion of the STL list myself hoping to get a smaller code footprint, but ended up being more heavy than the full STL list.
Am I doing something horribly wrong in my usage of templates?
Thanks
P.S. Please note that the code is untested so it may contain dragons.
#ifndef __LINK_LIST_HPP__
#define __LINK_LIST_HPP__

#include <stdint.h>
#include <stdlib.h>

template <typename T> class list
{
private:
    struct LinkListElement
    {
        T payload;
        LinkListElement* next;
        LinkListElement* prev;
    };
public:

    class iterator
    {
        // Need access to LinkListElement struct
        friend class list;
    public:
        iterator() : m_cur_item(NULL){}

        iterator(LinkListElement* elem) : m_cur_item(elem){}

        iterator(const iterator& other) : m_cur_item(other.m_cur_item){}

        ~iterator(){}

        iterator& operator=(const iterator& other)
        {
            m_cur_item = other.m_cur_item;
            return *this;
        }

        bool operator==(const iterator& other) const
        {
            // Compare by position, ignoring the payload contents when comparing iterators.
            return  (m_cur_item->next == other.m_cur_item->next) &&
                    (m_cur_item->prev == other.m_cur_item->prev);
        }

        bool operator!=(const iterator& other) const
        {
            return !(*this == other);
        }

        // Prefix increment operator.
        iterator& operator++()
        {
            increment();
            return *this;
        }

        // Postfix increment operator.
        iterator operator++(int)
        {
            iterator copy(*this);
            increment();
            return copy;
        }

        // Prefix decrement operator.
        iterator& operator--()
        {
            decrement();
            return *this;
        }

        // Postfix decrement operator.
        iterator operator--(int)
        {
            iterator copy(*this);
            decrement();
            return copy;
        }

        T& operator*()
        {
            // Just so we won't crash, but behavior is undefined.
            if (m_cur_item == NULL)
            {
                return dummy;
            }

            return m_cur_item->payload;
        }

        T* operator->()
        {
            if (m_cur_item == NULL)
            {
                return NULL;
            }

            return &(m_cur_item->payload);
        }

    private:

        void increment()
        {
            if (m_cur_item == NULL || m_cur_item->next == NULL)
            {
                return;
            }

            m_cur_item = m_cur_item->next;
        }

        void decrement()
        {
            if (m_cur_item == NULL || m_cur_item->prev == NULL)
            {
                return;
            }

            m_cur_item = m_cur_item->prev;
        }

        LinkListElement* m_cur_item;
        static T dummy;

    };

    // Need access to internal LinkListElement pointer
    friend class iterator;

    list()
    {
        // Add sentinel to mark end of list.
        m_tail = new LinkListElement;
        m_tail->next = m_tail;
        m_tail->prev = m_tail;
        m_head = m_tail;
    }

    ~list()
    {
        // Clear entire list except for sentinel
        clear();

        // Destroy sentinel
        delete m_tail;
        m_head = NULL;
        m_tail = NULL;
    }

    T& back()
    {
        // empty list with only sentinel. Result of back() is undefined
        if (empty())
        {
            // TODO: Show some debug error
        }

        return m_tail->prev->payload;
    }

    T& front()
    {
        if (empty())
        {
            // TODO: Show some debug error
        }

        // m_head is always defined even if list is empty
        return m_head->payload;
    }

    size_t size()
    {
        return m_count;
    }

    bool empty()
    {
        // head == tail means the list is empty
        return m_head == m_tail;
    }

    iterator begin()
    {
        return iterator(m_head);
    }

    iterator end()
    {
        return iterator(m_tail);
    }

    iterator insert(iterator position, const T& payload)
    {
        // Validate position by finding it in our list
        iterator find = begin();
        while (find != end() && find != position)
        {
            ++find;
        }

        if (find == end())
        {
            // TODO: Show some debug error
            return position;
        }

        return insert_before(find.m_cur_item, payload);
    }

    void push_back(const T& payload)
    {
        insert_before(m_tail, payload);
    }

    void push_front(const T& payload)
    {
        insert_before(m_head, payload);
    }

    iterator erase(iterator position)
    {
        // Validate position by finding it in our list
        iterator find = begin();
        while (find != end() && find != position)
        {
            ++find;
        }

        if (find == end())
        {
            // TODO: Show some debug error
            return position;
        }

        return remove_at(find.m_cur_item);

    }

    //iterator erase(iterator first, iterator last);    // Implement only if needed
    void pop_back()
    {
        if (!empty())
        {
            // Don't remove the sentinel
            remove_at(m_tail->prev);
        }
    }

    void pop_front()
    {
        if (!empty())
        {
            remove_at(m_head);
        }
    }

    void remove(const T& value)
    {
        iterator iter = begin();

        while (iter != end())
        {
            iterator remove = iter++;
            if (*remove == value)
            {
                remove_at(remove.m_cur_item);
            }
        }
    }

    void clear()
    {
        while (!empty())
        {
            pop_back();
        }
    }

private:

    iterator insert_before(LinkListElement* existing, const T& payload)
    {
        // Allocate memory and save the element
        LinkListElement* new_elem = new LinkListElement;

        // For classes types (not pointer to object) this should invoke copy constructor
        new_elem->payload = payload;
        new_elem->prev = existing->prev;
        new_elem->next = existing;
        existing->prev = new_elem;
        ++m_count;

        if (existing == m_head)
        {
            m_head = new_elem;
        }

        return iterator(new_elem);
    }

    iterator remove_at(LinkListElement* to_remove)
    {
        // Allocate memory and save the element
        LinkListElement* prev = to_remove->prev;
        LinkListElement* next = to_remove->next;
        prev->next = next;
        next->prev = prev;
        --m_count;

        if (to_remove == m_head)
        {
            m_head = next;
        }

        delete to_remove;

        return iterator(prev);
    }

    LinkListElement* m_head;
    LinkListElement* m_tail;
    uint32_t         m_count;
};

template <typename T> T list<T>::iterator::dummy;

#endif

A: You code has all kinds of features and checks that the STL doesn't have. So it makes sense that you would wind up with more code.
Yes, the STL has lots of features your code doesn't have. But you aren't using any of them, so they don't show up in your code footprint. The STL is designed using templates so that you don't pay for what you don't use.
It's unlikely you can improve on the STL. If you need to add features, add them. You don't need to reinvent the wheel.


text:
Q: AngularJS bootstrap or load controllers on the fly I think the answer to this question is "no" but I'm asking it anyways as I cant seem to find a definitive answer.
Can angularjs load controllers on the fly?
To explain further, I have an angular app that is bootstrapped the default way, via ng-app.Example, the index.html file:
<!doctype html>
<html>
<head>
    <title>myapp</title>
</head>
<body ng-app="app">
...
<app-body></app-body>
<script src="lib/angular/angular.min.js"></script>
<script src="app/app.js"></script>
...

Inside the app module, I have a route setup, something like this:
$routeProvider
          .when('/Home', {
              templateUrl: 'home/home.html',
              controller: 'HomeController'
          })
          .when('/Behaviors', {
              templateUrl: 'contact/contact.html',
              controller: 'ContactController'
          });
        // etc.

I was curious - is there a way to load the HomeController.js file when the user goes to that route? So that js file is not set in the index.html above, but inside the home/home.html:
<script src="home/HomeController.js"></script>

Is something like this possible?

A: Yes, AngularJS is able to dynamically load route controllers and dependencies such as factories. It would require the use of RequireJS. RequireJS would be your entry point, which would load Angular.
The angular route's resolve property would kick off a call to some code that resolved a file via RequireJS. Since the resolve property utilizes promises the route won't load until the file is loaded.
Alternatively you could optimize an app using something like GulpJS, Gulp-angular-template cache, concat, uglify, etc. Here is an example:
http://weblogs.asp.net/dwahlin/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs


text:
Q: Installing XP Office 2002 on Windows 7 in virtual XP mode I'm running Windows 7 64bit and have successfully installed the virtual machine and XP mode. I'm currently running Microsoft Office Outlook 2007. I want to install Windows XP Office 2002 to get access to the Outlook software.
What do I need to do before I start the installation process?
I don't want the outlook 2002 software install to "stomp" all over the current installation of office within the windows 7.

A: Mount the ISO in the XP VM or connect to it via a share and install it in XP.  If you installed Office / Outlook 2007 in Windows 7, then installing 2002 / XP in XP Mode won't touch the Windows 7/2007 install (XP Mode is a separate computer within your Windows 7 computer.


text:
Q: Firebase seems to use old data snapshot When in the Android app I'm developing I create a new Radiator, the firebase dashboard immediately shows me the new Radiator.
Anyway, when in another Activity i want to retrive all the radiators, it only retrieves the number of radiators of some time ago.
It seems like it is using an old data snapshot version.
I'm working Online and even closing and restarting the app has no impact.
After waiting a few minutes it retrieves the right number of radiators.
class RegisteredMaterialValueEventListener implements ValueEventListener {
    @Override
    public void onDataChange(DataSnapshot mDataSnapshot) {
        listRadiators = new ArrayList<Radiator>();
        if (firstLoad) {
            if (mDataSnapshot.hasChildren()) {
                Iterable<DataSnapshot> i = mDataSnapshot.getChildren();
                Iterator<DataSnapshot> radiatosIterator = i.iterator();
                if (radiatosIterator.hasNext()) {
                    listRadiators.clear();
                }
                while (radiatosIterator.hasNext()) {
                    DataSnapshot c = radiatosIterator.next();
                    listRadiators.add(c.getValue(Radiator.class));
                }
            }
    }
 }


text:
Q: How to UI test UICollectionViewCell didSelect I have a UIViewController that has a child UIViewController, this child holds a UICollectionView and inside this collectionView I need to simulate  a didSelect method or in other words, a user tapped on a UICollectionViewCell.
I tried to record and got something like this:
app.buttons["Tap here"].tap()

Which didn't work at all when I tried to run the test again.
Any suggestions?

A: I would suggest you look deeper into writing UI Test without recording.
Recording is fine for the basic UI's but if you use CollectionViews and TableViews, these tests tend to get even more fragile if you use the record function.
Have a look into this answer to get started: Stackoverflow


text:
Q: ExtJS 6 how to set Ext,panel.Panel items dynamically I need to update the items on a mounted Panel from the responses on an AJAX request.
I have this panel:
Ext.define('myComponents.MyPanelView', {
    extend: 'Ext.panel.Panel',
    id: 'idMyPanel',
    itemId: 'idMyPanel',
    alias: 'widget.WidgetMyPanel',
    scrollable: true,
    requires: [],
    layout: {
        type: 'table',
        columns: 4,
        tableAttrs: {
            style: {
                width: '100%',
                padding: '10px'
            }
        },
        tdAttrs: {
            style: {
                'vertical-align': 'top'
            }
        }
    },
    items: [
    ],

    initComponent: function () {
        this.callParent(arguments);
    }
});

and in a controller I have this:
Ext.define('myComponents.myController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.MyController',
    requires: [],
    views: ['myComponents.MyPanelView'],
    stores: [],
    models: [],

    init: function () {
        this.control({
            'WidgetMyPanel #deployer': {
                'itemclick': function (treenode, record, item, index, e, eOpts) {
                    Ext.Ajax.request({
                    url: 'myURL',
                    method: 'GET',
                    headers,
                    success: function (response) {

                        const myComponent = Ext.getCmp('idMyPanel');

                        // myComponent.setItems( items from the response )
                        //                ^
                        //                |---- I need something here to update the items

                    },
                    failure: function (response) { console.log('Failure'); }
                });
                }
            }
        });
    }
});

I tried
myComponent.items.items = [ //... items here ]

and it shows no error, but does not update the view. Also tried:
myComponent.items.items.push( //... items here )

again no error but the view remains with no changes.
I need every time the response is successfull the items to be displayed, but I can't figure it out how to do so. How can I achieve this?

A: try using the add() method from Ext.Panel.
myComponent.add(item);


text:
Q: No symbols in google breakpad stack trace when applying compiler optimizations The main point of a crash reporter tool like Google breakpad is to generate core dump or minidump files from stripped binaries to process later with debugging symbols. normally these binaries are release builds with compiler optimizations applied and also stripped.
To reproduce the problem on Linux:
1.Build + install google breakpad:
git clone https://chromium.googlesource.com/breakpad/breakpad && cd breakpad
git clone https://chromium.googlesource.com/linux-syscall-support src/third_party/lss
./configure --prefix=/usr/local
make -j$(nproc) && sudo make install

2.The Code:
CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)

project(BreakPadTest)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_VERBOSE_MAKEFILE TRUE)
set(BREAKPAD_DIR "/usr/local/include/breakpad")

option(OPTION_WITH_O1 "With -O1" OFF)
if(OPTION_WITH_O1)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O1 -fno-omit-frame-pointer")
endif()

include_directories(
    ${BREAKPAD_DIR}
    )

add_executable(${PROJECT_NAME} "main.cc")

target_link_libraries(${PROJECT_NAME}
    -lstdc++fs
    -pthread
    libbreakpad_client.a
    )

main.cc:
#include <thread>
#include <experimental/filesystem>

#include <client/linux/handler/exception_handler.h>

namespace breakpad = google_breakpad;
namespace filesystem = std::experimental::filesystem;

static bool DumpCallBack(const breakpad::MinidumpDescriptor& md,
                         void* context,
                         bool success) {
    (void)md;
    (void)context;
    return success;
}

static void fault(unsigned after) {
    std::this_thread::sleep_for(std::chrono::seconds{after});
    delete reinterpret_cast<std::string*>(0xFEE1DEAD);
}

int32_t main(int argc, char** argv) {
    (void)argc;
    (void)argv;

    auto pwd = filesystem::current_path();
    const auto dumpDir = pwd.string() + "/dumps";
    filesystem::create_directory(dumpDir);
    breakpad::MinidumpDescriptor md(dumpDir);
    new google_breakpad::ExceptionHandler(
        md,
        /* FilterCallback */ nullptr,
        DumpCallBack,
        /* callback_context */ nullptr,
        true,
        -1
    );

    fault(1U);

    return EXIT_SUCCESS;
}

dump.sh:
#!/bin/bash

#
# e.g ./dump.sh ./exec $PWD/dumps
#

set -e
set -u

DBG_INFO=$(realpath ${1})
DUMPS_DIR=$(realpath ${2:-$PWD/dumps})
DUMP_SYMS=${3:-~/WorkSpace/libraries/breakpad/src/tools/linux/dump_syms/dump_syms}
STAK_WALK=${4:-~/WorkSpace/libraries/breakpad/src/processor/minidump_stackwalk}

#
# Generate debug symbols
#
base=$(basename $DBG_INFO)
$DUMP_SYMS $DBG_INFO > $DUMPS_DIR/$base.sym

#
# Create dump dir structure
#
list=($(head -n1 $DUMPS_DIR/$base.sym))
hash=${list[3]}
mkdir -p $DUMPS_DIR/symbols/$base/$hash
mv $DUMPS_DIR/$base.sym $DUMPS_DIR/symbols/$base/$hash

#
# Produce stack trace
#
RED='\033[0;36m'
NC='\033[0m' # No Color
tree $DUMPS_DIR
for dmp in $DUMPS_DIR/*.dmp ; do
    filename=$(basename -- "${dmp}")
    filename="${filename%.*}"
    echo -e "generating stack trace for -> ${RED}${dmp}${NC}"
    $STAK_WALK ${dmp} $DUMPS_DIR/symbols > $DUMPS_DIR/${filename}.txt 2>/dev/null
done

3.Run normal Debug version:
cmake -DCMAKE_BUILD_TYPE=Debug . && make
./BreakPadTest

4.Process minidump generated from stage 3:
./dump.sh ./BreakPadTest ./dumps

stackwalk:
Operating system: Linux
                  0.0.0 Linux 4.19.0-16-amd64 #1 SMP Debian 4.19.181-1 (2021-03-19) x86_64
CPU: amd64
     family 6 model 58 stepping 9
     1 CPU

GPU: UNKNOWN

Crash reason:  SIGSEGV /SEGV_MAPERR
Crash address: 0xfee1dead
Process uptime: not available

Thread 0 (crashed)
 0  BreakPadTest!std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_data() const [basic_string.h : 176 + 0x4]
    rax = 0x00000000fee1dead   rdx = 0x00007ffcfccfcb90
    rcx = 0x00007f5b0cbb4bc1   rbx = 0x0000557d577eb8e0
    rsi = 0x00007ffcfccfcb90   rdi = 0x00000000fee1dead
    rbp = 0x00007ffcfccfcb50   rsp = 0x00007ffcfccfcb50
     r8 = 0x0000000000000000    r9 = 0x0000557d577efaf8
    r10 = 0xfffffffffffff60b   r11 = 0x0000000000000246
    r12 = 0x0000557d56d3d2c0   r13 = 0x00007ffcfccfce50
    r14 = 0x0000000000000000   r15 = 0x0000000000000000
    rip = 0x0000557d56d3dfda
    Found by: given as instruction pointer in context
 1  BreakPadTest!std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_is_local() const [basic_string.h : 211 + 0xc]
    rbx = 0x0000557d577eb8e0   rbp = 0x00007ffcfccfcb80
    rsp = 0x00007ffcfccfcb60   r12 = 0x0000557d56d3d2c0
    r13 = 0x00007ffcfccfce50   r14 = 0x0000000000000000
    r15 = 0x0000000000000000   rip = 0x0000557d56d3e2c5
    Found by: call frame info
 2  BreakPadTest!std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_dispose() [basic_string.h : 220 + 0xc]
    rbx = 0x0000557d577eb8e0   rbp = 0x00007ffcfccfcba0
    rsp = 0x00007ffcfccfcb90   r12 = 0x0000557d56d3d2c0
    r13 = 0x00007ffcfccfce50   r14 = 0x0000000000000000
    r15 = 0x0000000000000000   rip = 0x0000557d56d3dff8
    Found by: call frame info
 3  BreakPadTest!std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() [basic_string.h : 657 + 0xc]
    rbx = 0x0000557d577eb8e0   rbp = 0x00007ffcfccfcbc0
    rsp = 0x00007ffcfccfcbb0   r12 = 0x0000557d56d3d2c0
    r13 = 0x00007ffcfccfce50   r14 = 0x0000000000000000
    r15 = 0x0000000000000000   rip = 0x0000557d56d3d930
    Found by: call frame info
 4  BreakPadTest!fault [main.cc : 19 + 0xa]
    rbx = 0x0000557d577eb8e0   rbp = 0x00007ffcfccfcbf0
    rsp = 0x00007ffcfccfcbd0   r12 = 0x0000557d56d3d2c0
    r13 = 0x00007ffcfccfce50   r14 = 0x0000000000000000
    r15 = 0x0000000000000000   rip = 0x0000557d56d3d3f0
    Found by: call frame info
 5  BreakPadTest!main [main.cc : 39 + 0xa]
    rbx = 0x0000557d577eb8e0   rbp = 0x00007ffcfccfcd70
    rsp = 0x00007ffcfccfcc00   r12 = 0x0000557d56d3d2c0
    r13 = 0x00007ffcfccfce50   r14 = 0x0000000000000000
    r15 = 0x0000000000000000   rip = 0x0000557d56d3d4fd
    Found by: call frame info
 6  libc.so.6 + 0x2409b
    rbx = 0x0000000000000000   rbp = 0x0000557d56d78b80
    rsp = 0x00007ffcfccfcd80   r12 = 0x0000557d56d3d2c0
    r13 = 0x00007ffcfccfce50   r14 = 0x0000000000000000
    r15 = 0x0000000000000000   rip = 0x00007f5b0ca0609b
    Found by: call frame info
 7  BreakPadTest!fault [main.cc : 20 + 0x3]
    rsp = 0x00007ffcfccfcda0   rip = 0x0000557d56d3d402
    Found by: stack scanning
 8  ld-linux-x86-64.so.2 + 0xf476
    rsp = 0x00007ffcfccfce10   rip = 0x00007f5b0cf1c476
    Found by: stack scanning
 9  BreakPadTest!_start + 0x2a
    rsp = 0x00007ffcfccfce40   rip = 0x0000557d56d3d2ea
    Found by: stack scanning
10  0x7ffcfccfce48
    rsp = 0x00007ffcfccfce48   rip = 0x00007ffcfccfce48
    Found by: call frame info

Loaded modules:
0x557d56d34000 - 0x557d56d78fff  BreakPadTest  ???  (main)
0x7f5b0c9e2000 - 0x7f5b0cb4bfff  libc.so.6  ???  (WARNING: No symbols, libc.so.6, A8A9B91823C5CFE5E5B5D946D605D0920)
0x7f5b0cba3000 - 0x7f5b0cbb7fff  libpthread.so.0  ???
0x7f5b0cbc4000 - 0x7f5b0cbd7fff  libgcc_s.so.1  ???
0x7f5b0cbde000 - 0x7f5b0cc89fff  libm.so.6  ???
0x7f5b0cd61000 - 0x7f5b0ce95fff  libstdc++.so.6  ???
0x7f5b0cf0d000 - 0x7f5b0cf2bfff  ld-linux-x86-64.so.2  ???  (WARNING: No symbols, ld-linux-x86-64.so.2, 7BFD5DF2BE95A34B86FD71080ACCAE8C0)
0x7ffcfcdc5000 - 0x7ffcfcdc6fff  linux-gate.so  ???

5.Run stage 3 with -O1:
cmake -DCMAKE_BUILD_TYPE=Debug -DOPTION_WITH_O1=ON . && make
./BreakPadTest

6.Process minidump like stage 4:
stackwalk:
Operating system: Linux
                  0.0.0 Linux 4.19.0-16-amd64 #1 SMP Debian 4.19.181-1 (2021-03-19) x86_64
CPU: amd64
     family 6 model 58 stepping 9
     1 CPU

GPU: UNKNOWN

Crash reason:  SIGSEGV /SEGV_MAPERR
Crash address: 0xfee1dead
Process uptime: not available

Thread 0 (crashed)
 0  BreakPadTest!main [basic_string.h : 176 + 0x0]
    rax = 0x0000000000000000   rdx = 0x000055bd46f66a40
    rcx = 0x00007f7633ea8bc1   rbx = 0x00007ffde4cc7c40
    rsi = 0x00007ffde4cc7c40   rdi = 0x00007ffde4cc7c40
    rbp = 0x00007ffde4cc7d90   rsp = 0x00007ffde4cc7c20
     r8 = 0x0000000000000000    r9 = 0x000055bd474caaf8
    r10 = 0x0000000000000000   r11 = 0x0000000000000246
    r12 = 0x000055bd474c64f0   r13 = 0x000055bd474c64f0
    r14 = 0x0000000000000000   r15 = 0x0000000000000000
    rip = 0x000055bd46f1b8dd
    Found by: given as instruction pointer in context
 1  libc.so.6 + 0x2409b
    rbx = 0x0000000000000000   rbp = 0x000055bd46f555e0
    rsp = 0x00007ffde4cc7da0   r12 = 0x000055bd46f1b270
    r13 = 0x00007ffde4cc7e70   r14 = 0x0000000000000000
    r15 = 0x0000000000000000   rip = 0x00007f7633cfa09b
    Found by: call frame info
 2  BreakPadTest!DumpCallBack [main.cc : 15 + 0x3]
    rsp = 0x00007ffde4cc7dc0   rip = 0x000055bd46f1b358
    Found by: stack scanning
 3  ld-linux-x86-64.so.2 + 0xf476
    rsp = 0x00007ffde4cc7e30   rip = 0x00007f7634210476
    Found by: stack scanning
 4  BreakPadTest!_start + 0x2a
    rsp = 0x00007ffde4cc7e60   rip = 0x000055bd46f1b29a
    Found by: stack scanning
 5  0x7ffde4cc7e68
    rsp = 0x00007ffde4cc7e68   rip = 0x00007ffde4cc7e68
    Found by: call frame info

Loaded modules:
0x55bd46f14000 - 0x55bd46f55fff  BreakPadTest  ???  (main)
0x7f7633cd6000 - 0x7f7633e3ffff  libc.so.6  ???  (WARNING: No symbols, libc.so.6, A8A9B91823C5CFE5E5B5D946D605D0920)
0x7f7633e97000 - 0x7f7633eabfff  libpthread.so.0  ???
0x7f7633eb8000 - 0x7f7633ecbfff  libgcc_s.so.1  ???
0x7f7633ed2000 - 0x7f7633f7dfff  libm.so.6  ???
0x7f7634055000 - 0x7f7634189fff  libstdc++.so.6  ???
0x7f7634201000 - 0x7f763421ffff  ld-linux-x86-64.so.2  ???  (WARNING: No symbols, ld-linux-x86-64.so.2, 7BFD5DF2BE95A34B86FD71080ACCAE8C0)
0x7ffde4d9a000 - 0x7ffde4d9bfff  linux-gate.so  ???

As we can see correct symbols got disappeared from the stack walk of stage 6.
While in other tools like GDB we have correct trace pointing to right location even with -O1 as in stage 5:
Program received signal SIGSEGV, Segmentation fault.
fault (after=1) at /home/iman/WorkSpace/projects/BreakPadTest/src/main.cc:26
26      delete reinterpret_cast<std::string*>(0xFEE1DEAD);

Or in other tools like backward-cpp :
Stack trace (most recent call last):
#3    Object "", at 0xffffffffffffffff, in
#2    Object "/home/iman/WorkSpace/projects/build-CrashReporter-Desktop_Qt_5_11_3_GCC-Debug/CrashReporter", at 0x55f32a66b579, in _start
#1    Source "/build/glibc-vjB4T1/glibc-2.28/csu/../csu/libc-start.c", line 308, in __libc_start_main [0x7f56288be09a]
#0  | Source "/home/iman/WorkSpace/projects/BreakPadTest/src/main.cc", line 48, in main
    |    46: #endif // WITH_BREAKPAD
    |    47:
    | >  48:     fault(1U);
    |    49:
    |    50:     return EXIT_SUCCESS;
    | Source "/home/iman/WorkSpace/projects/BreakPadTest/src/main.cc", line 26, in fault
    |    24: static void fault(unsigned after) {
    |    25:     std::this_thread::sleep_for(std::chrono::seconds{after});
    | >  26:     delete reinterpret_cast<std::string*>(0xFEE1DEAD);
    |    27: }
    | Source "/usr/include/c++/8/bits/basic_string.h", line 657, in
    |   655:        */
    |   656:       ~basic_string()
    | > 657:       { _M_dispose(); }
    |   658:
    |   659:       /**
    | Source "/usr/include/c++/8/bits/basic_string.h", line 220, in
    |   218:       _M_dispose()
    |   219:       {
    | > 220:    if (!_M_is_local())
    |   221:      _M_destroy(_M_allocated_capacity);
    |   222:       }
    | Source "/usr/include/c++/8/bits/basic_string.h", line 211, in
    |   209:       bool
    |   210:       _M_is_local() const
    | > 211:       { return _M_data() == _M_local_data(); }
    |   212:
    |   213:       // Create & Destroy
      Source "/usr/include/c++/8/bits/basic_string.h", line 176, in main [0x55f32a66b66c]
        174:       pointer
        175:       _M_data() const
      > 176:       { return _M_dataplus._M_p; }
        177:
        178:       pointer
        179:       _M_local_data()
Segmentation fault (Address not mapped to object [0xfee1dead])
Segmentation fault

Any idea or hint?

A: With the optimisation -O1 almost all std::basic_string functions are inline. These functions are inline because std::basic_string is a template and defined in heder files.

A: There's an old and active issue with google breakpad processor sub-system to handle inline functions or extract inline functions metadata from DWARF debugging information on linux as discussed in these topics:

*

*https://bugzilla.mozilla.org/show_bug.cgi?id=524410

*https://bugzilla.mozilla.org/show_bug.cgi?id=563776

*https://bugzilla.mozilla.org/show_bug.cgi?id=1665367

*https://bugzilla.mozilla.org/show_bug.cgi?id=1398533

*https://bugzilla.mozilla.org/show_bug.cgi?id=1636194

*https://groups.google.com/g/google-breakpad-discuss/c/ZQOSZBbdF7U/m/58tpSnM1EBsJ
Which requires modification on breakpad internal symbols representation and stack walker but as a workaround you could generate core dump for GDB and get a backtrace with it, for that to happen there's utility inside breakpad code base(src/tools/linux/md2core) called minidump-2-core, so after building your release binary with debugging information:
$ objcopy --only-keep-debug BreakPadTest BreakPadTest.debug
$ strip BreakPadTest
$ ./BreakPadTest
Segmentation fault
$ minidump-2-core -o dumps/45a855b5-8931-4e7e-5f508496-3fe1cacc.core dumps/45a855b5-8931-4e7e-5f508496-3fe1cacc.dmp
$ gdb -c dumps/45a855b5-8931-4e7e-5f508496-3fe1cacc.core BreakPadTest.debug
Program terminated with signal SIGSEGV, Segmentation fault.
#0  std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_is_local (this=0xfee1dead) at /usr/include/c++/8/bits/basic_string.h:656
656       ~basic_string()
(gdb) backtrace
#0  std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_is_local (this=0xfee1dead) at /usr/include/c++/8/bits/basic_string.h:656
#1  std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_dispose (this=0xfee1dead) at /usr/include/c++/8/bits/basic_string.h:220
#2  std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string (this=0xfee1dead, __in_chrg=<optimized out>)
    at /usr/include/c++/8/bits/basic_string.h:657
#3  fault (after=1) at /home/iman/WorkSpace/projects/BreakPadTest/src/main.cc:19
#4  main (argc=<optimized out>, argv=<optimized out>) at /home/iman/WorkSpace/projects/BreakPadTest/src/main.cc:39
(gdb)


text:
Q: How set Response body in javax.ws.rs.core.Response There is a REST API endpoint which needs to be implemented is used to get some information and send backend request to an another server and response which is coming from backend server has to set the to final response. My problem is how to set response body in javax.ws.rs.core.Response?
@Path("analytics")
@GET
@Produces("application/json")
public Response getDeviceStats(@QueryParam("deviceType") String deviceType,
                               @QueryParam("deviceIdentifier") String deviceIdentifier,
                               @QueryParam("username") String user, @QueryParam("from") long from,
                               @QueryParam("to") long to) {

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = null;
    try {
        sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new File(getClientTrustStoretFilePath()), "password## Heading ##".toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();
    } catch (NoSuchAlgorithmException e) {
        log.error(e);
    } catch (KeyManagementException e) {
        log.error(e);
    } catch (KeyStoreException e) {
        log.error(e);
    } catch (CertificateException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    }
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslcontext,
            new String[] { "TLSv1" },
            null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();
    HttpResponse response = null;
    try {
        HttpGet httpget = new HttpGet(URL);
        httpget.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
        httpget.addHeader("content-type", "application/json");
        response = httpclient.execute(httpget);
        String message = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (ClientProtocolException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    }

}

Here message is the one I need to set. But I tried several methods. Didn't work any of them.

A: One of the following solutions should do the trick:
return Response.ok(entity).build();

return Response.ok().entity(entity).build();

For more details, have a look at Response and Response.ResponseBuilder classes documentation.
Tip: In the Response.ResponseBuilder API you might find some useful methods that allow you to add information related to cache, cookies and headers to the HTTP response.


text:
Q: Android Camera picture not showing in ImageView I am trying to take a picture with the camera of "Nexus 5X API 26" and show it in ImageView field, before uploading it to Firebase.
First problem is that after taking a picture, it does not show up in imageView. I am doing the following:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, CAMERA_REQUEST_CODE);}

And then I was trying to show the picture in the same way I do for the pictures taken from Gallery:
filePath = data.getData();
   try {
      Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
      imageView.setImageBitmap(bitmap);
   } catch (IOException e) {
       e.printStackTrace();
   }

The part which I do not understand is how data.getData() works in both cases (for Gallery and for Camera)?
I guess that the uploadImage() method, should be the same for both Gallery and Camera uploads (it works for Gallery already so...).
So the thing that I am currently missing is that I am not getting the filePath, I guess?
Is it necessary to "temporarily save" the camera's picture in order to .getData()? Or it can work without any kind of "saving"?
I just want the user to take a picture and it should be sent to Firebase. Not necessary for user to see it in imageView first, just to get the uri (data) in order to upload it.
view when i open the camera
   view after taking a picture

A: This will help you.
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
       startActivityForResult(intent,7);

     @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

            super.onActivityResult(requestCode, resultCode, data);

                    bitmap= (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream baos=new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] b = baos.toByteArray();
            imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);

            byte[] imageAsBytes = Base64.decode(imageEncoded.getBytes(), Base64.DEFAULT);
            InputStream is=new ByteArrayInputStream(imageAsBytes);
            bitmap1=BitmapFactory.decodeStream(is);
            img.setImageBitmap(bitmap1);

        }


text:
Q: blazor google maps refreshes on programmatic marker click I have a Blazor app in which I place markers on a google map.  The end user can click on a marker to have it update the selected value of a "select location" dropdown displayed below the map -- this works perfectly.
If the user selects a map location from the dropdown, I call a function, "clickPin", that programatically clicks the pin for that map location.
The trouble is that immediately after the marker is clicked programatically I see the Marker pop up for a split second, then the map refreshes.  I'm not sure if it's the dropdown acting like a submit button (I don't think it is...?), the script forcing a reload, or something built into Google Maps.
I have searched all over google and stackoverflow, and I have not been able to find a solution that even mentions this problem.
Here are the important parts of my code:
First, the scripts to deal with the maps:
var mapOptions = null;
var map = null;
var infoWindow = null;
var markers = [];

function initialize(coords) {
    mapOptions = {
        center: new google.maps.LatLng(35.68484978380786, -86.60681036623693),
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    infoWindow = new google.maps.InfoWindow();
    map = new google.maps.Map(document.getElementById("map"), mapOptions);
}

function addpins(name, lat, lng, desc) {
    var data = { name, lat, lng, desc };
    var myLatLng = new google.maps.LatLng(data.lat, data.lng);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: data.name
    });
    markers.push(marker);
    (function (marker, data) {
        google.maps.event.addListener(marker, "click", function (e) {
            infoWindow.setContent(data.desc);
            infoWindow.open(map, marker);
        });
    })(marker, data);
    (function bindInfoWindow(marker, map, infoWindow) {
        google.maps.event.addListener(marker, 'click', function () {
            Array.from(document.querySelector("#test").options).forEach(function (option_element) {
                let option_text = option_element.text;

                if (option_text === marker.title) {
                    option_element.selected = true;
                }
            });
        });
    })(marker, map, infoWindow);
}

function clickPin(txt) {
    markers.forEach(function (m) {
        let val = m.title;
        if (txt === val) {
            google.maps.event.trigger(m, 'click');
        }
    });
}

Second, The razor page:
@inject IJSRuntime JSRuntime

<select id="test" value="@testId" @onchange="@ClickPin">
     @foreach (var inf in Infos)
     {
        <option value="@inf.Name">@inf.Name</option>
     }
</select>

Third, calling "clickPin":
private int? testId { get; set; }

internal async Task ClickPin(ChangeEventArgs e)
{
    var selVal = e.Value.ToString();
    await JSRuntime.InvokeVoidAsync("clickPin", new string[] { selVal });
}

I'm hoping I'm missing something incredibly simple.  Any suggestions are welcome.
...and it turns out that I was missing something incredibly simple.  ::sigh::
In my OnAfterRenderAsync function:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await base.OnAfterRenderAsync(firstRender);
    Infos = await Info.GetAll();
    if (firstRender) { StateHasChanged(); }
    else { await LoadMapPins(); }
}

should read as:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await base.OnAfterRenderAsync(firstRender);
    Infos = await Info.GetAll();
    if (firstRender) { StateHasChanged(); await LoadMapPins(); }
    //else { await LoadMapPins(); }
}

I was running LoadMapPins anytime the page refreshed. ::sigh::
Sorry for the wasted time.  I'll leave the question here, though -- maybe someone else can get some use out of it.
Thanks,
Carthax

A: ...and it turns out that I was missing something incredibly simple. ::sigh::
In my OnAfterRenderAsync function:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await base.OnAfterRenderAsync(firstRender);
    Infos = await Info.GetAll();
    if (firstRender) { StateHasChanged(); }
    else { await LoadMapPins(); }
}

should read as:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await base.OnAfterRenderAsync(firstRender);
    Infos = await Info.GetAll();
    if (firstRender) { StateHasChanged(); await LoadMapPins(); }
    //else { await LoadMapPins(); }
}

I was running LoadMapPins anytime the page refreshed. ::sigh::
Sorry for the wasted time. I'll leave the question here, though -- maybe someone else can get some use out of it.


text:
Q: Name of object in string - how to use it I'm trying to find a way to print text from an object that name is in another string in Groovy.
Here is a simple example:
def object1 = "some text"
def object2 = "object1"
println(object2)

It gives me object1. How to modify the third line to get output as some text?

A: You can use the binding script properties:
def object1 = "some text"
def object2 = "object1"
binding.setProperty('object1', object1)
println(evaluate(object2))


text:
Q: Fetching data from mongodb through nodejs and express to a html page Basically, I want to show particular fields from "employees" collection into a html page. But even after searching a lot on web, I'm unable to do so.
Here is the route part from the server.js file:
app.get('/fetching', function(req, res){
    connection.fetcher(function(data)
        {
            res.render("testing.html",data);
        }
    );
});

Now this is the part from connection.js file:
var fetcher= function(callback) {
    var mongodb = require('mongodb');
    var MongoClient = mongodb.MongoClient;

    var url = 'mongodb://localhost:27017/HippoFeedo';

    MongoClient.connect(url, function (err, db) {
        if (err) {

            console.log('Unable to connect to the mongoDB server. Error:', err);
        }

        else {
            console.log('Connection established to', url);

            // Get the documents collection
            var collection = db.collection('employees');

            collection.find({},function (err, result) {
                if (err) {
                    console.log(err);
                } else {

                    console.log(result);
                    callback(result);
                }

            });
        }
    });

Now, findOne is working fine and returning the value to server.js file perfectly. But I need to use "find", so how to send the complete array to the server.js through callback?
And moreover, I need to send that retrieved data from server.js to a HTML file called testing.html through rendering and display it through angular js. Please explain a simple way to do so.
EDIT:
I got to know how to work with "find", I just used "toArray" alongwith "find" in function. And now, I'm able to return the value to server.js through call back. But the other question is still unsolved: How do I pass those values to the html page?

A: Using ejs, you need to set the view engine:
app.set('view engine', 'ejs');

Then get your data:
 app.get('/employees',(req , res) =>{
    db.collection('employees').find().toArray(function(err , i){
        if (err) return console.log(err)

        res.render('index.ejs',{employees: i})
     })
 });

The .ejs file would be like this:
employees

  <% for(var i=0; i<employees.length; i++) {%>

      <%= " Nome: " +employees[i].name+"."%>
      <%=" Address: " + employees[i].address%>

  <% } %>

Just a simple way using ejs. Hope it helps to clarify things.


text:
Q: Reload  info with  action I have a <p:tabView> with 2 tabs. The first one contains student details and the second one contains a table of all students.
<p:tab title="List">
    <p:dataTable id="studentsTable" value="#{studentMB.allStudents}" var="student">
        <p:column>
            <f:facet name="header"><h:outputText value="ID"/></f:facet>
            <h:outputText value="#{student.id}"/>
        </p:column>
        <p:column>
            <f:facet name="header"><h:outputText value="Name"/></f:facet>
            <h:outputText value="#{student.name}"/>
        </p:colum>
        <p:column>
            <p:commandButton value="Details" onclick="tabVar.select(0);" />
        </p:column>
    </p:dataTable>
</p:tab>

When the "Details" button in the table is pressed, then I would like to show the selected student in the first tab. How can I achieve this?

A: Primefaces tabview has activeIndex attribute, you can bind to bean variable:
<p:tabView id="tabView" activeIndex="#{studentMB.tabindex}">

In each commandButton action, you pass value to determine student.
<p:commandButton update=":tabView" value="Details" actionListener="#{studentMB.handUpdate(student)}" />

Bean:
public void handUpdate(StudentType stValue){
        // get student detail
    }

(Sorry for my english)