text:
Q: Downloading multiple files one by one using AsyncTask? I'm trying to download multiple files one by one (file is downloaded, we start downloading the next file). Using this method I can keep track of the files being downloaded. The problem is that I'm using the following code for executing a Task:
                File file = null;
                for(int i=0; i< videos.length; i++) {
                     file = new File(root.getPath() + videos[i]);
                     boolean exists = file.exists();
                     if(exists){
                         //tv.append("\n\n"+fileNames[i]+" already exists");
                         continue;
                     }
                     else {
                         currentFile = videos[i];
                         new DownloadFileAsync().execute(videoURL+videos[i],videos[i]);

                     }
                     file = null;
                }

As you can see, I call new DownloadFileAsync().execute(videoURL+videos[i],videos[i]); in a loop which obviously start a task for each of the files and downloads them simultaneously.
My question is: How can I run execute the task for a specific file, check if it has been downloaded-  if yes, proceed with next file by executing a task for it?

A: package com.example.androidhive;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidDownloadFileByProgressBarActivity extends Activity {

    // button to show progress dialog
    Button btnShowProgress;

    // Progress Dialog
    private ProgressDialog pDialog;
    ImageView my_image;
    // Progress dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;

    // File url to download
    String[] ur = {
            "http://www.funrocker.com/blog/wp-content/uploads/2010/04/Animals-Wild-Life-Jungle-FunRocker.Com-03.jpg",
            "http://2.bp.blogspot.com/-j56yaqpfjVE/TnzTjcqnCjI/AAAAAAAAGPM/MzqmczFkC30/s1600/natural-pictures.jpg",
            "http://www.fantasy-and-art.com/wp-content/gallery/nature-wallpapers/red-tree-wallpaper-hd.jpg" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // show progress bar button
        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        // Image view to show image after downloading
        my_image = (ImageView) findViewById(R.id.my_image);
        /**
         * Show Progress bar click event
         * */
        btnShowProgress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // starting new Async Task
                new DownloadFileFromURL().execute(ur);
            }
        });
    }

    /**
     * Showing Dialog
     * */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type:
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, Integer, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {

                for (int i = 0; i < f_url.length; i++) {
                    URL url = new URL(f_url[i]);
                    URLConnection conection = url.openConnection();
                    conection.connect();
                    // getting file length
                    int lenghtOfFile = conection.getContentLength();

                    // input stream to read file - with 8k buffer
                    InputStream input = new BufferedInputStream(
                            url.openStream(), 8192);
                    System.out.println("Data::" + f_url[i]);
                    // Output stream to write file
                    OutputStream output = new FileOutputStream(
                            "/sdcard/downloaded" + i + ".jpg");

                    byte data[] = new byte[1024];

                    long total = 0;

                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        // After this onProgressUpdate will be called
                        publishProgress((int) ((total * 100)/lenghtOfFile));

                        // writing data to file
                        output.write(data, 0, count);
                    }

                    // flushing output
                    output.flush();

                    // closing streams
                    output.close();
                    input.close();
                }
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(Integer... progress) {
            // setting progress percentage
            pDialog.setProgress(progress[0]);
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory()
                    .toString() + "/downloaded.jpg";
            // setting downloaded into image view
            // my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }

    }
}

A: If I understand correctly, you do not want to download all the files at the same tim e(simultaneously) but one by one (serially).
In order to do so build a String array with the URLs to download, and call execute() with that array.

Example: Assuming that your DownloadFileAsync expects String as a
  parameter to it's doInBackground method, you would call to:

new DownloadFileAsync().execute(url1, url2, url3, url4, video1, video2, video3, video4);

A: package com.ProgressDialogDemo1;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class ProgressDialogDemoActivity extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
    ProgressBar prgBar1;
    ImageView imgv1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imgv1 = (ImageView) findViewById(R.id.imgv1);
        startBtn = (Button)findViewById(R.id.startBtn);
        prgBar1 = (ProgressBar) findViewById(R.id.prgBar1);
        prgBar1.setMax(100);

        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                    startDownload();
            }
        });
    }

    private void startDownload() {
        String[] url = {"http://animal.discovery.com/birds/peacock/pictures/peacock-picture.jpg",
                    "http://www.funrocker.com/blog/wp-content/uploads/2010/04/Animals-Wild-Life-Jungle-FunRocker.Com-03.jpg",
                    "http://www.thewallpapers.org/photo/5790/Nature_Wallpapers-037.jpg",
                    "http://2.bp.blogspot.com/-j56yaqpfjVE/TnzTjcqnCjI/AAAAAAAAGPM/MzqmczFkC30/s1600/natural-pictures.jpg",
                    "http://www.fantasy-and-art.com/wp-content/gallery/nature-wallpapers/red-tree-wallpaper-hd.jpg",
                    "http://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Bachalpseeflowers.jpg/300px-Bachalpseeflowers.jpg"};
        DownloadFileAsync dloadFAsync = new DownloadFileAsync(url);
        dloadFAsync.execute(url);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setCancelable(false);
            return mProgressDialog;
        default:
            return null;
        }
    }

    //              Async  Task
    class DownloadFileAsync extends AsyncTask<String, String, String> {
        int current=0;
        String[] paths;
        String fpath;
        boolean show = false;

        public DownloadFileAsync(String[] paths) {
            super();
            this.paths = paths;
            for(int i=0; i<paths.length; i++)
                System.out.println((i+1)+":  "+paths[i]);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... aurl) {
            int rows = aurl.length;
                while(current < rows)
                {
                    int count;
                    try {
                        System.out.println("Current:  "+current+"\t\tRows: "+rows);
                        fpath = getFileName(this.paths[current]);
                        URL url = new URL(this.paths[current]);
                        URLConnection conexion = url.openConnection();
                        conexion.connect();
                        int lenghtOfFile = conexion.getContentLength();
                        InputStream input = new BufferedInputStream(url.openStream(), 512);
                        OutputStream output = new FileOutputStream("/sdcard/"+fpath);
                        byte data[] = new byte[512];
                        long total = 0;
                        while ((count = input.read(data)) != -1) {
                            total += count;
                            publishProgress(""+(int)((total*100)/lenghtOfFile));
                            output.write(data, 0, count);
                        }
                        show = true;
                        output.flush();
                        output.close();
                        input.close();
                        current++;
                    } catch (Exception e) {}
            }   //  while end
            return null;
        }

        @Override
        protected void onProgressUpdate(String... progress) {
            prgBar1.setProgress(Integer.parseInt(progress[0]));
            if(show) {
                File dir = Environment.getExternalStorageDirectory();
                File imgFile = new File(dir, getFileName(this.paths[(current-1)]));
                Bitmap bmp  = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                imgv1.setImageBitmap(bmp);
                show = false;
            }
        }

        @Override
        protected void onPostExecute(String unused) {
            System.out.println("unused: "+unused);
        }
    }

    public String getFileName(String wholePath)
    {
        String name=null;
        int start,end;
        start=wholePath.lastIndexOf('/');
        end=wholePath.length();     //lastIndexOf('.');
        name=wholePath.substring((start+1),end);
        name = "images/"+name;
        System.out.println("Start:"+start+"\t\tEnd:"+end+"\t\tName:"+name);
        return name;
    }
}


text:
Q: Calculating content of newcommand In order to have a tikz picture adjust to some input values I have created something as the code below. In the code below the distance between A and C is twice as long as the distance between A and B as it should be. However, the number given ist not correct. Instead of 2*15 I would like to have 30.
\documentclass[tikz]{standalone}
\usepackage{tikz}
\usepackage[utf8]{inputenc}
\usetikzlibrary{calc}
\usetikzlibrary{backgrounds}
\newcommand{\Anton}{15}
\newcommand{\Berta}{\Anton*2}
\begin{document}
\centering
\begin{tikzpicture}[x=1mm,y=1mm,scale=1]
\tikzset{mystyle/.style={<->}}
    \tikzset{every node/.style={fill=white, font=\normalsize}}
\node (A) at (0,0){A};
\node (B) at (\Anton,0){B};
\node (C) at (-\Berta,0){C};
% Maße Vertikal
\path (A) edge [mystyle] node {\Anton} (B);
\path (A) edge [mystyle] node {\Berta} (C);
\end{tikzpicture}
\end{document}

gives:

Is there a way to calculate the content of \Bertabefore using it as the lable on the \path?
Thanks!

A: I would do the whole thing with TikZ/PGF keys. If you want \Anton and \Berta available generally, you can use \tikzset{} in the preamble or at the beginning of the document.
There are various ways to do this. The way I've done it here involves setting up \Anton to store a simple value, defining an additional style (double trouble) to create \Berta from an argument using \pgfmathsetmacro, and then simply forwarding the value given to Anton to double trouble any time Anton is set.
This is more complicated to explain than to see in the code, I think!
\documentclass[tikz]{standalone}
\usepackage[utf8]{inputenc}
\tikzset{%
  % key Anton stores a value in \Anton
  Anton/.store in=\Anton,
  % key double trouble sets \Berta to twice the argument it is given
  double trouble/.code={%
    \pgfmathsetmacro\Berta{int(2*#1)}%
  },
  % any time the key Anton is used, the same value will be passed to double trouble
  Anton/.forward to=/tikz/double trouble,
  % make sure the key Anton is set to something so \Anton and \Berta have some default value
  Anton=15,
}
\begin{document}
\begin{tikzpicture}
  [
    x=1mm,
    y=1mm,
    mystyle/.style={<->},
    every node/.style={fill=white},
  ]
  \node (A) {A};
  \node (B) at (\Anton,0){B};
  \node (C) at (-\Berta,0){C};
  % Maße Vertikal
  % we can make this a bit more concise ...
  \path [mystyle] (A) edge node {\Anton} (B) edge node {\Berta} (C);
\end{tikzpicture}
\end{document}

The advantage of using TikZ keys is that the user interface is intuitive and that it is easy to modify the values between or within tikzpictures.
Adding the following after the above picture, for example, we change the value of both macros by setting Anton=10 and then modify them again for just one node, setting Anton=2, so that \Berta produces 4 while \Anton still produces 10 when creating the nodes on the final line.
\begin{tikzpicture}
  [
    x=1mm,
    y=1mm,
    mystyle/.style={draw=blue, thick, text=red},
    every node/.style={fill=white},
    Anton=10,
  ]
  \node (A) {A};
  \node (B) at (\Anton,0){B};
  \node (C) at (-\Berta,0){C};
  % Maße Verti
  % we can make this a bit more concise ...
  \path [mystyle] (A) edge node {\Anton} (B) edge node [Anton=2] {\Berta} (C);
\end{tikzpicture}

Note that the distances used are all based on the initial value. The macros differ only when creating the node containing \Berta.
Whether this is useful and how useful depends, obviously, on the real use case. But it the kind of thing which is often required in TikZ pictures and it is nice to keep that flexibility, even if it is not of any immediate use.
EDIT EDIT
Here's an extended and modified version which demonstrates:

*

*how to add further dependent variables (I didn't do 10 as I got bored, but I did get up to \Enid);

*how to accommodate both decimals and integers.

To print a variable, \variable, in a node, use
\node [print me=\variable] ;

Normally, a \node needs {}. However, in this case, the contents are being created by print me, which uses node contents.
If the node is created on an edge, you may need
... edge node [print me=\variable] {} ...

At least, I found I needed that.
print me expects a number. If you use e.g. A, you'll get an error. \variable is fine, as long as it produces a number. The code is configured to print the number up to 2 decimal places. Change the value of precision to alter this. If the number has fewer than 2 decimal places, no zeros will be printed. If the number is an integer, no decimal point will be printed.
Here's the code for the original case an an extended one.
\documentclass[tikz]{standalone}
\usepackage[utf8]{inputenc}
\tikzset{%
  % key Anton stores a value in \Anton
  Anton/.store in=\Anton,
  % key double trouble sets \Berta to twice the argument it is given
  double trouble/.code={%
    \pgfmathsetmacro\Berta{2*#1}%
    % additional dependent variables for demonstration purposes
    \pgfmathsetmacro\Carlos{4*(sqrt(#1))}%
    % we can use those we've just defined to create more
    \pgfmathsetmacro\Dave{atan(\Carlos/\Berta)}%
    \pgfmathsetmacro\Enid{sqrt((\Carlos)^2 + (\Berta)^2)}%
  },
  % any time the key Anton is used, the same value will be passed to double trouble
  Anton/.forward to=/tikz/double trouble,
  % make sure the key Anton is set to something so \Anton and \Berta have some default value
  Anton=15,
  % this pretty-prints the argument, which should be a number (or something which produces a number)
  print me/.style={node contents={\pgfmathprintnumber{#1}}},
  % this configures the printing of the numbers
  /pgf/number format/.cd,
  % we don't want decimal points in the case of integers; we don't want trailing zeros
  fixed,
  % print at most 2 decimal places - modify value as desired
  precision=2,
}
\begin{document}
\begin{tikzpicture}
  [
    x=1mm,
    y=1mm,
    mystyle/.style={<->},
    every node/.style={fill=white},
  ]
  \node (A) {A};
  \node (B) at (\Anton,0){B};
  \node (C) at (-\Berta,0){C};
  % Maße Verti
  % we can make this a bit more concise ...
  % notice the nodes are empty: print me=\variable puts the content in
  \path [mystyle] (A) edge node [print me=\Anton] {} (B) edge node [print me=\Berta] {} (C);
\end{tikzpicture}
\begin{tikzpicture}
  [
    x=1mm,
    y=1mm,
    mystyle/.style={<->},
    every node/.style={fill=white},
    Anton=15.5,
  ]
  \node (A) {A};
  \node (B) at (\Anton,0) {B};
  \node (C) at (-\Berta,0) {C};
  % use our new dependent variables
  \node (D) at (0,-\Carlos) {D};
  \path (C) ++(\Dave:\Enid) node (E) {E};
  % Maße Verti
  % we can make this a bit more concise ...
  \draw [mystyle] (A) edge node [print me=\Anton] {} (B) edge node [print me=\Berta] {} (C) edge node [print me=\Carlos] {} (D) [bend left] to (E);
\end{tikzpicture}
\end{document}

A: Use \pgfmathsetmacro for a decimal number and \pgfmathtruncatemacro for an integer. Alternatively, if you want to handle both together, here's a variant of \pgfmathsetmacro. The way it works is as follows: our problem is that \pgfmathsetmacro\test{1+1} sets \test to 2.0. So my variant checks whether the result is of the form n.0 for some integer n, and if so drops the 0. Other decimals are left alone.
\documentclass[tikz]{standalone}
\usepackage{tikz}
\usepackage[utf8]{inputenc}
\usetikzlibrary{calc}
\usetikzlibrary{backgrounds}
\newcommand\mymathsetmacro[2]{\pgfmathparse{#2}\expandafter\mymathsetmacrohelper\pgfmathresult\nil\edef#1{\pgfmathresult}}
\def\mymathsetmacrohelper#1.#2#3\nil{\ifx0#2\ifx&#3& \def\pgfmathresult{#1}\fi \fi}
\newcommand{\Anton}{15}
\mymathsetmacro{\Berta}{\Anton*2}
\begin{document}
\centering
\begin{tikzpicture}[x=1mm,y=1mm,scale=1]
\tikzset{mystyle/.style={<->}}
    \tikzset{every node/.style={fill=white, font=\normalsize}}
\node (A) at (0,0){A};
\node (B) at (\Anton,0){B};
\node (C) at (-\Berta,0){C};
% Maße Vertikal
\path (A) edge [mystyle] node {\Anton} (B);
\path (A) edge [mystyle] node {\Berta} (C);
\end{tikzpicture}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get a "show password" effect in vb.net? I am making an email login program in visual basic 2015 with various options, one of them being the option to show password or not with probably a check box. It is just a simple, standard windows forms application, I am relatively new to it.
Edit: Answered by jmcilhinney. Thanks! :D
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged

'Display plain text if and only if check box is checked.

TextBox1.UseSystemPasswordChar = Not CheckBox1.Checked

End Sub

A: Set the UseSystemPasswordChar property of your TextBox to True to mask the password.
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
    'Display plain text if and only if check box is checked.
    TextBox1.UseSystemPasswordChar = Not CheckBox1.Checked
End Sub

A: Private Sub txtPassword_MouseHover(sender As Object, e As EventArgs) Handles txtPassword.MouseHover
    txtPassword.PasswordChar = ""
End Sub

Private Sub txtPassword_MouseLeave(sender As Object, e As EventArgs) Handles txtPassword.MouseLeave
    txtPassword.PasswordChar = "*"
End Sub

A: You have to do couple of changes. Change your password textbox UseSystemPasswordChar to false and the PasswordChar to Char(0). Something like this:
If chkViewPassword.Checked Then txbPwd.PasswordChar = Convert.ToChar(0) Else txbPwd.PasswordChar = Convert.ToChar("*")
    txbSMTPPwd.UseSystemPasswordChar = Not chkViewPassword.Checked


text:
Q: Uibuttons keep freezing when clicked Im trying to gather the information on how many time the button is clicked and it freezes when clicked.  This is just after an animation has occurred.
- (IBAction)btnGreen:(id)sender {
    greenCount++;
    NSLog(@"%i",greenCount);
}

- (IBAction)btnRed:(id)sender {
    redCount++;
}
- (IBAction)btnBlue:(id)sender {
    blueCount++;
}

- (IBAction)btnYellow:(id)sender {
    yellowCount++;
}


text:
Q: New Ubuntu 20.04 Desktop System. Freezing after idle. Suspect Suspend and won't wake up I've recently loaded Ubuntu onto my desktop.  I had been using Windows 10 before.
Now the system seems to go to sleep and I am not able to wake it up.  I've taking the recommended steps that I have found to disable suspend/sleep/hibernate on my system, but it still seems to do this sometimes.  Sometimes this will happen after just 20 minutes and other times it won't do it for days on end.
My system is running Ubuntu 20.04 LTX x86_64
on a Gigabyte AB350-Gaming 3 Motherboard with a Ryzen 5 1600 3.2 GHz processor NVIDIA GeForce GTX 1060 3GB Video Card and 16 GB of memory.
I am not sure what to do next.


text:
Q: Sending traffic from an interface to another server I have traffic (TCP) coming to a network interface on an Ubuntu server. I would like to send all that incoming traffic to another server, i. e. to its IP address. Nothing else is required (i.e. filtering based on port, etc.) How can I achieve that? Can be either a set of iptables rules, a script, a daemon,...
The servers can be connected via a VPN, if that helps.

A: You can do this with iptables.
iptables -t nat -A PREROUTING -p tcp --dport <incoming_tcp_port> -j DNAT --to-destination <destination_server>:<destination_port>

# Set MASQUERADE so that we can receive responses back.
iptables -t nat -A POSTROUTING -j MASQUERADE

You will also need to enable forwarding in your kernel for this to work: sysctl -w net.ipv4.ip_forward=1.
Source here.


text:
Q: ORIENTDB: traverse / edges with attributes I have a application permission related question in a graph database. The structure is as follows ... and I have to read the role of a user related to a node. The nodes are hierarchically organized and the roles are provided as Edges containing a type attribute and the relation User -> UserRole {type:xyz} -> Node
create class User extends V
create class Node extends V
create class has_father extends E
create class UserRole extends E

create vertex User set name = 'u1'
create vertex User set name = 'u2'
create vertex User set name = 'u3'

create vertex Node set name = 'n1'
create vertex Node set name = 'n11'
create vertex Node set name = 'n12'
create vertex Node set name = 'n111'
create vertex Node set name = 'n112'
create vertex Node set name = 'n1111'
create vertex Node set name = 'n1112'
create vertex Node set name = 'n11111'
create vertex Node set name = 'n11112'

create edge has_father from (select from Node where name = 'n11') to (select from Node where name = 'n1')
create edge has_father from (select from Node where name = 'n12') to (select from Node where name = 'n1')
create edge has_father from (select from Node where name = 'n111') to (select from Node where name = 'n11')
create edge has_father from (select from Node where name = 'n112') to (select from Node where name = 'n11')
create edge has_father from (select from Node where name = 'n1111') to (select from Node where name = 'n111')
create edge has_father from (select from Node where name = 'n1112') to (select from Node where name = 'n111')
create edge has_father from (select from Node where name = 'n11111') to (select from Node where name = 'n1111')
create edge has_father from (select from Node where name = 'n11112') to (select from Node where name = 'n1111')

create edge UserRole from (select from User where name = 'u1') to (select from Node where name = 'n1') set type = 'admin'
create edge UserRole from (select from User where name = 'u1') to (select from Node where name = 'n11') set type = 'read'
create edge UserRole from (select from User where name = 'u2') to (select from Node where name = 'n111') set type = 'write'
create edge UserRole from (select from User where name = 'u1') to (select from Node where name = 'n11111') set type = 'test'

actually i have to read now all children from "n" and get the Node and the UserRole of User "u1":
asking for "u1" and "n1":
n11 read
n12 admin

asking for "u1" and "n1111":
n11111 test
n11112 read

Meaning that there is max 1 UserRole assigned and the value might get overridden within the tree. A user might be
admin for root level and only read from level n11 on.
How can I read the children Nodes passing the father @rid (or a filter) and the calculated Roles for a special User?

A: try this SQL for your 2nd example:
select name as Name, $a.type[0] as Role from (select expand(in('has_father')) from (select from Node where name = 'n1111') unwind in)

let $a=(select inE('UserRole').type as type from (
            traverse out('has_father'),in('UserRole') from $parent.$current while out('UserRole').@rid <> #21:0
            ) where in('UserRole').@rid = #21:0
            limit 1
        )

where #21:0 is the u1 @rid.
As long this isn't so much pretty, you could insert this in JS function and parametrise it.


text:
Q: pass by reference java public class Class_of_var
{
 public  String[] su_name =new String[100];

}
`public class Main_Class {
 public void show_all(int a)
 {
     Class_of_var arr = new Class_of_var() ;

     for (int i = 0; i < a; i++)
     {
      System.out.println("Surname  " + arr.su_name[i]);

     }

 }

public static void main(String[] agrs)
{

    Add_Car Car=new Add_Car();
    Main_Class m = new Main_Class() ;
    Scanner sc = new Scanner(System.in);
      int x = 1;
    int a = 0;
    do
    {
        int y=0;
        System.out.println("enter 1 to add a car");
        System.out.println("enter 3 to show all cars infromation");

        y=sc.nextInt();

        switch (y)
        {

            case 1:
             *emphasized text*
              Car.add_car(a);
                a++;
                break;

            case 3:

*when i call the s_name in class_of_var the value will be null  *
                    System.out.println("the a number" + a);
                    m.show_all(a);
                    break;
        }

    } while (x == 1);

}

}

public class Add_Car {
    Class_of_var arr = new Class_of_var() ;
    public void add_car(int a)
    {
      Scanner sc = new Scanner(System.in);

    System.out.println("enter the surname of owner");
    arr.su_name[a] = sc.nextLine();

}

}
`


text:
Q: Error: expected expression before '||' token I would like to know what's wrong with my code. Are there problems with or statement ( || ) or is there something else wrong with my code. The error that it gives me is: [Error] expected expression before '||' token
    if (DH>YH>=K) || (DH>K>=YH)
        {
        printf("Soodsaim variant on osta %f päevapiletit.\n", P);
        }

A: Once you get the parens right, DH>YH>=K probably doesn't mean what you think it means. DH>YH produces either 0 or 1, and then that's compared to K.
You'll want to write DH>YH && YH>=K.

A: Here we go. It should work fine. :)
#include <stdio.h>

int main()
{
    float P, S, Y, D, K, DH, YH;
    printf("Sisestage päevade arv:\n");
    scanf("%f", &P);
    printf("Sisestage sõitude arv:\n");
    scanf("%f", &S);
    printf("Sisestage ühekordse pileti hind:\n");
    scanf("%f", &Y);
    printf("Sisestage päeva pileti hind:\n");
    scanf("%f", &D);
    printf("Sisestage kuukaardi hind:\n");
    scanf("%f", &K);
    DH = P*D;
    YH = Y*S;
    if ((DH>YH>=K) || (DH>K>=YH))
        {
        printf("Soodsaim variant on osta %f päevapiletit.\n", P);
        }
    else
        if ((YH>DH>=K) || (YH>K>=DH))
        {
        printf("Soodsaim variant on osta %f ühekordset piletit.\n", S);
        }
    else
        if ((K>DH>=YH) || (K>YH>=DH))
        {
            printf("Soodsaim variant on kuukaart.\n");
        }
    system("pause");
}


text:
Q: Docker: Connect to container (without exposing ports) First things first: I did use the search, both Google and SO.
Task
Trying to connect a MongoGUIClient from my Host (OSX) to the MongoDB inside my container.
What did I do?

*

*Version: docker run --name some-mongo -d mongo

*Version: docker run --name some-mongo -d -p 127.0.0.1:27017:27017 mongo
What's the problem?
Using the 2. version I am able to connect from the host without any further problems. But that means I need to expose that port on my system which I do not want to do.
What I am trying to achieve
I want to use the 1. version given above, without exposing ports and then do docker inspect to get the container ip (which in my case is 172.17.0.2) and then I want to connect to 172.17.0.2:27017 but that does not work and that is the problem.
What am I doing wrong here? Is there a conceptual mistake of mine? I just want to connect to that container sub network without exposing ports. Is that not possible?

A: Use defreitas/dns-proxy-server. Then you can access the container with its hostname.
Example:
# First run DPS
$ docker run --rm --hostname dns.mageddo \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /etc/resolv.conf:/etc/resolv.conf \
defreitas/dns-proxy-server

# Then run the container
$ docker run --hostname some-mongo --name some-mongo -d mongo

You can check if it works using netcat:
$ nc -z some-mongo 27017
$ echo $?
0

A: Even if you could contact directly your container, it exposed port would only be visible by other containers, not by your docker host (xhyve VM) or your actual host (Mac).
So a mapping is still needed.
You could then try and use the XHyve Alpine VM IP but... this thread mentions a couple of current (Q4 2016) limitations preventing to do that.
That is why the current application example only shows access through localhost.

From this thread:

Currently the only way to access containers is by exposing a port.
  There is no docker0 on the Mac.


text:
Q: Symfony 5.4 routes by annotations not working I know this question has been discussed million times here, but it is the third day I keep on struggling on this issue.
I've got symfony application been developed on my local PC (Windows). Now I'm trying to deploy it on my linux web-hosting (Linux).
My routes are initted in controllers' classes via annotations.
<?php

namespace App\Controller;

use App\Entity\Category;
use App\Repository\CategoryRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class IndexController extends AbstractController
{
    /**
     * @Route("/", name="app_index")
     */
    public function index(): Response
    {
        return $this->render('index/index.twig', [
            'controller_name' => 'IndexController'
        ]);
    }
}

The issue is these routes are not included by some reason, which leads to 404 error
/config/services.yaml
services:
  _defaults:
    autowire: true
    autoconfigure: true

  App\:
    resource: '../src/'
    exclude:
      - '../src/DependencyInjection/'
      - '../src/Entity/'
      - '../src/Kernel.php'
...

/config/routes/annotations.yaml
controllers:
    resource: ../../src/Controller/
    type: annotation
    prefix:
      ru: '' # don't prefix URLs, the default locale
      en: '/en'

kernel:
    resource: ../../src/Kernel.php
    type: annotation

/config/routes.yaml is empty
symfony console debug:router shows only admin and profiler routes but not mine initted in controllers
I would be very grateful if you could help me solving this issue.
If I describe the index route in routes.yaml (which I don't like.. What are the annotations then for?)
index:
    path: /
    controller: App\Controller\IndexController::index

symfony goes wild
"App\Controller\IndexController" has no container set, did you forget to define it as a service subscriber?
All I've done during deployment was:

*

*clone git repo with my application on the production server

*installed composer dependencies

*migrated database structure

*updated env with new db connection

A: I hope auto wire is enabled in service.yaml
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

And please comment code in routes.yaml
And try with php bin/console cache:clear command.

A: try with PHP 8 attributes
#[Route('/', name: 'app_index')]

function:
#[Route('/', name: 'app_index')]
public function index(): Response {
    return $this->render('index/index.twig');
}

Documentation:
https://www.php.net/manual/fr/language.attributes.overview.php

A: You must require:
composer require symfony/apache-pack

After that just change FollowSymLinks to SymLinksIfOwnerMatch ... and "vu à la" ... This package reconfigure Your code for Apache web-server ...


text:
Q: Apache Camel timer route URI syntax I have a camel application with a timer route defined like this:
String timerURI = "timer:/MyApplication?period=5m";

I realized that the URI syntax is probably incorrect. The correct syntax as shown on the Apache Camel site should be:
String timerURI = timer://MyApplication?period=5m";

However, I noticed some strange behavior in the logs. In the first instance I show camel logging the URI as:
(route1) from(timer:///MyApplication?period=5m) --> bean[com.mypackage.....]

In the second instance, the log shows as:
(route1) from(timer://MyApplication?period=5m) --> bean[com.mypackage.....]

I tried a third option as
String timerURI = timer:MyApplication?period=5m";

and it showed in the logs as:
(route1) from(timer://MyApplication?period=5m) --> bean[com.mypackage.....]

When I defined the URI with a single /, as in the first case, I see an exception like this:
org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: direct: due to: Expected scheme-specific part at index 7: direct:
    at org.apache.camel.impl.DefaultCamelContext.normalizeEndpointUri(DefaultCamelContext.java:601)
    at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:483)
    at org.apache.camel.util.CamelContextHelper.getMandatoryEndpoint(CamelContextHelper.java:63)
    at org.apache.camel.util.ExchangeHelper.resolveEndpoint(ExchangeHelper.java:88)
    at org.apache.camel.processor.RecipientListProcessor.resolveEndpoint(RecipientListProcessor.java:223)
    at org.apache.camel.processor.RecipientListProcessor.createProcessorExchangePairs(RecipientListProcessor.java:163)
    at org.apache.camel.processor.MulticastProcessor.process(MulticastProcessor.java:208)
    at org.apache.camel.processor.RecipientList.sendToRecipientList(RecipientList.java:153)
    at org.apache.camel.processor.RecipientList.process(RecipientList.java:112
::::::::::::::::::::::::::::::::
Caused by: java.net.URISyntaxException: Expected scheme-specific part at index 7: direct:
    at java.net.URI$Parser.fail(URI.java:2829)
    at java.net.URI$Parser.failExpecting(URI.java:2835)
    at java.net.URI$Parser.parse(URI.java:3038)
    at java.net.URI.<init>(URI.java:595)
    at org.apache.camel.util.URISupport.normalizeUri(URISupport.java:448)
    at org.apache.camel.impl.DefaultCamelContext.normalizeEndpointUri(DefaultCamelContext.java:599)
    ... 51 more

So only with the first instance when I had single /, I saw this exception but the other two seem to be fine. Even stranger though, the error doesn't repeat very often. I never see it my local workspace but I saw it twice in my Dev test server and once in the Integration test server. Even after failing with this exception, it works in the next time when the timer runs after 5 minutes. Does anyone know how camel is interpreting these URLs and why it failed those few times?

A: Use no slashes, or use double slashes. eg
"timer:foo"

or
"timer://foo"

Then when having double slashes, then Camel regards this as no slashes, eg like http://foo.com, can be typed http:foo.com in the browser.
If you use 1 or 3 slashes, then that slash becomes part of the context-path for the component. Only a few components support a leading slash, such as the file/ftp components where a leading slash denotes the starting directory is /foo etc.


text:
Q: Configure nginx for both Vue app front end and node.js backend I have been searching for this answer for months and have never been able to resolve this. I am using nginx as my web server and using node.js for my backend apis and vue as my main front end webpage that uses webpack. I would like to be able to go to my Vue page by going to http://ip and then get access to the api services by going to http://ip/api. I dont have a domain name set up so I use IP address for the urls.
So far I built my Vue app and is sitting in the /var/www/html/Web/dist folder and it works if you go to the http://ip url but I can not access my node.js APIs. My node.js server is running on localhost port 3000. My nginx config looks like this:
server {
        listen 80;

        root /var/www/html/Web/dist;
}

server {

listen 80;

  location /api/ {

        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

  }

}

A: You are duplicating server configuration. Simply keep one server properties set :
server {
  listen 80;
  root /var/www/html/Web/dist;
  location /api/ {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

  }
}

That means :

*

*listens to all request for all ip's on port 80

*Evaluate relative path from root /var/www/html/Web/dist;

*if there's a matching '/api/' in url pass it to localhost:3000

It should work as expected now


text:
Q: Is there some known way to create the Mandelbrot set (the boundary), with an iterated function system? Is there some known way to create the Mandelbrot set (the boundary),
with an iterated function system (IFS)?
Julia sets can be formed by iterating the two functions $z \mapsto \pm \sqrt{z-c},$
and this quickly converges to the Julia set. Formally, the two functions form a Hutchinson operator,
and the Julia set is the unique compact fixed set.
That is, $J = f_1(J) \cup f_2(J)$ where $f_1,f_2$ are the two functions, and $J$ is the Julia set.
However, Mandelbrot is the iteration of many functions, with start value 0,
so there is no obvious way to define an IFS. Is there some non-obvious way?
That is, find maps $g_1,\dots,g_n$ s.t. the Mandelbrot $M$ can be expressed as
$M = \bigcup_i g_i(M),$ where each $g_i$ maps $M$ to some subset of $M,$ but not the entire $M.$

A: I know very little about the Mandelbrot set or complex dynamics, but there are several features which strongly suggest that its boundary is not the attractor of an iterated function system, at least a reasonable one.
For example.

*

*Around Misiurewicz points (which are only countable but dense), the Mandelbrot set looks locally like the corresponding Julia set, in particular it looks locally very different for each Misiurewicz point. Under some natural assumptions, sets invariant under IFS's look locally like the set itself.

*If an attractor of an IFS is connected, it is locally connected. The boundary of the Mandelbrot set is connected but it is a famous open problem whether it is locally connected.

*Under some weak contractivity assumptions on the generating maps, attractors of IFS's cannot have full dimension in the ambient space, while the boundary of the Mandelbrot set has dimension 2.

Also it is not quite true that all Julia sets are fixed sets for Hutchinson operators, at least under the usual definition of Hutchinson operator which requires strict contractivity of the maps (the maps $z\to\pm\sqrt{z-c}$ are in general not contractions, even on the Julia set itself)

A: You may take a look at Barnsley, Fractals everywhere, pp. 318f, Figures viii.237 and viii.238 (http://books.google.de/books?id=oh7NoePgmOIC&lpg=PP1&hl=de&pg=PA319#v=onepage&q&f=false). It looks not exactly like the Mandelbrot set, but there is a similarity. Unfortunately Im not able to reproduce these images (using algorithm 2.1 from page 302).


text:
Q: Json data is not getting loaded into Jqgird I have a Jqgrid that i am trying to load with server side Json data data is not getting loaded into Jqgrid.I am not getting any error either.
This is my client side code..
function getdata() {
    $("#UsersGrid").jqGrid({
        url: 'getGriddahico.ashx',
        datatype: 'json',
        colNames: ['AccountNumber', 'BillNumber', 'BillDate', 'Oprator', 'CallDate', 'Time', 'Destination', 'DialledNumber', 'CallType', 'Duration', 'CallCost', 'PhoneNumber'],
        colModel: [
            { name: 'AccountNumber', width: 100, sortable: true, align: 'center' },
            { name: 'BillNumber', width: 100, sortable: true, align: 'center' },
            { name: 'BillDate', width: 100, sortable: true, align: 'center' },
            { name: 'Oprator', width: 100, sortable: true },
            { name: 'CallDate', width: 100, sortable: true, align: 'center' },
            { name: 'Time', width: 100, sortable: true, align: 'center' },
            { name: 'Destination', width: 100, sortable: true, align: 'center' },
            { name: 'DialledNumber', width: 100, sortable: true, align: 'center' },
            { name: 'CallType', width: 100, sortable: true, align: 'center' },
            { name: 'Duration', width: 100, sortable: true, align: 'center' },
            { name: 'CallCost', width: 100, sortable: true, align: 'center' },
            { name: 'PhoneNumber', width: 100, sortable: true, align: 'center' }
            ],
            rowNum: 100,
            rowList: [100, 200, 300],
            pager: '#UsersGridPager',
            sortname: 'CallDate',
            viewrecords: true,
            ignoreCase: true,
            sortorder: 'asc',
            autowidth: true,
            toppager: true,
            height: '100%'
});

And this is my client side code to get the data in json format..
while(rs.Read()){
    if(rc){
        json = json + ",";
    }

    json = json + "\n{";
    json = json + "\"CallCost\":\"" + Convert.ToString(rs["CallCost"]) + "\",";
    json = json + "\"cell\":[" + Convert.ToString(rs["CallCost"]) + "";
    json = json + ",\"" + Convert.ToString(rs["AccountNumber"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["BillNumber"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["BillDate"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["Oprator"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["CallDate"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["Time"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["Destination"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["DialledNumber"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["CallType"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["Duration"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["CallCost"]) + "\"";
    json = json + ",\"" + Convert.ToString(rs["PhoneNumber"]) + "\"]";
    json = json + "}";

    rc=true;
}

json = json +"]\n";

json = json +"}";

HttpContext.Current.Response.Write(json);

Please help me to resolve the issue .Thanks..


text:
Q: How to make a container 'lighten' on hold / on tap in Flutter?
I am trying to create an app with a scroll view and the objects are clickable like the google news app. Can anyone answer how to animate the container to have a white glow on holding the tile?
Here is the list view builder I have for the app
                Container(
                  padding: EdgeInsets.only(top: 16),
                  child: ListView.builder(
                      physics: ClampingScrollPhysics(),
                      itemCount: article.length,
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        return news_tile(
                            imageurl: article[index].urlToimage,
                            news_title: article[index].title,
                            news_desc: article[index].description,
                            web_url: article[index].url
                        );
                      }),
                )

and this is the contents of the tile which the list view builder calls
class news_tile extends StatelessWidget {
  String imageurl, news_title, news_desc,web_url;

  news_tile({this.imageurl, this.news_title, this.news_desc,this.web_url});

  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        Navigator.push(context, MaterialPageRoute(
            builder: (context) => article_view(
              web_url: web_url,
            )
        ));
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 16),
        child: Column(
          children: <Widget>[
            ClipRRect(borderRadius: BorderRadius.circular(6), child: Image.network(imageurl)),
            SizedBox(
              height: 8,
            ),
            Text(news_title, style: TextStyle(fontSize: 17,fontWeight: FontWeight.w600)),
            SizedBox(
              height: 8,
            ),
            Text(news_desc, style: TextStyle(color: Colors.black54))
          ],
        ),
      ),
    );
  }
}

A: You could go with the InkWell Widget. It provides a tapping/holding color effect similar to that. Have a look at the official docs here:
https://api.flutter.dev/flutter/material/InkWell-class.html
Note that you need a Material Widget as an ancestor of your InkWell, but the docs explain that more.
Hope it works for you!
Edit: Sorry, since you are working with a Container, Ink is also important for you:
https://api.flutter.dev/flutter/material/Ink-class.html
Check the docs section "The ink splashes aren't visible!" for why that is.


text: Q: How do I retrieve scenario failure message (cucumber jvm) in the After hook? I have been able to get scenario failure status using scenario.isFailed() but not the error message that gets displayed in the stacktrace.


text:
Q: MySQL: Can't insert '&' in a column I'm going from Oracle to MySQL.
Doing some migration of data.
BUT
I got some problem regarding strings containing the '&' character...
Can't get it in a table in MySQL.
Example:
create table tmp_a(inforad varchar(100));

Doesn't work as I want ...
insert into tmp_a values('Me, myself & I');

Doesn't work as I want ...
insert into tmp_a values('Me, myself \& I');

Any advice ?!
I don't want to go through Java, PHP, C or anything else, just core SQL :)

A: Shouldn't be a problem
Had a quick look at the MySQL docs for special characters: https://dev.mysql.com/doc/refman/5.0/en/string-literals.html
String literal special character escape sequences
Escape Sequence | Character Represented by Sequence
\0  |   An ASCII NUL (0x00) character.
\'  |   A single quote ("'") character.
\"  |   A double quote (""") character.
\b  |   A backspace character.
\n  |   A newline (linefeed) character.
\r  |   A carriage return character.
\t  |   A tab character.
\Z  |   ASCII 26 (Control+Z). See note following the table.
\  |   A backslash ("\") character.
\%  |   A "%" character. See note following the table.
\_  |  A "_" character. See note following the table.


text:
Q: How make a Layout center with 3 view I would make that:
How do you do that? I have fixed the position of draws, Is there an other method with TableLayout for example because i would integrated drawing with other views. Thank you.
public class CaseView extends View {

private static final float MINP = 1f;
private static final float MAXP = 1f;

private Bitmap mBitmap1, mBitmap2, mBitmap3, _scratch1 = null,
        _scratch2 = null;
private Canvas mCanvas1;
private Canvas mCanvas2, mCanvas3;
private Path mPath1, mPath2;
private Paint mBitmapPaint1;
private Paint mBitmapPaint2, mBitmapPaint3;
private Paint mPaint1;
private Paint mPaint2, mPaint3;
private int IdImage;
private int positionTop = 0;
private int positionLeftOne = 0;
private int positionLeftTwo = 0;
private int positionLeftThree = 0, mHeightCase = 100,
        widthBetweenCase = 0;
private String colorGold = "#E29F2B";
private boolean firstTime = false;

// private Bitmap image;
// private Paint paint;

boolean isErase;

public CaseView(Context ctx, AttributeSet attrs) {
    super(ctx, attrs);
}

public CaseView(Context c, int resId, DisplayMetrics metrics) {
    super(c);

    this.positionTop = metrics.heightPixels / 2 - mHeightCase / 2;
    int weightRest = metrics.widthPixels - 3 * mHeightCase;
    this.widthBetweenCase = weightRest / 4;
    this.positionLeftOne = widthBetweenCase;
    this.positionLeftTwo = (widthBetweenCase * 2) + mHeightCase;
    this.positionLeftThree = (widthBetweenCase * 3) + mHeightCase * 2;
    firstTime = true;

    mPaint1 = new Paint();
    // mPaint1.setAntiAlias(true);
    // mPaint1.setDither(true);
    mPaint1.setColor(Color.TRANSPARENT);
    mPaint1.setStyle(Paint.Style.STROKE);
    mPaint1.setStrokeWidth(60);

    mPaint2 = new Paint();
    // mPaint2.setAntiAlias(true);
    // mPaint2.setDither(true);
    mPaint2.setColor(Color.TRANSPARENT);
    mPaint2.setStyle(Paint.Style.STROKE);
    mPaint2.setStrokeWidth(60);

    // create a square
    mBitmap1 = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < 100; j++) {
            mBitmap1.setPixel(i, j, Color.parseColor(colorGold));
        }

    }
    mBitmap2 = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < 100; j++) {
            mBitmap2.setPixel(i, j, Color.parseColor(colorGold));
        }

    }

    mCanvas1 = new Canvas(mBitmap1);
    mCanvas2 = new Canvas(mBitmap2);
    mPath1 = new Path();
    mPath2 = new Path();
    mBitmapPaint1 = new Paint(Paint.DITHER_FLAG);
    mBitmapPaint2 = new Paint(Paint.DITHER_FLAG);
    mBitmapPaint3 = new Paint(Paint.DITHER_FLAG);
    IdImage = resId;
    if (_scratch1 == null) {
        _scratch1 = BitmapFactory.decodeResource(getResources(), IdImage);
    }
    if (_scratch2 == null) {
        _scratch2 = BitmapFactory.decodeResource(getResources(), IdImage);
    }

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

}

@Override
protected void onDraw(Canvas canvas) {
    Log.v("", "onDraw");

    canvas.drawColor(Color.WHITE);
    // first case
    canvas.drawBitmap(_scratch1, positionLeftOne, positionTop, null);
    canvas.drawBitmap(mBitmap1, positionLeftOne, positionTop,
            mBitmapPaint1);
    // canvas.drawBitmap(mBitmap1, null, new Rect(0,0,100,100),
    // mBitmapPaint1);

    // second case
    canvas.drawBitmap(_scratch2, positionLeftTwo,
            positionTop, null);
    canvas.drawBitmap(mBitmap2, positionLeftTwo,
            positionTop, mBitmapPaint2);

    // mBitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

    if ((mX < mHeightCase + positionLeftOne && mX >= positionLeftOne)
            && (mY < positionTop + mHeightCase && mY >= positionTop)) {
        // Log.v("onDraw", "x:" + mX + "/y:" + mY);
        mPaint1.setMaskFilter(null);
        mPath1.reset();
        Log.v("first case","clear at"+mX);
        mPaint1.setXfermode(new PorterDuffXfermode(Mode.CLEAR));

        // mBitmap.setPixel((int) mY,(int) mX, Color.TRANSPARENT);
        // mBitmap1.eraseColor(Color.TRANSPARENT);
        mCanvas1.setBitmap(mBitmap1);

        canvas.drawBitmap(mBitmap1, positionLeftOne, positionTop, mBitmapPaint1);
        invalidate();

    } else if ((mX < positionLeftTwo+mHeightCase && mX >= positionLeftTwo)
            && (mY < positionTop + mHeightCase && mY >= positionTop)) {
        // Log.v("onDraw", "x:" + mX + "/y:" + mY);
        mPaint2.setMaskFilter(null);
        mPath2.reset();
        mPaint2.setXfermode(new PorterDuffXfermode(Mode.CLEAR));

        // mBitmap.setPixel((int) mY,(int) mX, Color.TRANSPARENT);

        mCanvas2.setBitmap(mBitmap2);

        canvas.drawBitmap(mBitmap2, positionLeftTwo, positionTop, mBitmapPaint2);
        invalidate();

    } else {
        mPaint1.setXfermode(null);
        mPaint2.setXfermode(null);
    }

    super.onDraw(canvas);

    int pixelColor = mBitmap1.getPixel(50, 50);
    int red = Color.red(pixelColor);
    int green = Color.green(pixelColor);
    Log.v("red", "red:" + red + " /green:" + green);

    //invalidate();
}

private Bitmap prepareBitmap(Drawable drawable, int width, int height) {
    Bitmap bitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);
    drawable.setBounds(0, 0, width, height);
    Canvas canvas = new Canvas(bitmap);
    drawable.draw(canvas);
    return bitmap;
}

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

private void touch_start(float x, float y) {
    mPath1.reset();
    mPath1.moveTo(x, y);
    mPath2.reset();
    mPath2.moveTo(x, y);
    mX = x;
    mY = y;
}

private void touch_move(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);

    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mPath1.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mPath2.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;
    }
}

private void touch_up() {
    mPath1.lineTo(mX, mY);
    mPath2.lineTo(mX, mY);
    // commit the path to our offscreen
    mCanvas1.drawPath(mPath1, mPaint1);
    mCanvas2.drawPath(mPath2, mPaint2);
    // kill this so we don't double draw
    mPath1.reset();
    mPath2.reset();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();
    Log.v("onTouchEvent", "x:" + x + "/y:" + y);

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        if ((mX < positionLeftOne+mHeightCase && mX >= positionLeftOne)
                && (mY < positionTop + mHeightCase && mY >= positionTop)) {
            mPath1.reset();
            mPaint1.setMaskFilter(null);
            mPaint1.setStrokeWidth(90);
            mPaint1.setXfermode(new PorterDuffXfermode(Mode.CLEAR));

            // mCanvas1.draw(x, y, 10, mPaint1);
            isErase = true;
        } else {
            mPaint1.setXfermode(null);
            isErase = false;
        }

        touch_start(x, y);
        invalidate();
        break;
    case MotionEvent.ACTION_MOVE:
        if (isErase) {
            mCanvas1.drawCircle(x, y, 20, mPaint1);
        }
        touch_move(x, y);
        invalidate();
        break;
    case MotionEvent.ACTION_UP:
        if (isErase) {
            mCanvas1.drawCircle(x, y, 20, mPaint1);
        }
        touch_up();
        invalidate();
        break;
    }
    return true;
      }

         }

A: Not quite sure what your actual question is.
If you simply wanna reach a view as in the image you'd be better off simply having a view in XML.
Create a horizontal LinearLayout, with 3 custom squares included and use the android:layout_weight attribute to let them fill up the space by themselves.


text:
Q: PHP code inside Joomla Protostar template can somebody explain this section I am learning Joomla template development by studying and reverse engineering the default Joomla Protostar template. I understand about 80% of what is going on and through learning the basics of php I have been able to replicate it. However, I do not understand what the following chunk of code is doing (it is right at the top of the template after defined('_JEXEC') or die;
// Getting params from template
$params = JFactory::getApplication()->getTemplate(true)->params;

$app = JFactory::getApplication();
$doc = JFactory::getDocument();
$this->language = $doc->language;
$this->direction = $doc->direction;

 // Detecting Active Variables
$option   = $app->input->getCmd('option', '');
$view     = $app->input->getCmd('view', '');
$layout   = $app->input->getCmd('layout', '');
$task     = $app->input->getCmd('task', '');
$itemid   = $app->input->getCmd('Itemid', '');
$sitename = $app->getCfg('sitename');

if($task == "edit" || $layout == "form" )
 {
$fullWidth = 1;
}
else
{
$fullWidth = 0;
}

A few things I dont get are...

*

*What are these variables such as "$task" since I dont see that they are set as a parameter

*Why arent these variables just included like the others and what is $app->input all about?

A: $option   = $app->input->getCmd('option', '');
$view     = $app->input->getCmd('view', '');
$layout   = $app->input->getCmd('layout', '');
$task     = $app->input->getCmd('task', '');
$itemid   = $app->input->getCmd('Itemid', '');

These calls look through the various global variables $_POST,$_GET,$_SESSION etc to see if those variables are defined ($_POST['task'], $_GET['task'], etc). If none exist return the default (the second argument).
$app->input is an object of joomla's input class (like JRequest, JInput or similar). That class is the one that does the actual work of looking through the global variables. You could change out getCmd for like getString, but getCmd might do other filtering that getString does not. You would have to look at the core files (request.php,input.php etc) to see what it actually does.
you can do the same thing like below:
$input = new JInput();
//get option or if none use the default 'com_users'
$option = $input->getString("option","com_users");

EDIT
As to your question about MVC:
No this is not part of the MVC. This is just joomla providing an easy way of filtering incoming data.
MVC is the abstraction of data(Model), View, and Controller parts of an application. You can see this in the components. Look at the com_users component or any of other components that come with joomla.
You will see that the models manipulate the data, the view only prints out the data (and the correct html,json what have you for that view), while the control just controls the flow.
Each part should only do the work that deals with its area. For instance the code for the View should not be doing database calls, getting data from a web service, etc. This is the job of the Model. The View should only get the data from the Model, which should be in the format that the view needs, and then print it out.
This is not to say YOU CAN'T do another parts work in a different part, it's just that you should let/build each part do the work its supposed to do.


text:
Q: Diagnose brightness control Brightness control on my laptop does not work, how can I diagnose if it's unsupported, or a bug? And if it is a bug, what do I include in the bug report?
UPDATE
Thank you for all the responses, specially @Guandalino for the bounty. But unfortunately the laptop in question is no longer functional due to an accident involving water. And as such I cannot actively participate and try the out the potential solutions.
Those still interested in this question, please participate in this discussion at Ask Ubuntu Meta.

A: There is a step-by-step troubleshooting guide on the wiki.

A: Check or dig around your laptop vendors website to see if they have any useful information relating dianosing the control.
If the vendor has forum, try seek information there also. Please add your laptop model detail as part of the post so we know which product and model you are seeking support on.


text:
Q: How to switch row value with column? I have a table which stores my data like this:

ID   Name   Value
1    Tag1   20
2    Tag2   30
3    Tag3   40

I wanna display the values for each tag like this:

ID  Tag1  Tag2  Tag3
1   20    30    40

I tried this for one column:
SELECT
    ID
   ,Value AS Tag1
FROM
    dbo.TableLogger
WHERE
    (Name = 'Tag1')

How could I do for the rest of columns?

A: SELECT ID,
[Tag1], [Tag2], [Tag3]
FROM
(SELECT ID, Value,Name
    FROM TableLogger) AS SourceTable
PIVOT
(
MAX(Value)
FOR Name IN ([Tag1], [Tag2], [Tag3])
) AS PivotTable;


text:
Q: Importing Custom Setting Records I am attempting to migrate a custom setting record from one sandbox org to another. I have successfully exported the custom setting record (~150 fields) from org1 to a .csv file. When importing into org 2, I am able to map all of the fields as expected.  However, when running the import I have receiving the following error:
FIELD_INTEGRITY_EXCEPTION:field integrity exception: SetupOwnerId (id value of incorrect type):SetupOwnerId --

I have used both dataloader.io and the Data Import Wizard from the Salesforce Setup menu - in both situations I am received the same error. I have also tried both inserting and upserting (created the custom setting record but left all of its fields blank) - in both situations I am received the same error. I have also tried adding a SetupOwnerId column to the .csv file but there does not appear to be a field to map this to. The custom setting itself is public, a List type and is not a part of a managed package.
Has anyone encountered this issue or know of a way to avoid this?

A: I think these two references from Salesforce Help on Custom Settings provide the back up for my comments. One of them is as follows:

If you're thinking of using List Custom Settings, consider using Custom Metadata Types instead. Unlike with List Custom Settings, you can migrate the records of Custom Metadata Types using Packages or Metadata API tools.

Which implies that you can't migrate List Custom Settings which of course is true.
Additionally, and I believe this is the clincher:

Only custom settings definitions are included in packages, not data. If you need to include data, you must populate the custom settings using a standard Apex or API script run by the subscribing organization after they have installed the package.

The above would seem to apply to production orgs as well as packages.


text:
Q: Azure AD getting wrong token version My application is based on this example
I'm receiving token in my wpf application form login and password like this:
result = await _app.AcquireTokenByUsernamePasswordAsync(Scopes, username, securePassword);

then I want to access to my secured web api.
But when I try to access I get

AADSTS70002: Error validating credentials. AADSTS500137: The token
  issuer doesn't match the api version: A version 1 token cannot be used
  with the v2 endpoint. Trace ID: 42aaa5f8-0a2c-4c3f-a593-1676fd662700
  Correlation ID: efe97d3a-ca2f-4dfe-a50c-5c3f4accde9a Timestamp:
  2019-01-20 15:52:16Z

here
AuthenticationResult result = application.AcquireTokenOnBehalfOfAsync(scopes.Except(_scopesRequestedByMsalNet), userAssertion).GetAwaiter().GetResult();

What I just found out is that AcquireTokenOnBehalfOfAsync gives v1 or v2 for different registered native applications. I cannot find the difference in configurations on azure between the 2 apps.

A: In the Azure portal, the App registrations (Preview) is to register an app in the v2 endpoint, the App registrations is to register an app in the v1 endpoint.
The v1 authorization endpoint is like:
> https://login.microsoftonline.com/tenantid/oauth2/authorize?

v1 token endpoint:
https://login.microsoftonline.com/tenantid/oauth2/token

The v2 authorization endpoint is:
https://login.microsoftonline.com/tenantid/oauth2/v2.0/authorize

v2 token endpoint is:
https://login.microsoftonline.com/tenantid/oauth2/v2.0/token

A: I got the same error, finally i figured it out. If you add the client app from Azure AD app registration preview it will give you the v1.0 access token, I created a new client using https://apps.dev.microsoft.com/, it is returning v2.0 end point. At least it worked for me.
Refer picture below, My angular app under converged applications giving me v2.0 token & traffic-lightapp-test under azure ad application is giving me v1.0 token

A: Finally got it work.
So, what we have:
Native client (name: WpfApp), web api (name: WebApiApp)
Now we want to get access token using login, password and scopes!
Assume our config is:
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}/v2.0"/>
<add key="ida:Tenant" value="organizations"/>
<add key="ida:ClientId" value="xxx-xxx-xxx-xxx"/>
<add key="todo:TodoListScope" value="https://ourdomain.onmicrosoft.com/WebApiApp/access_as_user"/>

To make it work you need to set in WpfApp manifest (not just in WebApiApp manifest) accessTokenAcceptedVersion:2


text:
Q: Как обнаружить цепочку редиректов? На сайте есть куча редиректов, которые размазаны по php роутингу. И возникают ситуации вроде

/site/loop1 > /site/loop2
/site/loop2 > /site/loop3
/site/loop3 > /site/loop4
/site/loop4 > /site/loop5
/site/loop5 > /site/loop6

Я отдаю себе отчётность в том что перед редиректом возможно "что-то" происходит(в сессию пишется или еще что). Но от этого явно нужно избавляться, чтоб в конечном итоге получился прямой редирект

/site/loop1 > /site/loop6

Благо хоть все редиректы сделанны через обёртку, некую функцию redirect, в которой я бы хотел складывать редиректы в стек и если формировалась цепочка. На конечной точке выхода, мне она куда-то писалась(например в базу данных). Для дальнейшего распутывания этого клубка.
Пока что в голову приходит только добавлять в сессию $_SERVER['HTTP_REFERER'] при каждом редиректе и анализировать после выхода из цепочки.
Как вообще это правильно огранизовать, чтоб я велосипедов не наделал.

A: Я бы попробовал следующий метод, возможно он окажется рабочим:

*

*Внутри функции redirect создаем или добавляем в конец обособленной
cookie URL редиректа. Например, при третьем редиректе будет уже
такое значение в cookie: "/site/loop1;/site/loop2;/site/loop3"

*При конечном скрипте приложения (перед отдачей ответа клиенту)
    проверяйте в ответе наличие заголовка "Location". Если его нет, то
    данное значение cookie записывайте в БД любым удобным способом и
    обнуляйте эту cookie

*...

*Profit!

A: Напишите плагин, например для Chrome достаточно просто это сделать, и при открытии на одной из вкладок нужного сайта следите за эволюцией страницы.
Это если редирект отправляется клиенту, а не полностью отрабатывает внутри "задней части" (бэкенд) сайта.


text:
Q: PHP times out on importing data into mysql type InnoDB database I am working on a PHP/mysql program that needs its own mysql table and I want to include a sample database for testing/learning purposes.
I want use a PHP installation script to automate the creation of the mysql table and inserting the sample database.
The latest versions of mysql now set the engine type to InnoDB and I can successfully create the mysql database using PHP - which defaults to the InnoDB type.
The problem comes when I try to import the sample database (from a csv file)  - out of 1800 records only 500 records are imported before PHP times out.
I have come up with a possible solution.

*

*Create a mysql database with MyISAM type - using CREATE TABLE $table_name ...... ENGINE=MyISAM

*Import the records from the csv file into the MyISAM table - using INSERT INTO $table_name .......

*Finally change the database type from MyISAM to InnoDB - using ALTER TABLE $table_name ENGINE = InnoDB
This three step process works MUCH faster and completes well before the PHP script times out.
I have checked the InnoDB table and data using phpmyadmin and all appears to be OK.
Can anyone find fault with this method and if so can you offer an easy solution.

A: This happens to all apache php and mysql installation. You need to up the Apache max execution time in order to make php upload large files into mysql.
I would recommend you carefully study php.ini file and understand how it's controlled in the backend.

A: The processing would be even faster if you did not do so much work.
LOAD DATA INFILE ...

will load the entire CSV file in one step, without your having to open + read + parse + INSERT each row one by one.
If you need to manipulate any of the columns, then these steps are more general, yet still much faster than either of your methods:
CREATE TABLE tmp ... ENGINE=CSV;  -- and point to your file
INSERT INTO real_table
    SELECT ... the columns, suitably manipulated in SQL
        FROM tmp;

No loop, no OPEN, no parsing.


text:
Q: How to navigate through a non recombinant binomial tree im looking to see how i can navigate through a non-recombinant binomial tree.
I have set up my tree as following:
enter image description here
def arbolno(t,S0,u,d):
S=[S0]
for i in range(1,2**(t+1)-1):
    if i%2==0:
        S.append(np.round(S[int(i/2-1)]*u,3))
    elif i%2!=0:
        S.append(np.round(S[int((i-1)/2)]*d,3))
return S

Now, I want to calculate a return from a holding period, lets say, n moments.
How can I index correctly, given my format of listing my nodes? For instance, if I define a return period of 2 moments in time, then, for instance, node number 14 would be compared with node 2.
I want to know a general formula if there is, in order to index through my list of nodes correctly.
Thanks!


text:
Q: How to get three displays on Linux Mint 21 This is a follow-up on How to get 3 monitors working in Linux Mint 18.
I am on a Dell Laptop with one HDMI output, but the cables are plugged in on a dock. I highly doubt that the laptop brand/type/version plays any role since anyone has the problem (unless they have two graphic cards in a desktop pc perhaps?).
I cannot add more than one other monitor to my Linux Mint 21, plugged in at the laptop, which has just one graphical output. Even on Ubuntu, there is just the official DisplayLink USB Graphics Software for Ubuntu for 20.04 and 22.04, but not for 21.04, though for Ubuntu, there was a fix for this to update the firmware on the dock, see Ubuntu 21.04 displaylink not working - DisplayLink Forum, taken from Ubuntu 21.04 with three external monitors - Ask Ubuntu. And that would not even work since it is needed for Linux Mint, which only builds on Ubuntu, but needs its own driver for the screens.
For Linux Mint, I found much the same problems for earlier versions, like Setting up multiple screens. - Linux Mint Forums.
(needless to say, but for anyone of you testing this, you need to restart your machine after any DisplayLink driver change)
How to get three screens/displays/monitors on Linux Mint 21?


text:
Q: How can I use media breakpoint to set number of columns in css I want my div element to displayed as a single column when the screen size is less than 537px
I don't want to use col-xs-** as the breakpoints are not where I want them.
I also don't want to use Less for this.
This is my CSS:
@media (max-width: 537px) {
.col-sm-12 {
width: 100%;
}
}

And here's my html:

PORTFOLIO

Me

Me

Me

Me

Me

Me

A: Try this code

@media (max-width: 537px) {
.custom-class {
width: 100% !important;
max-width:100% !important;
}
}


text:
Q: c# print right to left I am working with some arabic data and I want to print it from right to left
I tried this
StringFormat format = new StringFormat(StringFormatFlags.DirectionRightToLeft);
                e.Graphics.DrawString(dataToPrint, valueFont, System.Drawing.Brushes.Black, 20, 20, format);

but that makes the text to still start from the left and it makes it worse so now I can't see all the text like this:

but when I remove the format, I got this:

I need to have exactly as the second image but from right to left.
any help please?
Update 1
This is how I fill the dataToPrint object
 System.Drawing.Font valueFont = new System.Drawing.Font("Arial", 15, System.Drawing.FontStyle.Regular);
                string dataToPrint = "";
                dataToPrint += "رقم بطاقة التسويق = " + farmID.Text + Environment.NewLine;
                dataToPrint += "إسم صاخب المزرعة = " + farmOwner.Text + Environment.NewLine;
                dataToPrint += "رقم المزرعة = " + farmNumber.Text + Environment.NewLine;
                dataToPrint += "الموبايل = " + farmMobile.Text + Environment.NewLine;
                dataToPrint += "الإمارة = " + emaraNameArabic.Text + Environment.NewLine;
                dataToPrint += "المنطقة = " + areaNameArabic.Text + Environment.NewLine;
                dataToPrint += "الإقليم = " + regionNameArabic.Text + Environment.NewLine;
                dataToPrint += "مركز الإستلام = " + receivingCenterName.Text + Environment.NewLine;
                dataToPrint += "خلاص = " + khalas.Text + Environment.NewLine;
                dataToPrint += "فرض = " + fardh.Text + Environment.NewLine;
                dataToPrint += "لولو = " + otherLulu.Text + Environment.NewLine;
                dataToPrint += " خنيزي= " + khedrawi.Text + Environment.NewLine;
                dataToPrint += "بومعان = " + boumaan.Text + Environment.NewLine;
                dataToPrint += "برحي = " + barhi.Text + Environment.NewLine;
                dataToPrint += "جش خزمة = " + jeshKharma.Text + Environment.NewLine;
                dataToPrint += "رزيز = " + reziz.Text + Environment.NewLine;
                dataToPrint += "جبري = " + jabri.Text + Environment.NewLine;
                dataToPrint += "عنبرة المدينة = " + anbaretAlMadina.Text + Environment.NewLine;
                dataToPrint += " شيشي= " + shishi.Text + Environment.NewLine;
                dataToPrint += "دباس = " + dabbas.Text + Environment.NewLine;
                dataToPrint += "نبتة سيف = " + nabtetSaif.Text + Environment.NewLine;
                dataToPrint += "خضراوي = " + khedrawi.Text + Environment.NewLine;
                dataToPrint += "هلالي = " + hilali.Text + Environment.NewLine;
                dataToPrint += "مكتومي = " + maktoumy.Text + Environment.NewLine;
                dataToPrint += "نميشي = " + namishi.Text + Environment.NewLine;

Update 2
After @Reyhaneh SH answer I change the 20 to 400 and this is the result, still not from right to left

A: Both of your codes are right, but the problem is that you used 20 pixels for the X position. X specifies the location from upper-left. Try it with :
 e.Graphics.DrawString(dataToPrint, valueFont,
        System.Drawing.Brushes.Black, 200, 20, format);

You can also use any other numbers bigger than 20 pixels that is proper.


text:
Q: Core Animation and UIImageView returning to starting position I have a UIImageView that I'm moving across the screen based on a user swiping.  I accomplish this using Core Animation:
 [UIView beginAnimations:nil context:nil];
 [UIView setAnimationDuration:1.0];

 movingView.frame = theRect;

 [UIView commitAnimations];

It always starts out fine, but partway through going from its original location to the "theRect" location, it stops and the UIImageView jumps back to its starting point.  It's never at the same point.  Sometimes gets almost all the way through before jumping back, sometimes only barely moving then jumping back.  No other code is running after this.  I've tried changing the duration and it doesn't seem to matter.
If I add in:
 [UIView setAnimationDidStopSelector:@selector(completeAnimation:finished:context:)];
 [UIView setAnimationDelegate:self];

Then it actually delays until the Duration is complete and runs the selector, even if the image itself stops and returns to its starting point almost immediately.
Hopefully someone can give me some hints at what might be going on here.

A: If using autolayout, you can animate the changing of the constraint, not animating the change of the frame (because when constraints are reapplied, the original location will be restored). See Animating an image view to slide upwards for an example.


text:
Q: LazyColumn inside LazyColumn I am trying to create and list with sub list using LazyColumn with the code below
DropdownMenu(
    expanded = expandedDomain,
    onDismissRequest = { expandedDomain = false },
) {
    LazyColumn {
        items(1) {
            Checkbox(checked = false /*checkedState.value*/,
                onCheckedChange = {})
            Text(text = "$domainResponse.domains[0].name")
        }
        LazyColumn {
            items(domainResponse.domains[0].pwas) { pwas ->
                Checkbox(checked = false /*checkedState.value*/,
                    onCheckedChange = {})
                Text(text = "$pwas")
            }
        }
    }
}

Error:
@Composable invocations can only happen from the context of a @Composable function

A: Let me try to explain in parts what you should be changing.
1. Why did the error occur?

@Composable invocations can only happen from the context of a @Composable function occurred

If we peek into LazyColumn code, we can find content: LazyListScope.() -> Unit as the content parameter datatype.
This shows that the context does not have composable context.
On contrary, composables like Column/Row would have content: @Composable ColumnScope.() -> Unit/content: @Composable RowScope.() -> Unit respectively.
The @Composable shows that the content has a Composable context.
2. How to fix it?
From what I see in the code, you don't need a LazyColumn inside another LazyColumn. You would need one LazyColumn with multiple items in it from different data sources.
You can change your code like this,
LazyColumn {
    item {
        Checkbox(checked = false /*checkedState.value*/,
            onCheckedChange = {})
        Text(text = "$domainResponse.domains[0].name")
    }
    items(domainResponse.domains[0].pwas) { pwas ->
        Checkbox(checked = false /*checkedState.value*/,
            onCheckedChange = {})
        Text(text = "$pwas")
    }
    // You can have multiple lists in a single LazyColumn
    items(list2Items) { item ->
        Text(text = "$item")
    }
}

3. item vs items
Use item instead of items(1) if you have a single item as they are equivalent, but this would be more clear.
P.S:
LazyColumn uses item or items which have itemContent with composable context. Hence we can add Composables inside them.


text:
Q: ConTeXt: vertical alignment besides table I want to place a table besides some text:
\starttext
  \placetable[left,none]{}{%
    \starttable[|l|]
      \HL \VL Test \VL \SR \HL
    \stoptable
  }

  Here be some text
\stoptext

This does not look very nice, because the table starts somewhat below the text:

Inserting \blank[2cm] before the text does not seem to do anything. How can I have the table start at the same vertical position as the text?

A: If you do not need to have it aligned exactly with the baseline of the text, just add a negative multiple of line in the location key.  My personal advice is to always use the \start...\stop interface, also for placetable.  Furthermore, I recommend using Natural Tables.
\starttext
\startplacetable
  [
    location={left,none,-line},
  ]
  \startTABLE
    \NC Test \NC\NR
  \stopTABLE
\stopplacetable
Here be some text
\stoptext

A: Given the simplicity, I hope I understood the question correctly.
Why don't you use the cline command ? Is the following what you expect ?
\documentclass{article}
\begin{document}
    \begin{tabular}{|c|l}
        \cline{1-1}
        Test & Here be some text\\
        \cline{1-1}
    \end{tabular}
\end{document}


text:
Q: Explain the meaning of ' i ' in the following code import random

for i in range(5):

    print(random.randint(1, 10))

Is it the number of integers that we want to print? But we didn't specify that it's the number of integers in the code, so how does python understand?

A: The Python for construct requires a variable name between for and in. Conventional practice is to use _ (underscore) as the variable in cases where a variable is required but not actually used/relevant. Note that _ is a valid variable name.

A: for i in range(5):
  do this action

Is (the Python way of saying
"for each element in range(5)
do this action".
range(5) can be replaced by any iterable collection.
In this example the variable i is not used. We might write
for i in range(5):
  print(i)

which would print out all the values from the expression range(5).

A: As you guessed, i in that code will be the number of random integers to be printed. That is because, in python, the range constructor will generate a sequence of integers when specified in the way you are showing.
If only one argument is specified, python will assume that you want to begin by the number zero, incrementing by one unit until it reaches the number one unit below the specified argument.


text:
Q: Is there a better place to store large amounts of unused data than a the database? So the application we've got calls the API's of all the major carriers (UPS, FedEx, etc) for tracking data.
We save the most recent version of the XML feed we get from them in a TEXT field in a table in our database.
We really hardly ever (read, never so far) access that data, but have it "just in case."
It adds quite a bit of additional weight to the database. Right now a 200,000 row table is coming in at around 500MB...the large majority of which is compromised of all that XML data.
So is there a more efficient way to store all that XML data? I had thought about saving them as actual text/xml files, but we update the data every couple of hours, so wasn't sure if it would make sense to do that.

A: It has been my experience that the biggest trouble with TEXT/BLOB columns that are consistently large, is that people are not careful to prevent reading them when scanning many rows. On MyISAM, this will waste your VFS cache, and on InnoDB, it will waste your InnoDB buffer pool.
A secondary problem is that as tables get bigger, they become harder to maintain.. adding a column or index can rebuild the whole table, and a 500MB table rebuilds a lot slower than a 5MB table.
I've had good success moving things like this off into offline key/value storage such as MogileFS, and/or TokyoTyrant.
If you don't need to be crazy scalable, or you must value transactional consistency over performance, then simply moving this column into another table with a 1:1 relationship with the original table will at least require a join to blow out the buffer pool, and allow you to maintain the original table w/o having to tip-toe around the 500MB gorilla.

A: if its really unused, try:
/dev/null

A: I don't know what kind of data these XML streams contain, but maybe you can parse it and store only the pertinent info in a table or set of tables that way you can eliminate some of the XML's bloat.

A: Assuming it's data there's no particular reason not to keep it in your database (unless it's impeding your backups).   But it would be a good idea to keep it in a separate table from the actual data that you do need to read on a regular basis — just the XML, a FK back to the original table, and possibly an autonumbered PK column.

A: As a DATAbase is designed to store DATA this seems to be the logical place for it.  A couple of suggestions:

*

*Rather than storing it in a seperate table is to use a seperate database.  If the information isn't critical

*Have a look athe the compress and uncompress functions as this could reduce the size of the verbose XML.
I worked on one project where we split data between the database and file system. After this experience I vowed never again. Backups and maintenance of various production/test/dev environments turned into a nightmare.

A: Learn about OLAP techniques and data warehouses. They are probably what are you looking for.

A: Why not store them to text files, and them keep a simple path (or relative path) in the database?
We used to do something similar in the seismic industry where the bulk of the data were big arrays of floating point numbers. Much more efficient to store these as files on disk (or tape), and then only keep trace meta data (position/etc) in a RDBMS-like database (I at about the time they were porting to Oracle!). Even with the old system, the field data was always on disk and easily accessible - it was used more frequently than the array data (although, unlike in your case, this was most definitely essential!


text:
Q: TimerHandler's onTimePassed not been called I am new to andEngine and trying to create a simple game using it, but got stuck at initial stage.
I am trying to create splash screen with simple animation using andEngine's TimerHandler, but seems that after registerUpdateHandler it does not execute onTimePassed.
below is my code
public void createScene() {
    System.out.println("***************");
   registerUpdateHandler(new TimerHandler(INIT_WAIT, new ITimerCallback() {
        @Override
        public void onTimePassed(TimerHandler pTimerHandler) {
           System.out.println("onTimePassed");
        }
    }));
}


text:
Q: upload data to redshift using nodejs I followed the link https://walkingtree.tech/loading-data-to-redshift-using-nodejs/ and follow the step that creates an index.js file.
However, I don't understand the code app.post('/',)
The code that i modify is as below
app.post('/', function (request, response) {
// console.log(request.body);
// var body = [];
// var body = JSON.stringify(request.body);
// body.push(request.body.test) ;
var file_name = 'items.txt';
// csvbody = [Object.values(request.body)];
// console.log(body);
csvbody = ["abc","lalala"];
console.log(csvbody);

is the syntax correct that csvbody = ["abc","lalala"]; to upload to s3 ? and the local host 3001 shown that cannot get /. What should I do further?


text:
Q: How to modify Powerpoint with Office.Js APIs I'm looking for Office.js Powerpoint add-in apis that can modify slide content properties (e.g. change all font to Calibri).
The .load() and .sync() methods to read properties (font size , color, position) of ppt content are not documented very clearly and I could not find the list of options that can be passed to the .load() method in the docs
eg: calling .load("slides") along with the .sync() loads the slides property.
context.presentation.load("slides");
await context.sync();
I'm looking for all the possible arguments of the load() methods, and all the different properties that I can fetch.

A: We have been adding APIs to the PowerPoint-specific JavaScript library, but we don't yet have the detailed content modification you're looking for.
There is a guidance article about load and sync (among other things) at Using the application-specific API model. For a good understanding of these methods, I also recommend Building Office Add-ins with Office.js.
You can add content to PowerPoint with the Office Common APIs. See here for the distinction between the Common and application-specific libraries and links to more information.


text:
Q: ES6 - Convert from 'require' to 'import' If the alternative to:
var Foo = require('foo');

is:
import Foo from 'foo';

What is the alternative to:
var Bar = require('foo').batz

Could it be:
import {batz}  from 'foo' ?

A: Nearly. It does however depend on how you are exporting them.

*

*named exports (export var batz = …):
import {batz as Bar} from 'foo';

*default-exported object (export default {batz: …};) - should not be used:
import Foo from 'foo';
var Bar = Foo.batz;


text:
Q: CSS Blur Overlay Как создать такой эффект в CSS?

A: Используется не самое сложное CSS свойство filter.
Пока НЕ рекомендую писать без префиксов, так что всегда добавляйте их.
filter: blur(ваше значение в пикселях)

body {
  background: url('https://images.unsplash.com/photo-1486723312829-f32b4a25211b?dpr=2&auto=format&fit=crop&w=1500&h=1000&q=80&cs=tinysrgb&crop=&bg=') no-repeat center center fixed;
  background-size: cover;
}

.blur {
  background: url('https://images.unsplash.com/photo-1486723312829-f32b4a25211b?dpr=2&auto=format&fit=crop&w=1500&h=1000&q=80&cs=tinysrgb&crop=&bg=') no-repeat center center fixed;
  background-size: cover;
  overflow: hidden;
  filter: blur(13px); /*тот самый эффект blur который нужен*/
  -webkit-filter: blur(13px);
  position: absolute;
  height: 300px;
  top: -50px;
  left: -50px;
  right: -50px;
  bottom: -50px;
}

.widget {
  border-top: 2px solid rgba(255, 255, 255, .5);
  border-bottom: 2px solid rgba(255, 255, 255, .5);
  height: 150px;
  width: 80%;
  overflow: hidden;
}

.center {
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

/*  не обязательно  */

.text {
  height: 200px;
  width: 340px;
}

.text h1 {
  text-align: center;
  text-shadow: 1px 1px rgba(0, 0, 0, .1);
  color: #ffffff;
  margin-top: 57px;
  font-family: 'Lora', serif;
  font-weight: 700;
  font-size: 38px;
}

.text p {
  text-align: center;
  color: #ffffff;
  text-shadow: 1px 1px rgba(0, 0, 0, .1);
  margin-top: 0px;
  font-family: 'Lato', serif;
  font-weight: 400;
  font-size: 22px;
}

какой то текст

тут можно кликать :)


text:
Q: Error while passing a private data member as default argument to a public method of that class I think the title says it all. The error MSVS showing is

a nonstatic member reference must be relative to a specific object

My code:
struct Node
{
    Node(size_t id, int length, int size);
    size_t id_;
    int length_;
    std::vector<Node*> children_;
};

class SuffixTree
{
public:
    SuffixTree();
    void printSuffixes();
    void printSuffixes(Node* current = root_);    // ERROR
    ~SuffixTree();
private:
    Node *root_;
};

There are a few more methods similar to these such that I want the user to call these methods from main but since root_ is private, I had to overload all those methods and the user now calls the overloaded methods instead. The definition of these methods are simply like:
void SuffixTree::printSuffixes()
{
    printSuffixes(root_);
}

Any solution?
Edit:
void SuffixTree::printSuffixes(Node* current)
{
    if (current == nullptr)
        return;
    if (current->length_ == -1)
        std::cout << "leaf" << std::endl;
    for (size_t i = 0; i < current->children_.size(); ++i)
        printSuffixes(current->children_[i]);
}

A: Default arguments have quite a few restrictions.
Instead, consider using nullptr as the default:
void SuffixTree::printSuffixes(Node* current = nullptr)
{
    if (current == nullptr)
        current = root_;
    // ...
}


text:
Q: How to get the excerpt of a page before more tag? I have many pages in my wp installation. All I want is to be able to display the excerpt of any page, also on any page (before more tag). How do I go about it?
I was fetching the content of the current (front) page through this code:
global $more;
$temp = $more;
$more = false;
echo get_the_content( '' );
$more = $temp;

(I use these lines in my front page template)
But I have no idea of how do I fetch the content of any page. Maybe I need to do manipulations with add~/remove_filter changing the page id/slug/title/etc?

A: Another way to get the excerpt, by that I mean the text before the <!--more--> tag, is to use the following function: get_extended()
//somewhere in the loop...
global $post;
$content = get_extended( $post->post_content );
$excerpt = $content['main'];
$main_content = apply_filters('the_content', $content['extended']);

As it says in the Wordpress codex:

The returned array has 'main' and 'extended' keys. Main has the text
  before the <!--more-->. The 'extended' key has the content after the
  <!--more--> comment.

A: The content is manipulated by the get_the_content function, and that function always assumes the current post in the Loop. You can't pass it an ID, strangely.
The easiest way to get just the bit before the more for an arbitrary post ID is:
$p = get_post(1);
$p = preg_split( '/<!--more(.*?)?-->/', $p->post_content );
echo $p[0];

There may be ways to hijack the global $post variable but unless you really need the complex manipulation of get_the_content I wouldn't bother. You can always create a near clone of that function that will allow you to pass an ID into it.


text:
Q: Parents child threads not exiting properly Need a little help regarding multithreading. I am doing some computation in separate threads in unity and rendering the result when all threads are completed.
Below is structure of my code.
         Thread 1
    |                |
Thread 1.1       Thread 1.2
    |                |
Thread 1.1.2.1   Thread 1.2.1.1
Thread 1.1.2.2   Thread 1.2.2.2
...              ...

Every time Thread 1.1 and its child (Thread 1.1.2.1..) exits properly using Join() but this is not the case with Thread 1.2; Thread 1.2.1.1.. exits without completing the code block. It looks like Join() on childThreadList is not blocking current thread in case of Thread 1.2.
Code is simple making blocks of large list and process them in parallel. I was previously having same issue that Thread 1.1 and Thread 1.2 exits in midway; reason was they were sharing same variable values when on .Start(). I make sure this is not the reason now.
Is there anything I am mistaking or missing, please advice.
Example code:
//Running in Thread 1; started from main()
private unsafe void AddSurfaceData()
{
    float* points;
    int points_length;

    float* colours;
    int colours_length;

    System.UIntPtr *indices;
    int indices_length;

    //set references for points, colours, indices, points_length, colours_length, indices_length

    ProcessTriangles(points, indices, colours, indices_length);
}

private unsafe void ProcessTriangles(float* points, System.UIntPtr *indices, float* colours, int indices_length)
{
    List<Thread> threadList = new List<Thread>();

    int currLength = 65535;
    int initialLength = 0;

    while(true)
    {
        if(currLength < indices_length)
        {
            int from = initialLength;
            int to = currLength;

            //Add surfaceData
            int surfaceIndex = surfaceData.Count-1;

            //Start thread from initialLength to currLength
            Thread thread = new Thread(() => AddTriangle(from, to, indices, points, colours, surfaceIndex));
            threadList.Add(thread);
            thread1Count++;
            thread.Name = "Thread 1."+thread1Count;
            thread.Start();

            initialLength = currLength;
            currLength += 65535;
        }

        else
        {
            int from = initialLength;
            int to = indices_length;

            //Add surfaceData
            surfaceData.Add(new ScanManager.SurfaceData(new Vector3[to-from], new Color[to-from], new int[to-from]));
            int surfaceIndex = surfaceData.Count-1;

            //Start thread from initialLength to indices_length
            Thread thread = new Thread(() => AddTriangle(from, to, indices, points, colours, surfaceIndex));
            threadList.Add(thread);
            thread1Count++;
            thread.Name = "Thread 1."+thread1Count;
            thread.Start();

            break;
        }
    }

    foreach(Thread thread in threadList)
    {
       thread.Join();
    }
}

private unsafe void AddTriangle(int fromLength, int toLength, System.UIntPtr *indices, float* points, float* colours, int surfaceIndex)
{
    List<Thread> childThreadList = new List<Thread>();

    int initialLength = fromLength;
    int currLength = 21000+initialLength;
    int index = surfaceIndex;
    int indicesLength = toLength;

    while(true)
    {
        if(currLength < indicesLength)
        {
            int from = initialLength;
            int to = currLength;

            //Start thread from initialLength to currLength
            Thread childThread = new Thread(() => AddTriangleData(from, to, indices, points, colours, index));
            childThreadList.Add(childThread);
            thread2Count++;
            childThread.Name = Thread.CurrentThread.Name+".2."+thread2Count;
            childThread.Start();

            initialLength = currLength;
            currLength += 21000;
        }

        else
        {
            int from = initialLength;
            int to = indicesLength;

            //Start thread from initialLength to indices_length
            Thread childThread = new Thread(() => AddTriangleData(from, to, indices, points, colours, index));
            childThreadList.Add(childThread);
            thread2Count++;
            childThread.Name = Thread.CurrentThread.Name+".2."+thread2Count;
            childThread.Start();

            break;
        }
    }

   foreach(Thread childThread in childThreadList)
   {
     childThread.Join();
   }
}

private unsafe void AddTriangleData(int fromLength, int toLength, System.UIntPtr *indices, float* points, float* colours, int surfaceIndex)
{
    for(int i=fromLength; i<toLength; i+=3)
    {
        //AddTriangleVertex (i)
        //AddTriangleVertex (i+1)
        //AddTriangleVertex (i+2)
    }
}