text:
Q: C++ Google getting started exercise #4 https://developers.google.com/edu/c++/getting-started#exercises-and-projects
I'm referring to exercise #4 - Banner
I'm having a little trouble understand how this would work. I have created the different functions for each letter, "F" "R" & "E".
"F", for example:
void printF(){
cout<<"FFFFF"<<endl;
cout<<"F"<<endl;
cout<<"FFF"<<endl;
cout<<"F"<<endl;
cout<<"F"<<endl;
}

As far as I can tell, this won't work because there is no way to print something like this, and then print another right next to it.  Can somebody explain conceptually or provide an example of how I could print the word "FREE"?  Thank you

A: You can create your letters as an std::string array. For consistency, it's five strings five characters long. You can use a function like get_font_letter to select the current letter. There are better ways to do this, but if you only care about this word, it should be fine for the moment. I suggest doing something like a "font database" where you draw and index the letters in a textfile.
#include <iostream>
#include <vector>

std::string f[] = {
    "FFFFF",
    "F    ",
    "FFF  ",
    "F    ",
    "F    ",
};

std::string r[] = {
    "RRRRR",
    "R   R",
    "RRRR ",
    "RRR  ",
    "R  RR",
};

std::string e[] = {
    "EEEEE",
    "E    ",
    "EEE  ",
    "E    ",
    "EEEEE",
};

std::string* get_font_letter(const char& c)
{
    if (c == 'F') return f;
    if (c == 'R') return r;
    if (c == 'E') return e;
}

You don't need a two-dimensional std::vector. You can just piece each row together with a single space.
int main()
{
    std::string word = "FREE";
    std::vector<std::string> v;
    v.resize(5);
    for (unsigned int i = 0; i < 5; i++)
    {
        std::string row = "";
        for (auto it = word.begin(); it != word.end(); ++it)
        {
            auto letter = get_font_letter(*it);
            row += letter[i] + " ";
        }
        v.push_back(row);
    }
    for (auto it = v.begin(); it != v.end(); ++it)
        std::cout << *it << "\n";
}

Output:
FFFFF RRRRR EEEEE EEEEE
F     R   R E     E
FFF   RRRR  EEE   EEE
F     RRR   E     E
F     R  RR EEEEE EEEEE

A: Without giving you the complete solution since you're obviously there to learn, that would be my strategy:
Use vector of strings(or 2-D array) to represent a letter. Then build a list of those vector to represent the string and print all vector string by string(Print 1st string of all vectors, then second, etc). The individual strings should be of constant length and provide some spacing.

A: This is what I did in this example.

*

*First I thought to create a function like printA(), printB() just described in the question details. But I realized the same problem. Also, it would mean that we need to create more than 26 such functions for each of the letters in alphabet and symbols. So, didn't use this approach.

*I considered that the letter would be of 5x5 size. We need something what dot matrix printer does. It prints 1st line of dots of each letter in the string and then second line of dots of next and so on. Instead of dots, the letter we are printing needs the same symbol. For example if we are printing H, the dots will be 'H'.

*So, how to do this in minimum lines of code and less complexity?
I decided to create bitflags for rows. Considering that there are 5 dots in a row, there will be 32 combinations possible. Like - 10000, 11000, 11100 etc.
While implementing that, I came to know that we don't need that many to define letters in alphabet. Something like this -
const unsigned char EOne  = 0x1F;       // 000 11111
const unsigned char BOne  = 0x1E;       // 000 11110
I gave intuitive names to the bitFlags to know where they belong in the letter.
Here is nice information about bitflags - http://www.learncpp.com/cpp-tutorial/3-8a-bit-flags-and-bit-masks/

*Next step is to create the design for each letter in alphabet. Like -
const unsigned char A[5] = {AOne, ATwo, EOne, AFiv, AFiv};
const unsigned char B[5] = {BOne, AFiv, BOne, AFiv, BOne};
const unsigned char J[5] = {~EThr, ~BOne, ~BOne, AFiv, ~AFiv};
So, this formed the design of letters A, B, C.. Z.

*In the next step, a map can be created between letters in alphabet and their design.

*When the user enters string to print, in a for loop of 5 iterations, you can take - 0th letter: 0th bitflag in its design, 1st letter: 1st bitflag in its design.. nth letter: 1st bitflag in its design.
Then again, 0th letter: 1st bitflag, 1st letter: 1st bitflag, nth letter: 1st bitflag.. until you print all the 5 rows.

*What to do with the bitflag? I used std::bitset and tested each bit so that to print or leave blank space. lineBits is the bitflag for particular letter's design row.
std::bitset<8> bits(lineBits);
// Since we have only 5x5 letter, we start with leftmost bit (4th) to rightmost (0th)
for(int bitpos = 4; bitpos >= 0; bitpos--)
{
    if(bits.test(bitpos))
    {
        cout << letter;
        outFile << letter; // In file.
    }
    else
    {
        cout << " ";
        outFile << " "; // In file.
    }
}

This way, with reduced lines of code, I could print any string. Since, I used map, it was easy to print the symbol of the letter which was getting printed.
FFFFF  RRRR   EEEEE  EEEEE  ZZZZZ  Y   Y
F      R   R  E      E          Z   Y Y
FFF    RRRR   EEE    EEE      Z      Y
F      R R    E      E      Z        Y
F      R  RR  EEEEE  EEEEE  ZZZZZ    Y

Takes a while to design all the letters though. Let me know how this code can be improved.


text:
Q: Using multiple else if statements I was trying to make a calculator in VBScript to test my skill, but came across an error. My program uses multiple else if statement to test what the user has input.
Here is my code below:
Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans

head = "Calculator"

msg1 = msgBox("Ruan's Vbscript calculator",0,head)
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)

num1 = inputBox("Enter your first number",head)
num2 = inputBox("Enter your second number",head)

if (input1 = vbcancel) then
    wscript.quit()
else if (input1 = "+") then
    ans = num1 + num2
else if (input1 = "-") then
    ans = num1 - num2
else if (input1 = "*") then
    ans = num1 * num2
else if (input1 = "/") then
    ans = num1 / num2
else
    msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if

msgAns = msgBox "Your answere is: " + head

When I run the program, the error says: "Expected end of statement". I don't see the problem here, as I have end if after all those else if statements.

A: Remove the space between else and if and make it elseif. Like this:
if (input1 = vbcancel) then
    wscript.quit()
elseif (input1 = "+") then
    ans = num1 + num2
elseif (input1 = "-") then
    ans = num1 - num2
elseif (input1 = "*") then
    ans = num1 * num2
elseif (input1 = "/") then
    ans = num1 / num2
else
    msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if

With the additional space between else and if you start a new if statement nested in the else branch rather than continuing the first if statement. The nested if statements require end ifs of their own, which is why you're getting the error.

A: Minimal improvements to make it work:
Option Explicit

Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans

head = "Calculator"
msgBox "Ruan's Vbscript calculator", 0, head
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)
If Not IsEmpty(input1) Then
   num1 = CDbl(inputBox("Enter your first number",head))
   num2 = CDbl(inputBox("Enter your second number",head))
   if     input1 = "+" then
      ans = num1 + num2
   elseif input1 = "-" then
      ans = num1 - num2
   elseif input1 = "*" then
      ans = num1 * num2
   elseif input1 = "/" then
      ans = num1 / num2
   elseif input1 = "\" then
      ans = num1 \ num2
   else
      msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
   end if
   msgBox "Your answere is: " & ans
else
   msgBox "Aborted"
end if

Type and range checks for the operants left as execise.

A: A Select Case is usually a simpler/clearer construction for selecting operations based on a single variables value
Select Case input1
    Case vbCancel
        wscript.quit()
    Case "+"
        ans = num1 + num2
    Case "-"
        ans = num1 - num2
    Case "*"
        ans = num1 * num2
    Case "/", "\" '//multiples
        ans = num1 / num2
    Case Else
        msgBox "Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces", , "Error"
End Select

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I apply mpi4py to the following loop to speed it up? In the past I have not needed to use parallel computing, because my python scripts aren't usually computationally intensive. Recently, I wrote the following for-loop and found that it takes on the order of 10 - 15 minutes to run:
cpx_var = np.linspace(0.20,0.80,301)
horn_var = np.linspace(0.20,0.80,301)
plag_var = np.linspace(0.05,0.1,26)
mag_var = np.linspace(0.02,0.06,21)
ap_var = np.linspace(0.002,0.006,3)

poss_comb = []
count=0

for i in cpx_var:
    for j in horn_var:
        for k in plag_var:
            for l in mag_var:
                for m in ap_var:
                    count = count+1
                    if abs((i+j+k+l+m)-1.0)<0.002:
                        poss_comb.append([i,j,k,l,m])
print(count)

I've been looking into mpi4py as a means to speed up my for-loop, but I am not sure how to apply it to my example. Does anyone have any suggestions?
Thanks!
Zack Eriksen

A: Although multiprocessing is a way to speed up your code, the first thing you should try is to make your code more efficient in the first place. You are using 5 nested loops, which in Python, is crazy! As much as possible in Python you should aim to use arrays to implement code instead of for-loops.
Here is a solution where I only use one for loop at the very end (it is actually a list comprehension which is a slightly faster version of a for loop). I have used the np.mesh function and then some slicing to get rid of all of the loops you had and instead only have the list comprehension to put all the results into the list format you want.
So have a play with this version. It only takes about 20 seconds to run on my laptop
import numpy as np

cpx_var = np.linspace(0.20,0.80,301)
horn_var = np.linspace(0.20,0.80,301)
plag_var = np.linspace(0.05,0.1,26)
mag_var = np.linspace(0.02,0.06,21)
ap_var = np.linspace(0.002,0.006,3)

cpx_vars, horn_vars, plag_vars, mag_vars, ap_vars = np.meshgrid(cpx_var, horn_var, plag_var, mag_var, ap_var)

selection = abs((cpx_vars + horn_vars + plag_vars + mag_vars + ap_vars)-1.0)<0.002

poss_comb = [list(comb) for comb in zip(cpx_vars[selection], horn_vars[selection], plag_vars[selection], mag_vars[selection], ap_vars[selection])]

A: I have found another way to speed up your code by another 23 times. Since I answered this question I have been learning more about a Python package called numba. This package is really clever and it essentially translates your Python functions to machine code and can give you huge speed-ups (depending on what you are doing).
I was having a play around with this package and I thought of your question here, I wanted to see how fast numba could do it compared with using numpy arrays. Doing a comparison between your code, the numpy version I pasted in the answer above, and the numba optimised version of your code. I found that the numpy (no loop) version was 23 times faster than your loop version, but the numba version was 455 times faster!
Anyway I thought you might like to see this. The numba version is about 23 times faster than my answer above. Below are 3 versions of the code I was using. I made your code into a function called original_loop_function, the numpy version I posted above into the function numpy_function and the faster numba version of the code is the function numba_loop_function. Hopefully this is still useful to you
import numpy as np
from numba import jit

cpx_var = np.linspace(0.20,0.80,301)
horn_var = np.linspace(0.20,0.80,301)
plag_var = np.linspace(0.05,0.1,26)
mag_var = np.linspace(0.02,0.06,21)
ap_var = np.linspace(0.002,0.006,3)

def original_loop_function(cpx_var, horn_var, plag_var, mag_var, ap_var):
    '''Your original version of this code'''
    poss_comb = []
    count=0

    for i in cpx_var:
        for j in horn_var:
            for k in plag_var:
                for l in mag_var:
                    for m in ap_var:
                        count = count+1
                        if abs((i+j+k+l+m)-1.0)<0.002:
                            poss_comb.append([i,j,k,l,m])
    return poss_comb

def numpy_function(cpx_var, horn_var, plag_var, mag_var, ap_var):
    '''Numpy version of your code with no loops'''
    cpx_vars, horn_vars, plag_vars, mag_vars, ap_vars = np.meshgrid(cpx_var, horn_var, plag_var, mag_var, ap_var)

    selection = abs((cpx_vars + horn_vars + plag_vars + mag_vars + ap_vars)-1.0)<0.002

    poss_comb = [list(comb) for comb in zip(cpx_vars[selection], horn_vars[selection], plag_vars[selection], mag_vars[selection], ap_vars[selection])]

    return poss_comb

@jit(nopython=True)
def numba_loop_function(cpx_var, horn_var, plag_var, mag_var, ap_var):
    '''Numba optimised version of your code'''
    poss_comb = []
    count=0

    for i in cpx_var:
        for j in horn_var:
            for k in plag_var:
                for l in mag_var:
                    for m in ap_var:
                        count = count+1
                        if abs((i+j+k+l+m)-1.0)<0.002:
                            poss_comb.append([i,j,k,l,m])
    return poss_comb


text:
Q: Can I calibrate colors on a secondary XOrg.conf screen? I have configured a secondary screen using a xorg.conf file. (This was needed for an experimental setup using MATLAB and Psychtoolbox.)
On the secondary screen, the mouse cursor is shown as a cross, and it is impossible to do anything on the screen. This is the desired behaviour, as normal users are not expected to do anything on this screen. However, it is therefore also impossible to color-calibrate the screen (using a Spyder 4), as it does not show up in the Ubuntu screen list or in a tool like DisplayCAL either.
Is there a way to calibrate colors on the secondary screen?
Thanks in advance for your assistance!


text:
Q: Invalid parameter number: number of bound variables does not match number of tokens on line 38 I am working on a login and register system and I am getting this error whenever I try to register a new account.

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /home/public_html/classes/DB.php on line 38

Line 38 is if($this->_query->execute()) {.
<?php

error_reporting(E_ALL);

class DB {
    private static $_instance = null;
    private $_pdo,
        $_query,
        $_error = false,
        $_results,
        $_count = 0;

    private function __construct() {
        try {
            $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
        } catch(PDOException $e) {
            die($e->getMessage());
        }
    }

    public static function getInstance() {
        if(!isset(self::$_instance)) {
            self::$_instance = new DB();
        }
        return self::$_instance;
    }

    public function query($sql, $params = array()) {
        $this->_error = false;
        if($this->_query = $this->_pdo->prepare($sql)) {
            $x = 1;
            if(count($params)) {
                foreach($params as $param) {
                    $this->_query->bindValue($x, $param);
                    $x++;
                }
            }
            if($this->_query->execute()){
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count = $this->_query->rowCount();
            } else {
                $this->_error = true;
            }
        }

        return $this;
    }

    public function action($action, $table, $where = array()) {
        if(count($where) === 3){
            $operators = array('=', '>', '<', '>=', '<=');

            $field          = $where[0];
            $operator       = $where[1];
            $value          = $where[2];

            if(in_array($operator, $operators)) {
                $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
                if(!$this->query($sql, array($value))->error()) {
                    return $this;
                }
            }
        }
        return false;
    }

    public function get($table, $where) {
        return $this->action('SELECT *', $table, $where);
    }

    public function delete($table, $where) {
        return $this->action('DELETE', $table, $where);
    }

    public function insert($table, $fields = array()) {
            $keys = array_keys($fields);
            $values = null;
            $x = 1;

            foreach($fields as $field) {
                $values .= '?';
                if($x < count($fields)) {
                    $values .= '. ';
                $x++;
            }

            $sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

            if(!$this->query($sql, $fields)->error()) {
                return true;
            }
        }
        return false;
    }

    public function update($table, $id, $fields) {
        $set = '';
        $x = 1;

        foreach($fields as $name => $value){
            $set .= "{$name} = ?";
            if($x < count($fields)) {
                $set .= ', ';
            }
            $x++;

        }

        $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";

        if($this->query($sql, $fields)->error()) {
            return true;
        }

        return false;
    }

    public function results() {
        return $this->_results;
    }

    public function error() {
        return $this->_error;
    }
    public function count() {
        return $this->_count;

    }
}

User.php
<?php
class User {
    private $_db,
            $_data,
            $_sessionName,
            $_isLoggedIn;

    public function __construct($user = null) {
        $this->_db = DB::getInstance();

        $this->_sessionName = Config::get('session/session_name');

        if(!$user) {
            if(Session::exists($this->_sessionName)) {
                $user = Session::get($this->_sessionName);

                    if($this->find($user)) {
                        $this->_isLoggedIn = true;
                    } else {
                        // process Logout
                    }
                }
            } else {
                $this->find($user);
        }
    }

    public function create($fields = array()) {
        if(!$this->_db->insert('users', $fields)) {
            throw new Exception('There was a problem creating an account.');
        }
    }

    public function find($user = null) {
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';
            $data = $this->_db->get('users', array($fields, '=', $user));

            if($date->count()) {
                $this->_data = $date->first();
                return true;
            }
        }
    }

    public function login($username = null, $password = null) {
        $user = $this->find($username);

        if($user) {
            if($this->data()->password === Hash::make($password, $this->data()->salt)) {
                Session::put($this->_sessionName, $this->data()->id);
                return true;
            }
        }

            return false;

    }

    public function logout() {
        Session::delete($this->_sessionName);
    }

    public function data() {
        return $this->_data;
    }

    public function isLoggedIn() {
        return $this->_isLoggedIn;
    }
}

Register.php
<?php
require_once 'core/init.php';

if(Input::exists()) {
    if(Token::check(Input::get('token'))) {
    $validate = new Validate();
    $validation = $validate->check($_POST, array(
        'username' => array(
            'required' => true,
            'min' => 2,
            'max' => 20,
            'unique' => 'users'
        ),
        'password' => array(
            'required' => true,
            'min' => 6
        ),
        'password_again' => array(
            'required' => true,
            'matches' => 'password'
        ),
        'name' => array(
            'required' => true,
            'min' => 2,
            'max' => 50
        )
    ));

        if($validation->passed()) {
            $user = new User();

            $salt = Hash::salt(32);

            try {

                $user ->create(array(
                    'username' => input::get('username'),
                    'password' => hash::make(input::get('password'), $salt),
                    'salt' => $salt,
                    'name' => input::get('name'),
                    'joined' => date('Y-m-d H:i:s'),
                    'group' => 1
                ));

                Session::flash('home', 'you have been registered and can now log in!');
                Redirect::to('index.php');

            } catch(Exception $e) {
                die($e->getMessage());
            }
        } else {
            foreach($validation->errors() as $error) {
                echo $error, '
';
            }
        }
    }
}
?>

<form action="" method="post">

        Username
        <input type="text" name="username" id="username" value"<?php echo escape(Input::get('username')); ?>" autocomplete="off">

        Choose a password
        <input type="password" name="password" id="password">

        Enter your password again
        <input type="password" name="password_again" id="password_again">

        Enter your name
        <input type="text" name="name" value"<?php echo escape(Input::get('username')); ?>" id="name">

    <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
    <input type="submit" value="Register">
</form>

A: When building your query in the insert() method, I believe the line $values .= '. '; needs to instead be $values .= ', ';
This should cause the prepared statement to be formatted correctly.


text:
Q: Axios no cancela mi solicitud HTTP en ReactJS Espero que esté bien, tengo un problema para cancelar mi solicitud axios con el gancho useEffect en ReactJS.
Explicación
En primer lugar, debes saber que mi código usa un archivo llamado Requests.js, allí se almacenan mis solicitudes personalizadas, tales como: registro, inicio de sesión y consultar información de usuario.
En estas funciones recibo la url, los datos a enviar y algunos encabezados.
Cuando uso estas funciones en mi código principal, paso un token de cancelación creado por axios, este token se crea cuando se envía el formulario, y si el usuario abandona la página en ese período de tiempo, cancelo la solicitud de axios.
Donde puede tener el problema es cómo le paso el token de cancelación a axios, ya que lo paso en función en función, hasta que llego a la función de axios.
Request.js
```import { LOGIN_URL, SIGNUP_URL, GET_INFO_USER_LOGGED } from "../Config/api";
import { alertDanger } from "./notifications";

class Requests {
  _showNetworkErrorAlert(status) {
    if (status >= 400 && status < 500) {
      alertDanger("A client network error occurred.");
    } else if (status >= 500 && status < 600) {
      alertDanger("Platform server error.");
    } else {
      alertDanger("A connection error occurred.");
    }
  }

  async _post(url, args, headers) {
    console.log({ ...headers });
    try {
      const res = await axios.post(
        url,
        {
          ...args,
        },
        {
          ...headers, // Aquí recibo las configuraciónes y el token de cancelación
        }
      );
      return res;
    } catch (error) {
      this._showNetworkErrorAlert(error?.response?.status);
    }
  }

  async _get(url, args, headers) {
    console.log(headers);
    try {
      const res = await axios.get(url, {
        ...args,
        headers,
      });
      return res;
    } catch (error) {
      this._showNetworkErrorAlert(error.response.status);
    }
  }

  async login({ email, password, headers }) {

    // Aquí paso los parametros y el argumento "headers" tiene mi token
    const loginUser = await this._post(LOGIN_URL, { email, password }, headers);
    return loginUser;
  }

  async signup({ username, email, password, headers }) {
    const signupUser = await this._post(
      SIGNUP_URL,
      {
        username,
        email,
        password,
      },
      headers // lo mismo que el anterior...
    );
    return signupUser;
  }

  async getInfoUserLogged(token) {
    const userInfoLogged = await this._get(
      GET_INFO_USER_LOGGED,
      {},
      {
        authorization: `Bearer ${token}`,
      }
    );
    return userInfoLogged?.data?.data?.user;
  }
}

export default new Requests();```

El archivo que pienso que genera el problema:
```import { Redirect } from "react-router-dom";
import axios from "axios";

// import { useSelector } from 'react-redux';

// components
import LoginComponent from "./LoginComponent";
import { alertDanger, alertSuccess } from "../../../Helpers/notifications";

// Redux elements
import { connect } from "react-redux";
import { SetCurrentUserInfo } from "../../../Redux/Actions/UserActions";

// api links
import Resquests from "../../../Helpers/Resquests";

const LoginContainer = (props) => {
  const [credentials, setCredentials] = useState({
    email: "",
    password: "",
  });

  const [isLogged, setLogged] = useState(false);
  const [isLoading, setLoading] = useState(false);
  let cancelResquest = null;

  /*

    Aquí debería de cancelar mi petición, pero axios no lo hace.
  */
  useEffect(() => {
    return () =>
      cancelResquest && cancelResquest.cancel("Finalizando peticion");
  }, []);

  const onChangeCredentials = ({ target }) => {
    setCredentials({
      ...credentials,
      [target.name]: target.value,
    });
  };

  const onSubmitForm = async (ev) => {
    ev.preventDefault();
    setLoading(true);

    /*
      Aquí genero el token de cancelación y lo envio por un parámetro.
    */
    cancelResquest = axios.CancelToken.source();
    const res = await Resquests.login(
      {
        email: credentials.email,
        password: credentials.password,

      }, // El tercer parametro es un objeto que llamé "cabeceras" allí coloco mi token
      {
        cancelToken: cancelResquest.token, // the token
      }
    );

    setLoading(false);

    if (res?.data?.ok === false) {
      alertDanger("Error in your credentials");
    } else if (res?.data?.ok === true) {
      alertSuccess("Successful login.");
      const userInfoLogged = await Resquests.getInfoUserLogged(
        res.data.data.token
      );

      props.SetCurrentUserInfo(userInfoLogged);
      console.log("en la linea 49", props.UserInformation);

      setLogged(true);
    }
  };

  return isLogged ? (
    <Redirect to="/" />
  ) : (
    <LoginComponent
      {...{ onChangeCredentials, ...credentials, onSubmitForm, isLoading }}
    />
  );
};

const mapStateToProps = (state) => ({
  UserInformation: state.UserInformation,
});

const mapDispatchToProps = {
  SetCurrentUserInfo,
};

export default connect(mapStateToProps, mapDispatchToProps)(LoginContainer);```

Muchas gracias de antemano por leer esto.

A: Lo que está pasando es que en cada renderizado de tu componente (es decir cualquier cambio de estado) a tu variable cancelRequest se le vuelve a asignarse el valor null y al salir de tu vista y llegar al return de useEffect la condición no se cumple. Tienes algunas opciones para resolver esta cuestión.
Lo más sencillo sería que movieras tu variable fuera de tu componente para que no se vea afectada, así:
let cancelResquest = null;
const LoginContainer = (props) => {
  const [credentials, setCredentials] = useState({
    email: "",
    password: "",
  });

  const [isLogged, setLogged] = useState(false);
  const [isLoading, setLoading] = useState(false);

Podrías también manejar el valor de cancelRequest mediante useState como lo haces con tus otras variables, o podrías usar una useRef para asignar y mantener su valor.
Espero te sirva!


text:
Q: Why does FragmentTransaction.hide() not hide my fragment? I'm making an Android app that uses the action bar tabs (I'm using the support library's action bar), each associated with a fragment that I generate dynamically.
The idea is to show the fragment whenever its tab is selected using FragmentTransaction.show() and hide the deselected tab with FragmentTransaction.hide(), but when I do this, the 'hidden' fragment simply becomes slightly greyed out.
The fact that the UI indicates that something is different by greying out the hidden tab might suggest that this is intentional behavior, but I was under the impression that hide() actually hid the tabs.
What am I doing wrong and what should I do? The code for the tab listener is below if necessary:
public class VarientTabListener implements ActionBar.TabListener
{
    VarientFragment Arch_Fragment;
    VarientFragment Plane_Fragment;
    ActionBarActivity parent;

    public VarientTabListener(ActionBarActivity act)
    {
        parent = act;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
    {
        //Work out which tab was selected
        if (tab.getText() == "Arch_Tab")
        {
            //Create the tab if it doesn't exist
            if (Arch_Fragment == null)
            {
                Arch_Fragment = (VarientFragment) Fragment.instantiate(parent, VarientFragment.class.getName());
                ft.add(android.R.id.content, Arch_Fragment, "Arch");
            }
            //Otherwise show it
            else
            {
                ft.show(Arch_Fragment);
            }
        }
        else if (tab.getText() == "Plane_Tab")
        {
            if (Plane_Fragment == null)
            {
                Plane_Fragment = (VarientFragment) Fragment.instantiate(parent, VarientFragment.class.getName());
                ft.add(android.R.id.content, Plane_Fragment, "Plane");
            }
            else
            {
                ft.show(Plane_Fragment);
            }
        }
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
    {
        if (tab.getText() == "Arch_Tab")
        {
            if (Arch_Fragment != null)
            {
                //Hide the unselected tab
                ft.hide(Arch_Fragment);
            }

        }
        else if (tab.getText() == "Plane_Tab")
        {
            if (Plane_Fragment != null)
            {
                ft.hide(Plane_Fragment);
            }
        }
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft)
    {

    }
}

A: you need to commit the fragment
ft.hide(Arch_Fragment);
ft.commit();

A: because you are comparing Strings in a wrong way. don't comapare Strings with == operator.
use equals() method to compare Strings...
if (tab.getText().equals("Arch_Tab")) {
    if (Arch_Fragment != null) {
        //Hide the unselected tab
         ft.hide(Arch_Fragment);
    }
 }

A: While I didn't manage to really solve this problem, a workaround is to simply get a new FragmentTransaction and commit that at the end, ignoring the transaction you get passed as an argument.
For example for the onTabUnselected method:
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft_unused)
{
    FragmentTransaction ft = parent.getSupportFragmentManager().beginTransaction();
    if (tab.getText() == "Arch_Tab")
    {
        if (Arch_Fragment != null)
        {
            //Hide the unselected tab
            ft.hide(Arch_Fragment);
        }

    }
    else if (tab.getText() == "Plane_Tab")
    {
        if (Plane_Fragment != null)
        {
            ft.hide(Plane_Fragment);
        }
    }
    ft.commit();
}


text:
Q: Testing file names on macOS for equality, especially on HFS+ and APFS Apple's new file system APFS brings along new rules for testing file name equality, and they're different from HFS. I am seeking the correct way to compare two names for equality, for APFS in particular, but for completeness it can't hurt to add one for HFS+ checks are well.
Why? Because I need to be able to tell if a file name I find in a directory matches a certain pattern, e.g. contains a certain sub string. For that, I need to match the exact rules the file system and Finder would use for comparing names.
For case-sensitive variants of these file systems it's pretty easy, as a byte-wise compare is sufficient, I believe (provided both strings are using the same encoding).
For case-insensitive HFS+, I thought there was even a special comparison option, but I cannot find such in the NSStringCompareOptions. I believe that was needed because HFS+ uses an older version of the Unicode standard. I quote from the TN1150 (which is, sadly, no longer available at Apple's website, it appears):

Unicode Subtleties
HFS Plus makes heavy use of Unicode strings to store file and folder names. However, Unicode is still evolving, and its use within a file system presents a number of challenges. This section describes some of the challenges, along with the solutions used by HFS Plus.
IMPORTANT:
  An implementation must not use the Unicode utilities implemented by its native platform (for decomposition and comparison), unless those algorithms are equivalent to the HFS Plus algorithms defined here, and are guaranteed to be so forever. This is rarely the case. Platform algorithms tend to evolve with the Unicode standard. The HFS Plus algorithms cannot evolve because such evolution would invalidate existing HFS Plus volumes.

Ah, and there's the part that I had in mind about getting the HFS+ version of the used encoding:

Note:
  The Mac OS Text Encoding Converter provides several constants that let you convert to and from the canonical, decomposed form stored on HFS Plus volumes. When using CreateTextEncoding to create a text encoding, you should set the TextEncodingBase to kTextEncodingUnicodeV2_0, set the TextEncodingVariant to kUnicodeCanonicalDecompVariant, and set the TextEncodingFormat to kUnicode16BitFormat. Using these values ensures that the Unicode will be in the same form as on an HFS Plus volume, even as the Unicode standard evolves.

So, what's the modern way to compare HFS+ and APFS names properly?

A: I compared both file systems by reading the raw data. In the HFS plus catalogfile and file properties, the filename Test.jpg is stored as 0x0054006500730074002E006A00700067
In Apple file system, we have 4kb blocks. Blocktype 0x0300 BlockID 0x07040000 00000000 is comparable with a catalogfile. Blocktype 0x0300 BlockID 0x11040000 00000000 is the apple finder info, complete with filesize, size on disk and a small endian pointer to the block where the file is.
The filename Test.jpg is stored as 0x546573742E6A7067. I have never used filenames with characters other than Ascii 0-127 on my iMac, and after trying it turned out to be possible to use extended ascii, unicode and smileys in filenames on APFS and HFS plus.
APFS is undocumented and all we know is learned from reverse engineering.
See Cugu's blog for other info on APFS


text:
Q: Highcharts colorsByPoint not working when used with linear gradient in a series I'm trying to set up three different gradient colors -- red, green, and yellow, and then assign those colors to individual data points in my series based on the value. However, when I render the chart, they all default to the whichever color I specify on the first data point in the first series.
Consider this jsFiddle: http://jsfiddle.net/2UVcD/2/
Try changing the first color in the chartData array to yellowColor or redColor, and you can see what I mean. I have colorbypoint set to true in the plotOptions -- am I missing something?

A: linearGradient have to be an array, not an object.
It should be like the following.
var perShapeGradient = [0, 0, 1, 0];
demo


text:
Q: Android Studio : MediaPlayer setDataSource URL not playing music Opening app without any error. But can't play music. But can play music from local machine. Internet connection is fine.
I have enabled internet permission in AndroidManiFest.xml
<uses-permission android:name="android.permission.INTERNET" />
I have enabled http permission.
android:usesCleartextTraffic="true"
MediaPlayer mediaPlayer = new MediaPlayer();
try {
        mediaPlayer.setDataSource("http://penguinradio.dominican.edu/Sound%20FX%20Collection/Motorbike.mp3");
    } catch (IOException e) {
        e.printStackTrace();
}

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mP) {
                Toast.makeText(MainActivity.this, "Ready to Play", Toast.LENGTH_SHORT).show();
                mP.start();
            }
        });
mediaPlayer.prepareAsync();

Full Code:
https://paste.ubuntu.com/p/dsjbg7YMNn/

A: I have tested your code and sometimes it works, sometimes it doesn't. If you search on Stack Overflow you will find plenty of similar problems.
You have 2 options:

*

*Migrate to ExoPlayer2 which is far superior that MediaPlayer.

*It doesn't work to play the sound in OnPreparedListener, but you can play it on button click, after it's prepared:

public class MainActivity extends AppCompatActivity {

    private Button streamButton;
    private boolean isPrepared = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource("http://penguinradio.dominican.edu/Sound%20FX%20Collection/Motorbike.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }

        mediaPlayer.setOnPreparedListener(mp -> {
            Toast.makeText(MainActivity.this, "Ready to Play", Toast.LENGTH_SHORT).show();
            isPrepared = true;
            streamButton.setVisibility(View.VISIBLE);
        });

        mediaPlayer.setOnCompletionListener(mp -> {
            mp.release();
            isPrepared = false;
            streamButton.setVisibility(View.INVISIBLE);
        });

        mediaPlayer.prepareAsync();

        streamButton = findViewById(R.id.streamButton);
        streamButton.setOnClickListener(v -> {
            if (isPrepared) {
                mediaPlayer.start();
            }
        });

    }
}

A: try this:
if(mediaPlayer != null ){

                    if (mediaPlayer.isPlaying()){mediaPlayer.stop();}

                    mediaPlayer.reset(); //this line is important!

                    String path = File.separator + "sdcard" + File.separator + utilsFields.repoDirRoot + File.separator + media.mp4;

                    try {
                        mediaPlayer.setDataSource(path);
                    }catch (Exception ignored){}

                    try {
                        mediaPlayer.prepare();
                    }catch (Exception ignored){}

                    mediaPlayer.start();

                }


text:
Q: Meaning of "knew from" in this sentence I'm trying to understand the usage of "knew from" in the following quote:

(suddenly cleaning ladies knew from sun-dried tomatoes, suddenly hog farmers knew from creme brulee)

Source: The Corrections
To me (not a native English speaker), this seems ungrammatical. I understand the meaning of phrases like "know a from b", but I'm unable to parse this in any way that makes sense. Does "knew from" has some special meaning here?

A: No, in this case "knew from" doesn't mean deduced. It is a colloquial usage. I've mostly heard it used in the negative, in which a person says they "don't know from" sun dried tomatoes or crème brulee or whatever. When someone says it like that, they're usually portraying themselves as a simple down-to-earth person confronted with some outlandish new-fangled absurdity. Literally it means you don't know about this that or the other thing.
As noted above, it derives from a Yiddish translation.
In your passage, the writer was saying something about unsophisticated folk suddenly having the means of being savvy about fancy-shmancy (another Yiddishism, I believe) high-dollar noshes (to complete the Yiddish trifecta).

A: Well I think grammatically the sentence seems correct, even though the style is a tad informal. I haven't seen this usage a lot in writing, but reading a couple of examples you've used, didn't strike me oddly. "Knew from" could easily be a synonym for deduce. So your example sentences could also be used as "suddenly cleaning ladies deduced from sun-dried tomatoes that..." Please let me know if you're looking for a different answer.


text:
Q: Can not Find module in "index.js" I'm stuck in this error...I'm trying but I can not fix it
This is my index.js file
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";

const app = express();
dotenv.config();
const connect = async () => {
    try {
      await mongoose.connect(process.env.MONGO);
      console.log("Connected to mongoDB.");
    } catch (error) {
      throw error;
    }
  };
  mongoose.connection.on("disconnected", () => {
    console.log("mongoDB disconnected!");
  });

  app.listen(3000, () => {
    connect();
    console.log("Connected to backend.");
  });

This is my pacakge.json file
{
  "name": "quiz-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.2",
    "express": "^4.18.1",
    "mongoose": "^6.5.4"
  },
  "devDependencies": {
    "webpack-cli": "^3.3.12"
  }
}

when I run this app it shows this error
enter image description here

A: You are using ES6 style importing import express from "express"; but your package.json doesn't know about that. Because the default is CommonJS for Node.js right now. And that means it wants you to use const express = require("express");
If you want to change that to ES6, you need to add "type": "module", in your package.json.
For example:
  ...
  "description": "",
  "type": "module",
  "main": "index.js",
  ...


text:
Q: Is this singleton instance member thread safe? I have this code:
public class Singleton
{
    private static Singleton m_instance;
    private Singleton()
    {

    }

    public static Singleton Instance
    {
        get
        {
            if (m_instance == null)
            {
                m_instance = new Singleton();
            }
            return m_instance;
        }
    }

    public void CallMe()
    {
       // is this function thread safe ?
    }
}

Is the CallMe method is thread safe, as every instance member function is thread safe? Or will anything generate an exception here? I saw one sample singleton code using locks, do I really need that?

A: You've got multiple issues here...
Firstly the Instance property is not necessarily thread safe.
if two threads simultaneously request the property then they could both feasibly find m_instance == nullto betrue` at the same time, return two different instances of Singleton but only one would end up being assigned for future calls.
You would need your implementation to be
private static lockObject lock = new Object();

public static Singleton Instance
{
    get
    {
      if (m_instance != null) return m_instance;
      lock (lockObject)
            {
                if(m_instance != null) return m_instance;
                return m_instance = new Singleton();
            }
    }
}

Alternatively simply instanciate m_instance in the static constructor.
Secondly even after the first issue is resolved you can't say CallMe() is thread safe, we have no idea what it is doing.

A: First of all, your Instance method is not thread-safe. If it's called twice at the same time, it will return two different instances (and therefore break the singleton pattern).
Without seeing its code, it is impossible to know whether CallMe is thread-safe or not.

A: That code without any synchronization, is not thread safe without any locking mechanism. The only thread-safe code is one that has a synchronization mechanism.

A: There are singletone variants with double locking or nested classes. But the easiest solution in .NET 4.0 and above is to use Lazy property:
public class Singleton
{
    private static Lazy<Singleton> m_instance = new Lazy = new Lazy<Singleton>();
    private Singleton()
    {

    }

    public static Singleton Instance
    {
        get
        {
            return m_instance.Value;
        }
    }

    public void CallMe()
    {
       // now its threadsafe
    }
}

The Lazy constructor takes optionally also creating function, or a LazyThreadSafetyMode enum
The Singleton.Instance is now thread safe but not CallMe() itself. It can be still called from differend threads and e.g. access the fields and properties of other classes. It doesn't matter whethere the method is in in the singleton instance or not. You should use other mechanisms to ensure thread safety here.

A: Expanding on Daniel's answer:
private readonly object _threadLock = new Object();

public void CallMe() {
   // whatever happens here is not thread-safe

   lock(_threadLock) {

      // this is the simplest form of a locking mechanism
      // code within the lock-block will be thread-safe
      // beware of race conditions ...

   }
}

Jon Skeet is an authority in .Net and focuses on C#. Here is a link to his analysis of thread-safe singleton instantiation: C# in Depth: Implementing Singleton ...

A: This is how I would make CallMe Thread Safe:
public class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton()
    {

    }

    public static Singleton Instance { get { return instance; } }

    public void CallMe()
    {
       // Thread Safe
    }
}

In other words - let the core framework manage the locking, mutex and volatile stuff for you.


text:
Q: Python: gethostbyname error I was coding a simple program in python that allows you to find the IP of the URL. I get this error:
File "wexec.py", line 40, in hell
  ipname = socket.gethostbyname('http://%s' % (hcon))
socket.gaierror: [Errno 11004] getaddrinfo failed

Now i'm not sure what I did wrong but here is my functions code:
def hell():

    hcon = raw_input(Fore.RED + Style.BRIGHT + "Website: ")
    h1 = httplib.HTTPConnection('http://%s:80' % (hcon))
    urlopen = urllib.urlopen('http://%s:80' % (hcon))
    ipname = socket.gethostbyname('http://%s' % (hcon))
    print(strftime("[%H:%M:%S]", gmtime()) + " Found IP: %d " % (ipname))
    enter = raw_input("Press enter or any other key to continue.")

hell()

As you can see. I open a HTTP connection to the website and then I open the URL with urllibb and then I get the IP of the website. But as you can see, I'm not sure what i'm doing wrong. Can someone help?

A: socket.gethostbyname() only takes the domain name, so you need to drop the 'http://' from that call. I don't understand what calls to httplib and urllib are doing, but they seem unnecessary from this snippet.


text:
Q: Laplacian and Fourier transform Show the laplacian is rotationally invariant:
$\Delta(f\circ R)=(\Delta f)\circ R, \forall R\in SO_d(\mathbb{R})$.
Suggestion:  You can use that the Fourier Transform (FT) of $f(Ax)$ is $det(A)^{-1}\hat{f}((A^{-1})^t\xi)$ (lineal composition) and that FT of $\Delta f(x)$ is $-4\pi^2|\xi|^2\hat{f}(\xi)$.
I'm completely lost. Pelase help

A: The Fourier transform of $f(Ax)$ is
$$
         \mathcal{F}\{f\circ A\}(\xi)=  \frac{1}{(2\pi)^{n/2}}\int_{\mathbb{R}^n} f(Ax)e^{-ix\cdot \xi}dx.
$$
Let $y=Ax$. Then $x=A^t y$ because $A^tA=AA^t=I$ by the definition of a symmetric orthogonal matrix. The Jacobian of this transformation is $|A^t|=1$, which gives
\begin{align}
    \mathcal{F}\{f\circ A\}(\xi) & = \frac{1}{(2\pi)^{n/2}}\int_{\mathbb{R}^n}f(y)e^{-i(A^t y)\cdot \xi}dy \\
    & = \frac{1}{(2\pi)^{n/2}}\int_{\mathbb{R}^n}f(y)e^{-iy\cdot(A\xi)}dy \\
    & = (\mathcal{F}\{ f\}\circ A)(\xi)\end{align}
In other words, $\mathcal{F}\{f\circ A\}=\mathcal{F}\{f\}\circ A$. Therefore,
\begin{align}
      -\Delta (f\circ A) &= \mathcal{F}^{-1}\{|\xi|^2\mathcal{F}\{f\circ A\}\} \\
   &= \mathcal{F}^{-1}\{ |A\xi|^2\mathcal{F}\{f\}\circ A\} \\
   &= \mathcal{F}^{-1}\{ |\xi|^2\mathcal{F}\{f\}\}\circ A \\
   &= (-\Delta f)\circ A.
\end{align}


text:
Q: Unable to report Facebook install event I'm trying to report install events to Facebook through Android, using the call to:
com.facebook.Settings.publishInstallAsync(<context>, <appId>);

In DDMS, I see the following request was sent:
02-23 21:02:30.205: D/FacebookSDK.Request(4871): Request:
02-23 21:02:30.205: D/FacebookSDK.Request(4871):   Id:  2
02-23 21:02:30.205: D/FacebookSDK.Request(4871):   URL: https://graph.facebook.com/<app id appears here>/activities?format=json&sdk=android&migration_bundle=fbsdk%3A20121026
02-23 21:02:30.205: D/FacebookSDK.Request(4871):   Method:  POST
02-23 21:02:30.205: D/FacebookSDK.Request(4871):   User-Agent:  FBAndroidSDK.3.0.1
02-23 21:02:30.205: D/FacebookSDK.Request(4871):   Content-Type:    multipart/form-data; boundary=3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f
02-23 21:02:30.205: D/FacebookSDK.Request(4871):   Parameters:
02-23 21:02:30.205: D/FacebookSDK.Request(4871):       format:  json
02-23 21:02:30.205: D/FacebookSDK.Request(4871):       sdk: android
02-23 21:02:30.205: D/FacebookSDK.Request(4871):       migration_bundle:    fbsdk:20121026
02-23 21:02:30.205: D/FacebookSDK.Request(4871):   Attachments:
02-23 21:02:30.205: D/FacebookSDK.Request(4871):       attribution: 9201d8b6-2c14-47e1-b326-0c397a9498d0
02-23 21:02:30.205: D/FacebookSDK.Request(4871):       event:   MOBILE_APP_INSTALL

And the following response is received:
02-23 21:02:31.265: D/FacebookSDK.Response(4871): Response (raw)
02-23 21:02:31.265: D/FacebookSDK.Response(4871):   Size: 4
02-23 21:02:31.265: D/FacebookSDK.Response(4871):   Response:
02-23 21:02:31.265: D/FacebookSDK.Response(4871): true
02-23 21:02:31.265: D/FacebookSDK.Response(4871): Response
02-23 21:02:31.265: D/FacebookSDK.Response(4871):   Id: 3
02-23 21:02:31.265: D/FacebookSDK.Response(4871):   Size: 4
02-23 21:02:31.265: D/FacebookSDK.Response(4871):   Responses:
02-23 21:02:31.265: D/FacebookSDK.Response(4871): [{Response:  responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"FACEBOOK_NON_JSON_RESULT":true}}, error: null, isFromCache:false}]

However, I see no mention of this activation in Facebook's dashboard in the AppEvents tab, or in the Mobile App Installs tab.
I'm using Facebook SDK 3.0.1, the Facebook App is installed and logged-in on the Android device that I'm testing.
Furthermore, I can see iOS activations just fine.
Any solution for this issue, which doesn't require me to upgrade the Facebook SDK to the latest version?

A: Just as a follow up, I can update that I had updated the Facebook SDK to version 3.7.0 and replaced 'publishInstallAsync' with the newer 'activateApp' method.
This has fixed the issue for me.


text:
Q: Работа с ComboBox в потоке Здравствуйте!
При попытке установить ValueMember для ComboBox в потоке получаю следующую ошибку:

Этот компонент BackgroundWorker занят и не может одновременно выполнять несколько задач.

Код таков:
this.Invoke((Action) delegate
{
    metroComboBox1.DataSource = st;
    metroComboBox1.ValueMember = "name";
    metroComboBox1.DisplayMember = "id";
});

Спасибо!


text:
Q: Crystal reports - How to put an "OR" condition between 2 fields when joining tables? Using Crytal Reports for VS2010, I am writing a new report.
I am trying to figuring out how I can do the following on the report. Please see my SQL that I want to use. Note the first condition in the JOIN which I need assistance with.
SELECT * -- <SOME FIELDS HERE>
FROM CUST_ORDER CUST_ORDER
    INNER JOIN "SALES_TX_HDR" "SALES_TX_HDR" ON
                (CUST_ORDER."cust_order_no"="SALES_TX_HDR".sale_tx_no OR  -- NOTE THIS  CONDITION
                        CUST_ORDER."cust_order_no"="SALES_TX_HDR".status_hdr_no)
            AND CUST_ORDER."branch_no"="SALES_TX_HDR"."status_branch_no"
            AND CUST_ORDER."workstation_no"="SALES_TX_HDR"."status_wrkst_no"

I can link the tables but it adds "AND" condition between them, instead of OR.
UPDATE
Let me explain the scenario:
When a new order is placed,

sale_tx_hdr.sale_tx_no = customerordernumber and
  sale_tx_hdr.status_hdr_no

is left empty.
When same order is amended, (some more payment made towards the order)

new sale_tx_hdr.sale_tx_no is created but sale_tx_hdr.status_hdr_no =
  original order no.

So when I use the OR condition, I get to see both the sale_tx_hdr entries, using any one condition will show me either the amend or new sale or none (if using both conditions with AND)
Thanks

A: As Lan already said, you cannot do this in the Database Expert and will need to add the SQL via a SQL Command manually as the data source for your report. You already have the query you want to use, so it should be easy:
When you're creating the report, instead of selecting different tables to add just select the top-most option under your connection called "Add Command" which will allow you to just paste that query in and be used instead. You won't have to worry about visually linking fields, etc. and you'll be able to do all the types of joins that your database supports but Crystal doesn't.

A: I have found a solution to this without using Sql Command.  I havent used command before.
Using an alias of the same table and then joining it on the 2nd field (OR condition) does the trick.
There's a bit of care to be taken when writing the formula though. @Ryan


text:
Q: How can I alias labels (using a query) in Grafana? I'm using Grafana v9.3.2.2 on Azure Grafana
I have a line chart with labels of an ID. I also have an SQL table in which the IDs are mapped to simple strings. I want to alias the IDs in the label to the strings from the SQL
I am trying to look for a transformation to do the conversion.
There is a transformation called "rename by regex", but that will require me to hardcode for each case. Is there something similar with which I don't have to hardcode for each case.
There is something similar for variables - https://grafana.com/blog/2019/07/17/ask-us-anything-how-to-alias-dashboard-variables-in-grafana-in-sql/. But I don't see anything for transformations.

A: Use 2 queries in the panel - one for data with IDs and seconds one for mapping ID to string. Then add transformation Outer join and use that field ID to join queries results into one result.
You may need to use also Organize fields transformation to rename, hide unwanted fields, so only right fields will be used in the label at the end.


text:
Q: Battlefield 3 ''Race''  in ME3 Multiplayer In the ME3 multiplayer lobby, I've seen some people list Battlefield 3 instead as their race. How do you obtain this? Is there any other perks other than the name change?

A: You have to log in to Origin with an account that has an activated Battlefield 3 Online Pass, and the pack is only for the PC and Xbox 360 versions of ME3. From the Mass Effect Wiki:

Battlefield 3 Pack (Free, single-use) - Unlock your Battlefield 3 Limited Edition soldier! A kit containing items with an aesthetic inspired by Battlefield 3. Requires that the player signs in to Mass Effect 3 with an Origin account linked to a Battlefield 3 Online Pass. (PC and Xbox 360 only)

The Battlefield 3 "race" is mostly a Human Soldier with the power Carnage instead of Concussive Shot. Full list of Powers at the Wiki, aside from the obvious cosmetic differences.

A: I believe they must have changed or lifted those exclusives, because I have never played any Battlefield and I use a PS3, and I unlocked the Battlefield 3 soldier with a veteran pack yesterday.  I don't see what the big deal is -- it's kind of a mediocre class.


text:
Q: Access to variadic function' arguments without va_list in C Is it possible to iterate through variadic function' arguments using pointer (void pointer?) to last named argument?
(I know that's not the right way to work with variadic arguments, but I'm still interested if that would work)
Setting pointer to the end of the string doesn't work, because after I start moving the pointer, it points to other strings used in the program.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void form_date(MON* datePtr, int dayMonth, int dayYear, int month);
MON* evaluate_date(MON* datePtr, int count, int dayArg);
void what_month(char *format, ...);
void output(MON* datePtr, int count);

int main(void)
{
what_month("ii", 126, 125);
return 0;
}

void what_month(char *format, ...){

    char* arg_ptr = format+2;
    int* arg_int_ptr;
    double* arg_double_ptr;

    MON dateArr[MAX_DATE];
    int count = 0;
    int dayYear;
    char *ptrFormat = format;

    for(; *ptrFormat != '\0'; ptrFormat++){
        if(*ptrFormat == 'i'){
            arg_int_ptr = (int*) arg_ptr;
            dayYear = *arg_int_ptr;
            arg_int_ptr++;
        }

        if(*ptrFormat == 'd'){
            arg_double_ptr = (double*) arg_ptr;
            dayYear = *arg_double_ptr;
            arg_int_ptr++;
        }
        evaluate_date(dateArr, count, dayYear);
            count++;
     }
    output(dateArr, count);
}

void form_date(MON* datePtr, int dayYear, int dayMonth, int month){
    char month_names[][15] = {"January", "February", "March", "April", "May", "June",
                              "July", "August", "September", "October", "November",
                              "December", "INVALID_MONTH"};

    datePtr->day_of_year = dayYear;
    datePtr->day_of_month = dayMonth;

    if(month == -1){
        strcpy(datePtr->month, month_names[12]);
    }
    else {
        strcpy(datePtr->month, month_names[month]);
    }
}

MON* evaluate_date(MON* dateArr, int count, int dayArg){
    int months_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int j;
    int dayMonth;
    int sumDays = 0;

        if (dayArg > 365 || dayArg < 1){
            form_date(dateArr + count, dayArg, -1,  -1);
            count++;
        }

        else {
            for(j = 0; j < 12; j++){
                sumDays += months_days[j];
                if (dayArg <= sumDays)
                    break;
            }
            dayMonth = months_days[j] - (sumDays - dayArg);
            sumDays = 0;
            if (dayMonth == 0){
                dayMonth++;
            }

            form_date(dateArr + count, dayArg, dayMonth, j);
        }
        return dateArr;
}

void output(MON* dateArr, int count){
    int i, j;

    for(i = 0; i < 80; i++)
        printf("_");

    printf("\n");
    for(i = 0; i < 80; i++)
        printf("_");

    for(j = 0; j < count; j++){
        if (j % 100 == 0 && j != 0){
            puts("Press any key to continue");
            getchar();
        }

        printf("\n%-7d  :::  %7d, %-8s %5s\n", dateArr[j].day_of_year, dateArr[j].day_of_month,
               dateArr[j].month, "|");
    }
    for(i = 0; i < 80; i++)
        printf("_");
}

A: No, you cannot do that portably. To use variable function arguments you must use the facilities provided in <stdarg.h>.
You can, however, look at your platform's code generation and/or machine code output and get an understanding of the machine layout of the variable arguments, and perhaps use that for your own, platform-specific purposes.

A: First - strings are not passed via value in C/C++ unless encapsulated in some struct/class so on the stack you'll find a pointer to a string not a string itself.
You should not handle variable argument list manually using pointers as that is not portable in first place.
Why not portable ? Here are some problems:

*

*do not assume your code will be executed on x86 where stack pointer when push is executed behaves like *--sp = value

*not all stacks (not on all archs) grow down and before storing value - ARM processor let's you implement stack push as *--sp = val, *++sp = val, --*sp = val, ++*sp = val (it is up to you)

*what is 32bit int on one architecture might be 16bit int on other (or 64)

*even with the same compiler - if you compile to 64bit instruction set you get different calling convension that spoils your code

Moreover in standard calling convention for C/C++ your last argument is pushed on stack first so you cannot use it for variadic functions (as you cannot immediately locate it fromyour func). cdecl calling convension pushes arguments on stack in reversed order ie.:
func(a,b)

is
push b
push a
call func

This reversed convention is only for the purpose of allowing variadic functions to work since your first argument a (which is always needed in varargs) can always be easily accessed from stack as it's location is known (because pushed last). To get other arguments (or to understand how many they are, or their types) you usually must parse first argument - just like in printf.
Hope this sheds some ligh on that.
Some additional info that may help:

*

*assembler internals of calling a function

*x86 calling conventions

*x64 calling conventions


text:
Q: Can't install pandas-dedupe on Windows Python 3.9 Running pip install pandas-dedupe, I get the following error:

I tried manually installing python-Levenshtein first and got the same problem with the addition . What can I do?

A: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/.
In the installation guide, choose "Desktop development with C++".


text:
Q: How do I align my label and input element contents on separate lines while maintaining centered alignments? I am trying to align my form contents so that each label falls on a separate line and the input content within the label falls in separate lines after the label element. Please help. I included an image link and my code in this question.
I would like my label to be displayed above the input elements, the input elements to have centered content (for example: radio type inputs to be aligned perfectly centered with their relative text description. If I have "male" as an option for a radio, I would like the input button itself to be aligned centered and even with the words "male").

html,
body {
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
  display: block;
}

div {
  display: block;
}

.form-group {
  margin: 0 auto;
}

.container {
  max-width: 600px;
  margin: auto;
}

form {
  height: 100%;
  width: 100%;
  display: block;
}

label {
  padding: 0.25rem;
  display: flex;
  width: 100%;
}

input[type="radio"],
label {
  align-items: center;
}

input {
  width: 100%;
  display: block;
}

Studentas Survey Form

Thank you for taking time to complete this survey

    <form id="survey-form">

        Enter your name
        <input type="text" id="name" placeholder="Enter your name" required></input>

        Enter your Email
        <input type="email" id="email" placeholder="Enter your email" required></input>

        Enter your age
        <input type="number" id="number" min="1" max="99" placeholder="Age" required></input>

        Favorite subject?
          <select id="dropdown">
            <option value="">Select an option</option>
            <option value="1">History</option>
            <option value="2">Math</option>
            <option value="3">Science</option>
            <option value="4">English</option>
          </select>

        What is your gender?
          <input type="radio" name="gender" required>Male
        <input type="radio" name="gender" required>Female

        What do you like about school?
          <input type="checkbox" value="lunch" required>Lunch Time</input>
          <input type="checkbox" value="social" required>Social Interaction</input>
          <input type="checkbox" value="work" required>Course Work</input>
          <input type="checkbox" value="home" required>Going Home</input>

        What are your thoughts on this survey?
          <textarea></textarea>

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

    </form>

A: Check this out!
.Your-choosen-label
{
    display:flex;
    justify-content:space-evenly;
    align-items:center;
    flex-direction:column;
}


text:
Q: corrupt image file generated from win32com.client client to export images from xlsx file. But when I open the image file, it is not opening and say: "format is unsupported or file is corrupted":
code is here:
from win32com.client import Dispatch
import win32com.client as win32

app = Dispatch("Excel.Application")
workbook_file_name = 'excel_file.xlsx'
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(Filename=r"path\\to\\excel_file.xlsx")
app.DisplayAlerts = False

for sheet in workbook.Worksheets:
    for chartObject in sheet.ChartObjects():
        print("Obj: ", chartObject.Chart)
        chartObject.Chart.Export(r"C\\path\\to\\xyz.png")

workbook.Close(SaveChanges=False, Filename="absolute\\path\\to\\excel_file.xlsx")


text:
Q: PHP adding time I have a code where I have 2 texboxes and a button where it adds the time value of those textboxes according to input.
Here is my simple code:
<?php

echo "<form method=post><input type=text name=etd>";
echo "<input type=text name=btime>";
echo "<input type=submit name=sub value=submit></form>";
if(isset($_POST['sub']))
{

        $etime = $_POST['etd'];
        $btym = $_POST['btime'];
        $time = strtotime("$etime");
        $tym = strtotime("btym");
        $etym = strtotime("+$btym hours", $time);
        $eta = date('H:i:s', $etym);

echo "$eta";
}
?>

This works however, when I input 12:00 and 00:30 (meaning I want to add 30 minutes to 12:00), it outputs 11:30 which is supposed to be 12:30. What am I doing wrong? Thanks in advance.

A: Shouldn't this:
$tym = strtotime("btym");

Be this:
$tym = strtotime("$btym");

?

A: This should work. Although, if you want to use 30 minutes, your value for btime should be 0.5, not 0:30 (since the reference in your strtotime() call is to hours).
As the commenter suggested, all your attributes should be wrapped in quotations.
<?php

echo '<form method=post><input type="text" name="etd">';
echo '<input type="text" name="btime">';
echo '<input type="submit" name="sub" value="submit"></form>';
if(isset($_POST['sub']))
{
    $eta = date('H:i:s', strtotime( $_POST['etd'] . ' +' . $_POST['btime'] . ' hours' ) );
    echo "$eta";
}
?>

A: Thank you for all your replies! :))) This is my first post and I feel so glad that you guys answered! :))) Got it working by using mysql addtime() and timediff() function. It worked easily without me banging my head on the table. Thanks anyway for the replies! I'll be on your hands from now on since I think I'll be posting a lot of questions. ^_^


text:
Q: Different plugins activated online and offline I develop / add to / etc. my site offline, then transfer the updated database (in toto) to the live site. Some of the plugins I need / use offline, I don't need online, and vice versa.
Is there a way to have one set of plugins active if the database is 'online' and a different set for 'offline'? Or do I just need to accept that whenever I upload a new version of the database I need to activate / deactivate as appropriate?


text:
Q: PHP Countdown like Amazon Delivery I have been wondering this for a while and has searched for an answer over the internet but still no luck.
My question is: How do I create a timer be it in Javascript or PHP like the one amazon uses to tell you how long you have left to order for a specified delivery time.
Example:
I am talking about the text that displays:
Want delivery by Monday, 13 May? Order it in the next 18 hours and 29 minutes.
I hope I have made some sense. If anyone could help me or point me in the right direction that would be great!

A: hope this points you in the right direction:
http://php.net/manual/en/function.date.php
PHP Calculating future date by adding days to a variable date
Javascript Countdown


text:
Q: Nginx. Wild card Alias location. Is it possible? Using the http://wiki.nginx.org/NginxHttpCoreModule#alias example regarding how to use sub directory aliases, I've noticed it does not mention how to do it dynamically.
In the following example...
location ~ ^/download/(.*)$ {
  alias /home/website/files/$1;
}

...the request "/download/book.pdf" will return the file "/home/website/files/book.pdf". Note again that only part of the request URI after the location is appended to the path defined by alias.
If I'm creating a folder labeled the username that the user created once signing up, then this folder name would always be unique and different. How do I alter the regex in the example above so that the word download also becomes a wild card sub directory?
location ~ ^/randomusername/(.*)$ {
  alias /home/website/profiles/randomusername/$1;
}

A: You need a little background about regex.
Please try the code below and see if it helps.
location ~ ^/([^/]+)/([^/?]+)$ {
  alias /home/website/profiles/$1/$2;
}

A: Well, after learning NGINX here is the answer I was looking for 9 years ago.
location / {

  # example rewrite rules for www.example1.com

  rewrite ^/get/users/?$ /getData.php?usersFilter=all                             last;
  rewrite ^/get/users/(\d+)/?$ /getData.php?userId=$1                             last;
  rewrite ^/get/users/(\d+)/comments/?$ /getData.php?userId=$1&commentsFilter=all last;

}

@Kristi Jorjii: Below, we use the /[^/]*$/ regex to match the part of the URL after the last slash.
rewrite ^/sitemap/[^/]*$ /var/www/html/sitemap/$1 last;


text:
Q: How do I properly apply padding to a group box control? I have a class that inherits a panel which I am adding a group box to. This group box contains for now a couple text boxes. I would like to have the text boxes centered horizontally and vertically within the group box by using the AutoSize property of the group box and the Padding property of the group box. Here is my attempt:
Imports System.Drawing

Public Class pnlItemMstr_A_OSI
    Inherits Panel

    Public Sub New(ByRef ItemMstr_DS As DataSet, ByVal padding As Integer)
        MyBase.New()

        Dim drItemMstr As DataRow = ItemMstr_DS.Tables(0)(0)
        Dim txtHeight As Integer = 26

        ' article numbers
        Dim grpArtNum As New GroupBox
        Dim txtARTC_NUM_DOM_C As New TextBox
        Dim txtARTC_NUM_CAN_C As New TextBox

        With txtARTC_NUM_DOM_C
            .Text = drItemMstr("ARTC_NUM_DOM_C").ToString
            .Size = New Size(200, txtHeight)
            .Location = New Point(0, 0)
        End With

        With txtARTC_NUM_CAN_C
            .Text = drItemMstr("ARTC_NUM_CAN_C").ToString
            .Size = New Size(200, txtHeight)
            .Location = New Point(0, txtHeight)
        End With

        With grpArtNum
            grpArtNum.Text = "Article Number"
            grpArtNum.Padding = New Padding(padding)
            grpArtNum.Controls.Add(txtARTC_NUM_DOM_C)
            grpArtNum.Controls.Add(txtARTC_NUM_CAN_C)
        End With

        Me.Controls.Add(grpArtNum)

    End Sub

End Class

What I am ending up with is ugly and not what I would expect to happen, notice how the group box text is cut off:

It seems the padding is not being applied properly, but I am sure I am just doing something wrong.

A: The Padding property is used primarily for Dock Styled child controls, so try adding a dock filled panel into your GroupBox to contain those TextBoxes:
With grpArtNum
  grpArtNum.Text = "Article Number"
  grpArtNum.Padding = New Padding(padding)
  Dim innerPanel As New Panel With {.Dock = DockStyle.Fill}
  innerPanel.Controls.Add(txtARTC_NUM_DOM_C)
  innerPanel.Controls.Add(txtARTC_NUM_CAN_C)
  grpArtNum.Controls.Add(innerPanel)
End With


text:
Q: Solving an equation with exponentials $$2^x+4^x+12=0$$
How exactly am I supposed to solve this? Am I supposed to get $x$ alone or solve it another way?

A: let $u = 2^x$, then $4^x = (2^2)^x = 2^{2x} = 2^{2x} = (2^x)^2 = u^2$. Thus, $2^x + 4^x + 12 = 0$ becomes,
$$u + u^2 + 12 = 0$$
Using the quadratic equation will solve $u$, which is really $2^x$. To solve for the $x$, just take $\log$ on both sides of the solution, then after rearranging, you should be able to solve for $x$.

A: For any $x \in \mathbb{R}$, $2^x > 0$ and $4^x > 0$, therefore
$$ 2^x + 4^x + 12 > 0 + 0 + 12 = 12 > 0 $$
Therefore there is no real solution.


text:
Q: Model derivative translate job giving status code 409 (CONFLICT) How to fix status code 409 for translate job.
There are two types of problems I am facing.
 1. Sometimes API returns error status code 409(conflict)
 2. Sometimes it continuously gives in progress status and never completes or fails even.
Once any of the above error occurs, any subsequent job requests starts failing with error code 409.
We are trying node js API for translating job using following code.
let translateResult = derivativesAPI.translate(job, { 'xAdsForce': true }, forgeSvc.requestOAuth2TwoLeggedOBJ(), accessToken);

A: First try to delete manifest for the stuck/pending request file,
If that doesn't works , last option is to delete the bucket with pending/stuck translation request and then try again.

A: As per documentation, the 409 means:

The request conflicts with a previous request that is still in progress

As you mentioned a previous request failed, but is pending on our system and causes this conflict. Is that happening consistently with a file? Or random? When it fails (or hangs), what's the manifest? Finally, can you share a problematic URN?
EDIT: the file is working now and we'll keep investigating this.


text:
Q: Can /etc/passwd change because of a reboot? A Zabbix server I am currently started showing an alert like this:
/etc/passwd has been changed on Router

Now, on this Router machine I don't have a history of the passwd file so I cannot see exactly what changed, but what I know is that the time of the alert roughly coincided with this Router machine being rebooted. As soon as the router came back up, Zabbix started throwing this alert.
Running ls -l /etc/passwd on the Router device shows that the last modified timestamp is roughly the same as the time of the reboot.
This could be pure coincidence, but I'd rather double check here since I could not find anything online: can a simple device reboot cause the /etc/passwd file to be updated (if not in the contents, at least in the timestamp)?

A: I can think of one instance this could happen....
Lets say someone edited the /etc/passwd file a while ago and they put some lines in there for a user, and that user was not added to the corresponding /etc/shadow, after a reboot the user would be removed from the /etc/passwd file. Under this circumstance yes a reboot could change the file.
That's the only circumstance I can think of. I am unsure if, or under what other circumstances a reboot would change the /etc/passwd file

A: this can happen:

*

*after manual tinkering (as described above)

*after an automated package update (eg: debian unattended-upgrades) where a package/service is updated or included as a dependency that adds a user specific for that package/service. This happened recently with the package snmpd that now uses the user 'debian-snmp'. it triggered a zabbix alert.


text:
Q: Javascript : how to get the name of the instance? I create a class called foo :
foo = function()
{
...
}

Then I create an object called pear from the foo class :
pear = new foo();

Then I put the pear object in array :
array_obj = [pear];

So when I parse the array_obj by a "for loop", I want to get the name of the instance, that is say "pear" string :
for(var i = 0; i < array_obj.length; i++)
{
    console.log(array_obj[i].name);
}

But it doesn't work because array_obj[i].name doesn't return "pear" name.
Have you an idea ? Thank you in advance, cordially.

A: Change your function:
foo = function(name)
{
   this.name = name;
}

And your call:
var pear = new foo("pear");

A: You can't do this.  1 - it doesn't work, and 2 - it's a "layer violation" for an object to know anything about the names of the variables that reference it.
Also, variable names are a convenience for the programmer.  They can change through programmer choice, or even be changed automatically by things like minifiers or obfuscators.
If the name really matters therefore, it either needs to become a property of the object itself (passed in the constructor, per @Paulo's answer), or you need to maintain a "hash" (aka "map") that maps "human readable names" to the individual objects:
var map_obj = { pear: new foo() };

You can then iterate over the keys of that map (  Object.keys(map_obj) ) to find each object by name.  However in this case each name must be unique - a map can't contain duplicate keys.

A: You can't because
array_obj[i].name == pear.name == (new foo()).name

And it depends on what you return from foo() function. I suspect it will return undefined because you not define such property in foo()
You can use @Paulo solution


text:
Q: flutter setState does not add a widget This is my code. It is supposed to add a list tile when you enter a city in the field above and then press plus button. But it does not! There's a listView which has all the list tiles in it.The listView is supposed to show all list tiles in a list.
When I press the button a message is printed to indicate the number of cities. It shows that the city is added but nothing changes in the screen.
ColorfulBox is a widget that I've built. It's just a decoration.
import 'package:flutter/material.dart';
import 'package:learner/logic/Weather.dart';
import 'ColorfulBox.dart';

class CitiesScreen extends StatefulWidget{
  @override
  _CitiesScreenState createState() => _CitiesScreenState();
}
class _CitiesScreenState extends State<CitiesScreen>{
  List<Weather> weatherData = List<Weather>();
  String cityName;
  List<Widget> cities = List<Widget>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
        child: Column(
          children: <Widget>[
            DecoratedBox(
              decoration: BoxDecoration(color: Colors.blueAccent, borderRadius: BorderRadius.circular(10),
              gradient: LinearGradient(colors: [Colors.blue, Colors.purple]) ),
              child: ColorfulBox(Padding(
                padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 0),
                child: ListTile(
                  title: TextField(onChanged: (value){
                    cityName = value;
                  },
                  style: TextStyle(fontSize: 20, color: Colors.white),),
                  trailing: FlatButton(
                    child: Icon(Icons.add, size: 30, color: Colors.white,),
                    onPressed: (){
                      setState(() {
                        addCity(cityName);
                        print(cities.length);
                      });
                    },
                  ),
                ),
              ),
              )
            ),
            SizedBox(height: 30,),
            Expanded(
              child: ListView(
                shrinkWrap: true,
                scrollDirection: Axis.vertical,
                children: cities,
              ),
            )
          ],
        ),
      ),
    );
  }

  void addCity(String city){
    weatherData.add(Weather(city: city));
    Container toBeAddedCity = Container(
      margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
      child:  Text(city, style: TextStyle(fontSize: 22, color: Colors.white),),
    );
    cities.add(ColorfulBox(toBeAddedCity));
  }

}

Can you help me fix this? I have no idea!
Is it because the addCity method is out of the build method? or it adds but does not show it?

A: You can just use ListView.builder(...) to create your widgets. Please do not store Widgets as states.
Sample:
class CitiesScreen extends StatefulWidget {
  @override
  _CitiesScreenState createState() => _CitiesScreenState();
}

class _CitiesScreenState extends State<CitiesScreen> {
  final TextEditingController _controller = TextEditingController();
  final List<Weather> _weatherData = <Weather>[];
  final Random _rand = Random();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
        child: Column(
          children: <Widget>[
            DecoratedBox(
              decoration: const BoxDecoration(
                color: Colors.blueAccent,
                borderRadius: BorderRadius.all(Radius.circular(10)),
                gradient: LinearGradient(
                  colors: <Color>[Colors.blue, Colors.purple],
                ),
              ),
              child: Container(
                //ColorfulBox(
                color: Colors.blue,
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  child: ListTile(
                    title: TextField(
                      controller: _controller,
                      style: const TextStyle(fontSize: 20, color: Colors.white),
                    ),
                    trailing: FlatButton(
                      child: const Icon(
                        Icons.add,
                        size: 30,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        setState(() {
                          _weatherData.add(Weather(city: _controller.text));
                        });
                        _controller.clear();
                      },
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(height: 30),
            Expanded(
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: _weatherData.length,
                itemBuilder: (_, int index) => ListTile(
                  tileColor: Color.fromARGB(
                    255,
                    _rand.nextInt(255),
                    _rand.nextInt(255),
                    _rand.nextInt(255),
                  ),
                  title: Text(
                    _weatherData[index].city,
                    style: const TextStyle(
                      fontSize: 22,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

A: First of all, a convenient way to get the value of a TextField is to use a TextEditingController, instead of using variable:
// Create a controller
final TextEditingController _textController = TextEditingController();

// Then use it in your TextField
TextField(
   controller: _textController,

   // ... other lines

   trailing: FlatButton(
   onPressed: () {

     // Use the TextController's value
     setState(() {
       addCity(_textController.text);
     });

     // Clear the text after using it
     _textController.clear();
     },
   ),
),

Because you only update the content of the cities array, but keep the same cities array as the ListView's child, Flutter assumes that the state doesn't change and hence not updating the UI. There are 2 ways to solve this:

*

*Mutate the whole list (not recommended for large number of items):

// Set new value to the list, instead of just adding items in
cities = List.from(cities)..add(ColorfulBox(toBeAddedCity));

*Use ListView.builder() that keep track of the length of your List (which will be modified when adding/ removing an items) (recommended)

ListView.builder(
   itemCount: cities.length,
   itemBuilder: (context, index) => cities[index]
   // ... other lines

Working code:

import 'package:flutter/material.dart';
import 'package:learner/logic/Weather.dart';
import 'ColorfulBox.dart';

class CitiesScreen extends StatefulWidget {
  @override
  _CitiesScreenState createState() => _CitiesScreenState();
}

class _CitiesScreenState extends State<CitiesScreen> {
  final TextEditingController _textEditingController = TextEditingController();
  List<Weather> weatherData = List<Weather>();
  String cityName;
  List<Widget> cities = List<Widget>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
        child: Column(
          children: <Widget>[
            DecoratedBox(
                decoration: BoxDecoration(color: Colors.blueAccent,
                    borderRadius: BorderRadius.circular(10),
                    gradient: LinearGradient(
                        colors: [Colors.blue, Colors.purple])),
                child: ColorfulBox(Padding(
                  padding: const EdgeInsets.symmetric(
                      vertical: 10, horizontal: 0),
                  child: ListTile(
                    title: TextField(
                      controller: _textEditingController,
                      style: TextStyle(fontSize: 20, color: Colors.white),),
                    trailing: FlatButton(
                      child: Icon(Icons.add, size: 30, color: Colors.white,),
                      onPressed: () {
                        setState(() {
                          addCity(_textController.text);
                          _textController.clear();
                          print(cities.length);
                        });
                      },
                    ),
                  ),
                ),
                )
            ),
            SizedBox(height: 30,),
            Expanded(
              child: ListView.builder(
                shrinkWrap: true,
                scrollDirection: Axis.vertical,
                itemCount: cities.length,
                itemBuilder: (context, index) => cities[index],
              ),
            )
          ],
        ),
      ),
    );
  }

  void addCity(String city) {
    weatherData.add(Weather(city: city));
    Container toBeAddedCity = Container(
      margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
      child: Text(city, style: TextStyle(fontSize: 22, color: Colors.white),),
    );
    cities.add(ColorfulBox(toBeAddedCity));
  }
}


text:
Q: ways for Direct2D and Direct3D Interoperability I want make a Direct2D GUI that will run on a DLL and will render with the Direct3D of the application that I inject into it.
I know that I can simply use ID2D1Factory::CreateDxgiSurfaceRenderTarget to make a DXGI surface and use it as d2d render target, but this require enabling the flag D3D11_CREATE_DEVICE_BGRA_SUPPORT on Direct3D's device.
The problem is that the application creates its device without enabling this flag and, for this reason, ID2D1Factory::CreateDxgiSurfaceRenderTarget fails.
I am trying to find a other way to draw on the application window (externally or inside window's render target) that also works if that window is in full-screen.
I tried these alternatives so far:

*

*Create a d2d render target with ID2D1Factory::CreateDCRenderTarget. This worked, but the part I rendered was blinking/flashing (show and hide very fast in loop). I also called ID2D1DCRenderTarget::BindDC before ID2D1RenderTarget::BeginDraw, but it just blinks but a bit less, so I still had the same issue.

*Create a new window that will always be on the top of every other window and render there with d2d but, if the application goes into full-screen, then this window does not show on screen.

*Create a second D3D device with enabled the D3D11_CREATE_DEVICE_BGRA_SUPPORT flag and share an ID3D11Texture2D resource between the device of the window and my own, but I wasn't able to make it work... There are not a lot of examples on how to do it. The idea was to create a 2nd device, draw with d2d on that device and then sync the 2 D3D devices – I followed this example (with direct11).

*Create a D2D device and share the data of d2d device with d3d device; but, when I call ID2D1Factory1::CreateDevice to create the device it fails because the D3D device is created without enabling the D3D11_CREATE_DEVICE_BGRA_SUPPORT flag. I started with this example.
I've heard of hardware overlay but it works only on some graphics cards and I think I will have problems with this https://learn.microsoft.com/el-gr/windows/win32/medfound/hardware-overlay-support.
I am currently at a dead end; I don't know what to do. Does anyone have any idea that may help me?
Maybe is there any way to draw on screen and work even if a window is in full-screen?

A: The #3 is the correct one. Here's a few tips.
Don't use keyed mutexes. Don't use NT handles. The only flag you need is D3D11_RESOURCE_MISC_SHARED.
To properly synchronize access to the shared texture across devices, use queries. Specifically, you need a query of type D3D11_QUERY_EVENT. The workflow should look like following.

*

*Create a shared texture on one device, open in another one. Doesn't matter where it's created and where imported. Don't forget the D3D11_BIND_RENDER_TARGET flag. Also create a query.

*Create D2D device with CreateDxgiSurfaceRenderTarget of the shared texture, render your overlay into the shared texture with D2D and/or DirectWrite.

*On the immediate D3D device context with the BGRA flag which you use for D2D rendering, call ID3D11DeviceContext.End once, passing the query. Then wait for the ID3D11DeviceContext.GetData to return S_OK. If you care about electricity/thermals use Sleep(1), or if you prioritize latency, busy wait with _mm_pause() instructions.

*Once ID3D11DeviceContext.GetData returned S_OK for that query, the GPU has finished rendering your 2D scene. You can now use that texture on another device to compose into 3D scene.
The way to compose your 2D content into the render target depends on how do you want to draw your 2D content.
If that's a small opaque quad, you can probably CopySubresourceRegion into the render target texture.
Or, if your 2D content has transparent background, you need a vertex+pixel shaders to render a quad (4 vertices) textured with your shared texture. BTW you don't necessarily need a vertex/index buffer for that, there's a well-known trick to do without one. Don't forget about blend state (you probably want alpha blending), depth/stencil state (you probably want to disable depth test when rendering that quad), also the D3D11_BIND_SHADER_RESOURCE flag for the shared texture.
P.S. There's another way. Make sure your code runs in that process before the process created their Direct3D device. Then use something like minhook to intercept the call to D3D11.dll::D3D11CreateDeviceAndSwapChain, in the intercepted function set that BGRA bit you need then call the original function. Slightly less reliable because there're multiple ways to create a D3D device, but easier to implement, will work faster, and use less memory.


text:
Q: VB.Net - Inserting data to Access Database using OleDb Can you please tell me what's wrong with the code I'm using? Everytime I execute this, it throws the exception (Failed to connect to database)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim conn As New System.Data.OleDb.OleDbConnection()

conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb"

Dim sql As String = String.Format("INSERT INTO login     VALUES('{username}','{password}','{secques}','{secans}')", txt_username.Text, txt_passwd.Text, txt_secquestion.Text, txt_secansw.Text)

            Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)

            'Open Database Connection
            sqlCom.Connection = conn
            conn.Open()
            Dim icount As Integer = sqlCom.ExecuteNonQuery
            MessageBox.Show(icount)
            MessageBox.Show("Successfully registered..", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error)

        Catch ex As Exception
            MessageBox.Show("Failed to connect to Database..", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        cmd_submit2_Click(sender, e)

    End If
End Sub

I am using Access 2013 and VS 2015 Community, if that helps. Thank you.

A: You should use a parameterized approach to your commands.
A parameterized query removes the possibility of Sql Injection and you will not get errors if your string values are not correctly formatted.
Note that if you don't do anything in the exception block then it is better to remove it and let the exception show itself or at least show the Exception.Message value, so you are informed of the actual error.
Finally every disposable object should be created with the Using statement that ensures a proper close and dispose of such objects (in particular the OleDbConnection)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim sql As String = "INSERT INTO login VALUES(@name, @pass, @sec, @sw)"
    Using conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb")
    Using sqlCom = New System.Data.OleDb.OleDbCommand(sql, conn)
         conn.Open()
         sqlCom.Parameters.Add("@name", OleDbType.VarWChar).Value = txt_username.Text
         sqlCom.Parameters.Add("@pass", OleDbType.VarWChar).Value = txt_passwd.Text
         sqlCom.Parameters.Add("@sec", OleDbType.VarWChar).Value = txt_secquestion.Text
         sqlCom.Parameters.Add("@sw", OleDbType.VarWChar).Value =  txt_secansw.Text
         Dim icount As Integer = sqlCom.ExecuteNonQuery
    End Using
    End Using
End Sub

Keep in mind that omitting the field names in the INSERT INTO statement requires that you provide values for every field present in the login table and in the exact order expected by the table (So it is better to insert the field names)
For example, if your table has only the 4 known fields:
Dim sql As String = "INSERT INTO login (username, userpass, secfield, secfieldsw) " & _
                    "VALUES(@name, @pass, @sec, @sw)"