问:
How can i keep adding images to pictureBox1 when cropping and adding items to the listBox1 if the flag saveRectangles is false?
This is a link to the winforms project from my onedrive:

https://1drv.ms/u/s!AmVw2eqP6FhB4h01pNXIMlqdZJk_?e=wSGaRx

```<code>using Newtonsoft.Json;
using Ookii.Dialogs.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace Image_Crop
{
    public partial class Form1 : Form
    {
        Rectangle rect;
        int pixelsCounter = 0;
        Color SelectedColor = Color.LightGreen;
        List<DrawingRectangle> DrawingRects = new List<DrawingRectangle>();
        Bitmap rectImage;
        int saveRectanglesCounter = 1;
        bool drawBorder = true;
        bool clearRectangles = true;
        bool saveRectangles = true;
        //bool drawnNewRectangle = false; // To think how to work with this flag bool variable
        // where to use it how and how to solce this problem !!!!!
        string rectangleName;
        Dictionary<string, string> FileList = new Dictionary<string, string>();
        string selectedPath;
        int x, y;
        private bool crop = false;

        public Form1()
        {
            InitializeComponent();

            textBox1.Text = Properties.Settings.Default.ImageToCropFolder;
            textBox2.Text = Properties.Settings.Default.CroppedImagesFolder;

            selectedPath = textBox2.Text;

            if (textBox1.Text != "")
            {
                Bitmap bmp = new Bitmap(Image.FromFile(textBox1.Text),
                    pictureBox2.Width, pictureBox2.Height);
                pictureBox2.Image = bmp;
            }

            checkBoxDrawBorder.Checked = true;
            checkBoxClearRectangles.Checked = true;
            checkBoxSaveRectangles.Checked = true;

            if (selectedPath != "" && selectedPath != null)
            {
                if (System.IO.File.Exists(Path.Combine(selectedPath, "rectangles.txt")))
                {
                    string g = System.IO.File.ReadAllText(Path.Combine(selectedPath, "rectangles.txt"));
                    g = g.Remove(0, 32);

                    FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
                    listBox1.DataSource = FileList.Keys.ToList();
                    label2.Text = listBox1.Items.Count.ToString();
                    listBox1.SelectedIndex = listBox1.Items.Count - 1;
                }
                else
                {
                    label2.Text = "0";
                }
            }
            else
            {
                label2.Text = "0";
            }

            if ((selectedPath != "" && selectedPath != null) && textBox1.Text != "")
            {
                crop = true;
            }
            else
            {
                crop = false;
            }
        }

        public class DrawingRectangle
        {
            public Rectangle Rect => new Rectangle(Location, Size);
            public Size Size { get; set; }
            public Point Location { get; set; }
            public Control Owner { get; set; }
            public Point StartPosition { get; set; }
            public Color DrawingcColor { get; set; } = Color.LightGreen;
            public float PenSize { get; set; } = 3f;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || crop == false) return;

            x = 0;
            y = 0;

            if (pictureBox2.Image != null && selectedPath != null)
            {
                if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
                {
                    DrawingRects.Add(new DrawingRectangle()
                    {
                        Location = e.Location,
                        Size = Size.Empty,
                        StartPosition = e.Location,
                        Owner = (Control)sender,
                        DrawingcColor = SelectedColor
                    });
                }
            }
        }

        private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
        {
            int X = e.X;
            int Y = e.Y;

            if (e.Button != MouseButtons.Left || crop == false) return;

            if ((X >= 0 && X <= pictureBox2.Width) && (Y >= 0 && Y <= pictureBox2.Height))
            {
                if (pictureBox2.Image != null && selectedPath != null && DrawingRects.Count > 0)
                {
                    if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
                    {
                        x = e.X;
                        y = e.Y;

                        var dr = DrawingRects[DrawingRects.Count - 1];
                        if (e.Y < dr.StartPosition.Y) { dr.Location = new Point(dr.Rect.Location.X, e.Y); }
                        if (e.X < dr.StartPosition.X) { dr.Location = new Point(e.X, dr.Rect.Location.Y); }

                        dr.Size = new Size(Math.Abs(dr.StartPosition.X - e.X), Math.Abs(dr.StartPosition.Y - e.Y));
                        pictureBox2.Invalidate();
                    }
                }
            }

        }

        int count = 0;
        private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || crop == false) return;

            if (DrawingRects.Count > 0 && pictureBox2.Image != null && selectedPath != "")
            {
                if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
                {
                    var dr = DrawingRects.Last();
                    if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
                    {
                        rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);

                        if (saveRectangles)
                        {
                            count++;
                            rectangleName = GetNextName(Path.Combine(selectedPath, "Rectangle"), ".bmp");
                            FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
                            string json = JsonConvert.SerializeObject(
        FileList,
        Formatting.Indented
    );
                            using (StreamWriter sw = new StreamWriter(Path.Combine(selectedPath, "rectangles.txt"), false))
                            {
                                sw.WriteLine("Total number of rectangles: " + count + Environment.NewLine);
                                sw.Write(json);
                                sw.Close();
                            }

                            rectImage.Save(rectangleName);
                            saveRectanglesCounter++;
                        }

                        pixelsCounter = rect.Width * rect.Height;
                        pictureBox1.Invalidate();
                        listBox1.DataSource = FileList.Keys.ToList();
                        listBox1.SelectedIndex = listBox1.Items.Count - 1;

                        pictureBox2.Focus();
                        Graphics g = Graphics.FromImage(this.pictureBox1.Image);
                        g.Clear(this.pictureBox1.BackColor);
                    }
                }
                else
                {
                    if (clearRectangles)
                    {
                        DrawingRects.Clear();
                        pictureBox2.Invalidate();
                    }

                    x = 0;
                    y = 0;
                }
            }
        }

        string GetNextName(string baseName, string extension)
        {
            int counter = 1;
            string nextName = baseName + counter + extension;
            while (System.IO.File.Exists(nextName))
            {
                counter++;
                nextName = baseName + counter + extension;
            }
            return nextName;
        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            if (drawBorder)
            {
                ControlPaint.DrawBorder(e.Graphics, pictureBox2.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
            }

            if (pictureBox2.Image != null && selectedPath != null && DrawingRects.Count > 0)
            {
                DrawShapes(e.Graphics);
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (drawBorder)
            {
                ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
            }

            if (rectImage != null && DrawingRects.Count > 0)
            {
                var dr = DrawingRects.Last();
                e.Graphics.DrawImage(rectImage, dr.Rect);

                if (clearRectangles)
                {
                    DrawingRects.Clear();
                    pictureBox2.Invalidate();
                }
            }
        }

        private void DrawShapes(Graphics g)
        {
            if (DrawingRects.Count == 0) return;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            foreach (var dr in DrawingRects)
            {
                if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
                {
                    using (Pen pen = new Pen(dr.DrawingcColor, dr.PenSize))
                    {
                        g.DrawRectangle(pen, dr.Rect);
                    };
                }
            }
        }

        public Bitmap cropAtRect(Bitmap b, Rectangle r)
        {
            Bitmap nb = new Bitmap(r.Width, r.Height);
            using (Graphics g = Graphics.FromImage(nb))
            {
                g.DrawImage(b, -r.X, -r.Y);
                return nb;
            }
        }

        private void checkBoxDrawBorder_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxDrawBorder.Checked)
            {
                drawBorder = true;
            }
            else
            {
                drawBorder = false;
            }

            pictureBox1.Invalidate();
            pictureBox2.Invalidate();
        }

        private void checkBoxClearRectangles_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxClearRectangles.Checked)
            {
                clearRectangles = true;
            }
            else
            {
                clearRectangles = false;
            }

            pictureBox2.Invalidate();
        }

        private void checkBoxSaveRectangles_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBoxSaveRectangles.Checked)
            {
                saveRectangles = true;
            }
            else
            {
                saveRectangles = false;
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var item = ((ListBox)sender).SelectedItem;
            var val = FileList[(string)item];
            pictureBox1.Image = System.Drawing.Image.FromFile(val);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            VistaOpenFileDialog dialog = new VistaOpenFileDialog();
            {
                dialog.Filter = "Images (*.jpg, *.bmp, *.gif)|*.jpg;*.bmp;*.gif";
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = dialog.FileName;

                Properties.Settings.Default.ImageToCropFolder = dialog.FileName;
                Properties.Settings.Default.Save();

                Bitmap bmp = new Bitmap(Image.FromFile(dialog.FileName),
                    pictureBox2.Width, pictureBox2.Height);
                pictureBox2.Image = bmp;

                if(textBox1.Text != "" && textBox2.Text != "")
                {
                    crop = true;
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox2.Text = dialog.SelectedPath;
                selectedPath = dialog.SelectedPath;

                Properties.Settings.Default.CroppedImagesFolder = selectedPath;
                Properties.Settings.Default.Save();

                if (textBox1.Text != "" && textBox2.Text != "")
                {
                    crop = true;
                }
            }
        }
    }
}
</code>```

The problem is in the mouse up event i can't find the logic with the saving flag saveRectangles.

this is the saving part in the mouse up

```<code>if (saveRectangles)
                        {
                            count++;
                            rectangleName = GetNextName(Path.Combine(selectedPath, "Rectangle"), ".bmp");
                            FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
                            string json = JsonConvert.SerializeObject(
        FileList,
        Formatting.Indented
    );
                            using (StreamWriter sw = new StreamWriter(Path.Combine(selectedPath, "rectangles.txt"), false))
                            {
                                sw.WriteLine("Total number of rectangles: " + count + Environment.NewLine);
                                sw.Write(json);
                                sw.Close();
                            }

                            rectImage.Save(rectangleName);
                            saveRectanglesCounter++;
                        }
</code>```

if the checkBox checkBoxSaveRectangles is not checked when running the application and the folder in textBox1 is empty there are no saved images yet on the hard disk then it will throw exception at the line 201 in the MouseUp event :

```<code>Graphics g = Graphics.FromImage(this.pictureBox1.Image);
</code>```

because the image in pictureBox1 is null.

but in that case i still want it to crop images and add the images information as items to the listBox just not to save it to the hard disk.

i think that rectImage variable is also used in the pictureBox1 paint event.

anyway the goal is to be able to keep cropping even if the saving checkbox not checked and the there are no saved images in the cropped images folder.

Body:
This is a link to the winforms project from my onedrive:

https://1drv.ms/u/s!AmVw2eqP6FhB4h01pNXIMlqdZJk_?e=wSGaRx

using Newtonsoft.Json;
using Ookii.Dialogs.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace Image_Crop
{
    public partial class Form1 : Form
    {
        Rectangle rect;
        int pixelsCounter = 0;
        Color SelectedColor = Color.LightGreen;
        List<DrawingRectangle> DrawingRects = new List<DrawingRectangle>();
        Bitmap rectImage;
        int saveRectanglesCounter = 1;
        bool drawBorder = true;
        bool clearRectangles = true;
        bool saveRectangles = true;
        //bool drawnNewRectangle = false; // To think how to work with this flag bool variable
        // where to use it how and how to solce this problem !!!!!
        string rectangleName;
        Dictionary<string, string> FileList = new Dictionary<string, string>();
        string selectedPath;
        int x, y;
        private bool crop = false;

        public Form1()
        {
            InitializeComponent();

            textBox1.Text = Properties.Settings.Default.ImageToCropFolder;
            textBox2.Text = Properties.Settings.Default.CroppedImagesFolder;

            selectedPath = textBox2.Text;

            if (textBox1.Text != "")
            {
                Bitmap bmp = new Bitmap(Image.FromFile(textBox1.Text),
                    pictureBox2.Width, pictureBox2.Height);
                pictureBox2.Image = bmp;
            }

            checkBoxDrawBorder.Checked = true;
            checkBoxClearRectangles.Checked = true;
            checkBoxSaveRectangles.Checked = true;

            if (selectedPath != "" && selectedPath != null)
            {
                if (System.IO.File.Exists(Path.Combine(selectedPath, "rectangles.txt")))
                {
                    string g = System.IO.File.ReadAllText(Path.Combine(selectedPath, "rectangles.txt"));
                    g = g.Remove(0, 32);

                    FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
                    listBox1.DataSource = FileList.Keys.ToList();
                    label2.Text = listBox1.Items.Count.ToString();
                    listBox1.SelectedIndex = listBox1.Items.Count - 1;
                }
                else
                {
                    label2.Text = "0";
                }
            }
            else
            {
                label2.Text = "0";
            }

            if ((selectedPath != "" && selectedPath != null) && textBox1.Text != "")
            {
                crop = true;
            }
            else
            {
                crop = false;
            }
        }

        public class DrawingRectangle
        {
            public Rectangle Rect => new Rectangle(Location, Size);
            public Size Size { get; set; }
            public Point Location { get; set; }
            public Control Owner { get; set; }
            public Point StartPosition { get; set; }
            public Color DrawingcColor { get; set; } = Color.LightGreen;
            public float PenSize { get; set; } = 3f;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || crop == false) return;

            x = 0;
            y = 0;

            if (pictureBox2.Image != null && selectedPath != null)
            {
                if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
                {
                    DrawingRects.Add(new DrawingRectangle()
                    {
                        Location = e.Location,
                        Size = Size.Empty,
                        StartPosition = e.Location,
                        Owner = (Control)sender,
                        DrawingcColor = SelectedColor
                    });
                }
            }
        }

        private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
        {
            int X = e.X;
            int Y = e.Y;

            if (e.Button != MouseButtons.Left || crop == false) return;

            if ((X >= 0 && X <= pictureBox2.Width) && (Y >= 0 && Y <= pictureBox2.Height))
            {
                if (pictureBox2.Image != null && selectedPath != null && DrawingRects.Count > 0)
                {
                    if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
                    {
                        x = e.X;
                        y = e.Y;

                        var dr = DrawingRects[DrawingRects.Count - 1];
                        if (e.Y < dr.StartPosition.Y) { dr.Location = new Point(dr.Rect.Location.X, e.Y); }
                        if (e.X < dr.StartPosition.X) { dr.Location = new Point(e.X, dr.Rect.Location.Y); }

                        dr.Size = new Size(Math.Abs(dr.StartPosition.X - e.X), Math.Abs(dr.StartPosition.Y - e.Y));
                        pictureBox2.Invalidate();
                    }
                }
            }

        }

        int count = 0;
        private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left || crop == false) return;

            if (DrawingRects.Count > 0 && pictureBox2.Image != null && selectedPath != "")
            {
                if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
                {
                    var dr = DrawingRects.Last();
                    if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
                    {
                        rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);

                        if (saveRectangles)
                        {
                            count++;
                            rectangleName = GetNextName(Path.Combine(selectedPath, "Rectangle"), ".bmp");
                            FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
                            string json = JsonConvert.SerializeObject(
        FileList,
        Formatting.Indented
    );
                            using (StreamWriter sw = new StreamWriter(Path.Combine(selectedPath, "rectangles.txt"), false))
                            {
                                sw.WriteLine("Total number of rectangles: " + count + Environment.NewLine);
                                sw.Write(json);
                                sw.Close();
                            }

                            rectImage.Save(rectangleName);
                            saveRectanglesCounter++;
                        }

                        pixelsCounter = rect.Width * rect.Height;
                        pictureBox1.Invalidate();
                        listBox1.DataSource = FileList.Keys.ToList();
                        listBox1.SelectedIndex = listBox1.Items.Count - 1;

                        pictureBox2.Focus();
                        Graphics g = Graphics.FromImage(this.pictureBox1.Image);
                        g.Clear(this.pictureBox1.BackColor);
                    }
                }
                else
                {
                    if (clearRectangles)
                    {
                        DrawingRects.Clear();
                        pictureBox2.Invalidate();
                    }

                    x = 0;
                    y = 0;
                }
            }
        }

        string GetNextName(string baseName, string extension)
        {
            int counter = 1;
            string nextName = baseName + counter + extension;
            while (System.IO.File.Exists(nextName))
            {
                counter++;
                nextName = baseName + counter + extension;
            }
            return nextName;
        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            if (drawBorder)
            {
                ControlPaint.DrawBorder(e.Graphics, pictureBox2.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
            }

            if (pictureBox2.Image != null && selectedPath != null && DrawingRects.Count > 0)
            {
                DrawShapes(e.Graphics);
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (drawBorder)
            {
                ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
            }

            if (rectImage != null && DrawingRects.Count > 0)
            {
                var dr = DrawingRects.Last();
                e.Graphics.DrawImage(rectImage, dr.Rect);

                if (clearRectangles)
                {
                    DrawingRects.Clear();
                    pictureBox2.Invalidate();
                }
            }
        }

        private void DrawShapes(Graphics g)
        {
            if (DrawingRects.Count == 0) return;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            foreach (var dr in DrawingRects)
            {
                if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
                {
                    using (Pen pen = new Pen(dr.DrawingcColor, dr.PenSize))
                    {
                        g.DrawRectangle(pen, dr.Rect);
                    };
                }
            }
        }

        public Bitmap cropAtRect(Bitmap b, Rectangle r)
        {
            Bitmap nb = new Bitmap(r.Width, r.Height);
            using (Graphics g = Graphics.FromImage(nb))
            {
                g.DrawImage(b, -r.X, -r.Y);
                return nb;
            }
        }

        private void checkBoxDrawBorder_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxDrawBorder.Checked)
            {
                drawBorder = true;
            }
            else
            {
                drawBorder = false;
            }

            pictureBox1.Invalidate();
            pictureBox2.Invalidate();
        }

        private void checkBoxClearRectangles_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxClearRectangles.Checked)
            {
                clearRectangles = true;
            }
            else
            {
                clearRectangles = false;
            }

            pictureBox2.Invalidate();
        }

        private void checkBoxSaveRectangles_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBoxSaveRectangles.Checked)
            {
                saveRectangles = true;
            }
            else
            {
                saveRectangles = false;
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var item = ((ListBox)sender).SelectedItem;
            var val = FileList[(string)item];
            pictureBox1.Image = System.Drawing.Image.FromFile(val);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            VistaOpenFileDialog dialog = new VistaOpenFileDialog();
            {
                dialog.Filter = "Images (*.jpg, *.bmp, *.gif)|*.jpg;*.bmp;*.gif";
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = dialog.FileName;

                Properties.Settings.Default.ImageToCropFolder = dialog.FileName;
                Properties.Settings.Default.Save();

                Bitmap bmp = new Bitmap(Image.FromFile(dialog.FileName),
                    pictureBox2.Width, pictureBox2.Height);
                pictureBox2.Image = bmp;

                if(textBox1.Text != "" && textBox2.Text != "")
                {
                    crop = true;
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox2.Text = dialog.SelectedPath;
                selectedPath = dialog.SelectedPath;

                Properties.Settings.Default.CroppedImagesFolder = selectedPath;
                Properties.Settings.Default.Save();

                if (textBox1.Text != "" && textBox2.Text != "")
                {
                    crop = true;
                }
            }
        }
    }
}

The problem is in the mouse up event i can't find the logic with the saving flag saveRectangles.

this is the saving part in the mouse up

if (saveRectangles)
                        {
                            count++;
                            rectangleName = GetNextName(Path.Combine(selectedPath, "Rectangle"), ".bmp");
                            FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
                            string json = JsonConvert.SerializeObject(
        FileList,
        Formatting.Indented
    );
                            using (StreamWriter sw = new StreamWriter(Path.Combine(selectedPath, "rectangles.txt"), false))
                            {
                                sw.WriteLine("Total number of rectangles: " + count + Environment.NewLine);
                                sw.Write(json);
                                sw.Close();
                            }

                            rectImage.Save(rectangleName);
                            saveRectanglesCounter++;
                        }

if the checkBox checkBoxSaveRectangles is not checked when running the application and the folder in textBox1 is empty there are no saved images yet on the hard disk then it will throw exception at the line 201 in the MouseUp event :

Graphics g = Graphics.FromImage(this.pictureBox1.Image);

because the image in pictureBox1 is null.

but in that case i still want it to crop images and add the images information as items to the listBox just not to save it to the hard disk.

i think that rectImage variable is also used in the pictureBox1 paint event.

anyway the goal is to be able to keep cropping even if the saving checkbox not checked and the there are no saved images in the cropped images folder.


来源: stackexchange

问:
VSCode Vim Extension '*' search not properly searching whole words when '$' is taken out of Editor:WordSeparators
I have VSCode configured with the Vim v1.24.3 and PHP v1.26.11793 extensions. I've removed the '$' from the Editor:WordSeparator string to allow PHP variables that begin with '$' to be seen as whole words. When I place my cursor on a variable and type '*' to search for other instances of that variable, the search is performed without the '>' termination that would enforce the whole word search. Therefore a search for $foo will find $foobar as well, as shown in this example:

Is there a settings parameter I can change to fix this so that the search is performed on the whole word $foo?

ContentLicense: CC BY-SA 4.0


问:
sdkman and $PATH in Linux
After installing sdkman and let it install java temurin 8 and 17 and setting use to java 8, $JAVA_HOME nicely pointed to the current candidate.

But $PATH and java -version still point to the original /usr/lib/jvm/java-17-openjdk-amd64/bin. Do I have to manually modify $PATH, each time I change the current java version?

I changed the 'use' version, and $JAVA_HOME changed appropriately, but $PATH and java -version did not change.

Title: sdkman and $PATH in Linux


问:
reactjs function call returns undefined even when function has value
The following client code calls a function

```<code>export async function verifyImage (image ) {

  const data = new FormData();
  ...

    let moderated;

          await verifyImage (image).then(function (response) {
            moderated = response;
          });

          console.log(moderated); //why is this always undefined?
</code>```

and the function code is

```<code>  await axios({
    method: 'post',
    url:'https://api.someapi.com/1.0/check.json',
    data: data,
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  .then(function (response) {
    // on success: handle response
    console.log("resp in moderate pics")
    console.log(sendVerifyResponse (response.data))
    const moderated = sendVerifyResponse (response.data);
    return moderated;
  })
  .catch(function (error) {
    // handle error
    if (error.response) console.log(error.response.data);
    else console.log(error.message);
    return false;
  });
</code>```

The following log shows the correct values

```<code>console.log(sendVerifyResponse (response.data))
</code>```

But return moderated; is always undefined.

Body:
The following client code calls a function

export async function verifyImage (image ) {

  const data = new FormData();
  ...

    let moderated;

          await verifyImage (image).then(function (response) {
            moderated = response;
          });

          console.log(moderated); //why is this always undefined?

and the function code is

  await axios({
    method: 'post',
    url:'https://api.someapi.com/1.0/check.json',
    data: data,
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  .then(function (response) {
    // on success: handle response
    console.log("resp in moderate pics")
    console.log(sendVerifyResponse (response.data))
    const moderated = sendVerifyResponse (response.data);
    return moderated;
  })
  .catch(function (error) {
    // handle error
    if (error.response) console.log(error.response.data);
    else console.log(error.message);
    return false;
  });

The following log shows the correct values

console.log(sendVerifyResponse (response.data))

But return moderated; is always undefined.


问:
How to have two touch sliders operate indepently at the same time
I have a mobile web app with two sliders a jquery roundslider and html/js slider acting as steering and throttle respectively. if I only slide one or the other then each works as expected. But use two fingers one one for each slider at the same time then the touch actions appear to interfer with each other. How can I get them to work independently at the same time.

Each slider is in its own div inside a split page. I am not using any dedicated ontouch functions just drag:function for the roundslider and oninput for the html/js slider.


问:
How to parse a CSV file in in nextjs and update my postgres prisma database with that data?
I am currently trying to create a Prisma Postgres Database with historical stock data. My workflow is as follows:
-get data from yfinance on flask server
-convert the data to a csv and send it to nextjs server
-from nextjs server, parse the csv and update my prisma database

I am able to send the data to the nextjs server, however for some reason it just won't parse correctly. Here is the code for my nextjs server:

```<code>import { prisma } from "../../../prisma/shared-client";
import { useState } from 'react';
import type { NextApiRequest, NextApiResponse } from 'next';
import { parse } from 'csv-parse';

export default async function (req: NextApiRequest, res: NextApiResponse) {

  async function processData(payload: any) {
    console.log('started')
    console.log(req.body)

    const options = {
      columns: ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Dividends', 'Stock Splits', 'ID']
    };

    // Parse the CSV data
    const parser = parse(payload, options);
    // console.log(parser)

    // Read the parsed data one chunk at a time
    let chunk: any;
    chunk = parser.read()
    console.log(chunk)
    while ((chunk = parser.read())) {
      for (const item of chunk) {
        console.log(item.ID)
        try {
          // Convert the 'Date' column to ISO 8601 format
          const isoDate = new Date(item.Date).toISOString();
          console.log(isoDate)

          // Insert a new record into the database
          await prisma.financialData.create({
            data: {
              symbol: item.ID,
              date: isoDate,
              open: item.Open,
              close: item.Close,
              high: item.High,
              low: item.Low
            }
          });
        } catch (error) {
          console.error('error:', error);
        }
      }
    }
  }

  await processData(req.body);
  console.log('done')
  res.status(200).json({ message: 'Hello, World!' });
}
</code>```

When I log req.body, the csv data shows up correctly, so I don't know why the code above is not working.

If you have any idea how I can successfully use the csv data to update my database, i would be extremely grateful.

For reference, here is my flask server which shows how I'm sending the csv file:

```<code>from flask import Flask, request, Response
from autogluon.timeseries import TimeSeriesDataFrame, TimeSeriesPredictor
import yfinance as yf
from helper_functions import Helper
import requests
from flask_cors import CORS
import csv
import tempfile

app = Flask(__name__)
CORS(app)

@app.route('/predict', methods=['POST'])
def predict():
    response = Response()
    response.headers['Access-Control-Allow-Origin'] = '*'

    data = request.get_json()
    ticker = yf.Ticker(data["ticker"])
    stock_data = ticker.history(start="2017-01-06", end="2017-04-30")
    stock_data = stock_data.assign(ID=data['ticker'])
    stock_data = stock_data.reset_index()
    stock_data['Date'] = stock_data['Date'].astype(dtype='datetime64[ns]')
    stock_data['Date'] = stock_data['Date'].dt.normalize()

    temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False)
    writer = csv.writer(temp_file)
    writer.writerow(stock_data.columns)
    writer.writerows(stock_data.values)

    stock_data_csv = stock_data.to_csv()

    headers = {
    'Content-Type': 'text/csv; charset=utf-8',  # specify that the content type is CSV
    # 'Content-Disposition': 'filename=Test.csv'
}

    # requests.post('http://localhost:3000/api/data/processData', data=stock_data_csv, headers=headers)
    with open(temp_file.name, 'r') as f:
        file_contents = f.read()

    requests.post('http://localhost:3000/api/data/processData', data=file_contents, headers=headers)

    return 'response'

if __name__ == '__main__':
    app.run()
    print('Server started')

</code>```

Body:
I am currently trying to create a Prisma Postgres Database with historical stock data. My workflow is as follows:
-get data from yfinance on flask server
-convert the data to a csv and send it to nextjs server
-from nextjs server, parse the csv and update my prisma database

I am able to send the data to the nextjs server, however for some reason it just won't parse correctly. Here is the code for my nextjs server:

import { prisma } from "../../../prisma/shared-client";
import { useState } from 'react';
import type { NextApiRequest, NextApiResponse } from 'next';
import { parse } from 'csv-parse';

export default async function (req: NextApiRequest, res: NextApiResponse) {

  async function processData(payload: any) {
    console.log('started')
    console.log(req.body)

    const options = {
      columns: ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Dividends', 'Stock Splits', 'ID']
    };

    // Parse the CSV data
    const parser = parse(payload, options);
    // console.log(parser)

    // Read the parsed data one chunk at a time
    let chunk: any;
    chunk = parser.read()
    console.log(chunk)
    while ((chunk = parser.read())) {
      for (const item of chunk) {
        console.log(item.ID)
        try {
          // Convert the 'Date' column to ISO 8601 format
          const isoDate = new Date(item.Date).toISOString();
          console.log(isoDate)

          // Insert a new record into the database
          await prisma.financialData.create({
            data: {
              symbol: item.ID,
              date: isoDate,
              open: item.Open,
              close: item.Close,
              high: item.High,
              low: item.Low
            }
          });
        } catch (error) {
          console.error('error:', error);
        }
      }
    }
  }

  await processData(req.body);
  console.log('done')
  res.status(200).json({ message: 'Hello, World!' });
}

When I log req.body, the csv data shows up correctly, so I don't know why the code above is not working.

If you have any idea how I can successfully use the csv data to update my database, i would be extremely grateful.

For reference, here is my flask server which shows how I'm sending the csv file:

from flask import Flask, request, Response
from autogluon.timeseries import TimeSeriesDataFrame, TimeSeriesPredictor
import yfinance as yf
from helper_functions import Helper
import requests
from flask_cors import CORS
import csv
import tempfile

app = Flask(__name__)
CORS(app)

@app.route('/predict', methods=['POST'])
def predict():
    response = Response()
    response.headers['Access-Control-Allow-Origin'] = '*'

    data = request.get_json()
    ticker = yf.Ticker(data["ticker"])
    stock_data = ticker.history(start="2017-01-06", end="2017-04-30")
    stock_data = stock_data.assign(ID=data['ticker'])
    stock_data = stock_data.reset_index()
    stock_data['Date'] = stock_data['Date'].astype(dtype='datetime64[ns]')
    stock_data['Date'] = stock_data['Date'].dt.normalize()

    temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False)
    writer = csv.writer(temp_file)
    writer.writerow(stock_data.columns)
    writer.writerows(stock_data.values)

    stock_data_csv = stock_data.to_csv()

    headers = {
    'Content-Type': 'text/csv; charset=utf-8',  # specify that the content type is CSV
    # 'Content-Disposition': 'filename=Test.csv'
}

    # requests.post('http://localhost:3000/api/data/processData', data=stock_data_csv, headers=headers)
    with open(temp_file.name, 'r') as f:
        file_contents = f.read()

    requests.post('http://localhost:3000/api/data/processData', data=file_contents, headers=headers)

    return 'response'

if __name__ == '__main__':
    app.run()
    print('Server started')


问:
why column order datatable can not be executed
when i want order column similarity from Levenshtein calculation result but i get error in ajax_list response

Type: mysqli_sql_exception

Message: Unknown column 'similarity' in 'order clause'

i have code in controller codeigniter3 like this
```<code>public function ajax_list()
    {
        $list = $this->article->get_datatables();
        $data = array();
        $no = $_POST['start'];
        $searchinput=$_POST['search']['value'];
        foreach ($list as $article) {
            $no++;
            $row = array();
            $row[] = $no;
            $row[] = $article->title;

            $text1   = $row[2];
            $text2  = $searchinput;
            $similarity = levenshtein($text1, $text2) / max(strlen($text1), strlen($text2));
            $result_similarity=(1 - $similarity) * 100;

            $row[] = $result_similarity;
            $data[] = $row;
        }
        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->article->count_all(),
                        "recordsFiltered" => $this->article->count_filtered(),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    }
</code>```

and i have code in models like this

```<code>    var $table = 'article';
    var $column_order = array(null,'title','result_similarity'); //set column field database for datatable orderable
    var $column_search = array('title'); //set column field database for datatable searchable

    var $order = array('title' => 'asc'); // default order
</code>```

Body:
when i want order column similarity from Levenshtein calculation result but i get error in ajax_list response

Type: mysqli_sql_exception

Message: Unknown column 'similarity' in 'order clause'

i have code in controller codeigniter3 like this

public function ajax_list()
    {
        $list = $this->article->get_datatables();
        $data = array();
        $no = $_POST['start'];
        $searchinput=$_POST['search']['value'];
        foreach ($list as $article) {
            $no++;
            $row = array();
            $row[] = $no;
            $row[] = $article->title;

            $text1   = $row[2];
            $text2  = $searchinput;
            $similarity = levenshtein($text1, $text2) / max(strlen($text1), strlen($text2));
            $result_similarity=(1 - $similarity) * 100;

            $row[] = $result_similarity;
            $data[] = $row;
        }
        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->article->count_all(),
                        "recordsFiltered" => $this->article->count_filtered(),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    }

and i have code in models like this

    var $table = 'article';
    var $column_order = array(null,'title','result_similarity'); //set column field database for datatable orderable
    var $column_search = array('title'); //set column field database for datatable searchable

    var $order = array('title' => 'asc'); // default order


问:
Strange and unusable URLs when using UIDocumentPickerViewController to access iCloud directories/files
I have an iOS application that uses UIDocumentPickerController to present the user with a dialog where they can pick the location of a directory containing files for upload

This is working just fine in most cases but if they pick a directory that is located on their iCloud account, DocumentPickerViewController returns a URL that produces unusable file URLs when enumerating the iCloud directory

Here is how I set it up:

```<code>var documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeFolder as String], in: .open)

documentPicker.delegate = self
sView.present(documentPicker, animated: true, completion: nil)
</code>```

And here is how I enumerate the files in the iCloud directory that they have chosen:

```<code>NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { (url) in

  let access = url.startAccessingSecurityScopedResource()

  var directoryContents: [URL]

  do {
    let keys : [URLResourceKey] = [.nameKey, .isDirectoryKey]

    directoryContents = try FileManager.default.contentsOfDirectory(
     at: url,
     includingPropertiesForKeys: keys)

  } catch {
      print("error \(error))")
      if access {
          url.stopAccessingSecurityScopedResource()
      }
      return
  }

  if access {
     url.stopAccessingSecurityScopedResource()
  }
}
</code>```

For each file, I pass it to FileManager to copy into the application's sandbox:

```<code>for fromURL in directoryContents {
   var lastPath = fromURL.lastPathComponent
   print("Lastpath is \(lastPath)")

   let toURL: URL = documentURL.appendingPathComponent(lastPath)

   print("fromURL - \(fromURL)")
   print("toURL \(toURL)")

   let fM = FileManager.default

   if(fM.fileExists(atPath: toURL.path)) {
        exists += 1
   } else {
        do {
         let access = url.startAccessingSecurityScopedResource()
         try fM.copyItem(at: fromURL, to: toURL)
         if access {
            url.stopAccessingSecurityScopedResource()
         }
         count += 1
        } catch {
         print("Error on file copy \(error)")
        }
    }
}
</code>```

This works just fine if the directory is on, say, an external USB drive but if I point it to iCloud, this is what I get:

```<code>fromURL - file:///Users/greg/Library/Developer/CoreSimulator/Devices/FFDED20B-B142-4FC6-BA8F-C1DC193E2AB7/data/Library/Mobile%20Documents/com~apple~CloudDocs/Savvy/SavvyLink/SmallEngineDataRepo/.Flt0002_20180913P.csv.icloud
toURL file:///Users/greg/Library/Developer/CoreSimulator/Devices/FFDED20B-B142-4FC6-BA8F-C1DC193E2AB7/data/Containers/Data/Application/167AC69D-494C-4CB1-8A36-E230C5303F30/Documents/.Flt0002_20180913P.csv.icloud
</code>```

Note the file names have a dot (.) prepended and a .iCloud postpended.  If I look in my application's sandbox I see the files in the Documents directory but the contents of the files are NOT the contents of the files on iCloud but instead look to be themselves some kind of a URL

Thanks for any insight into what is going on here and what I am missing

What I expect to happen is to be able to take the URLs returned when enumerating the files in the iCloud directory and then pass those URLs to FileManager.copyItems to copy them into my application's sandbox

As I said, this works just fine for directories located on (say) USB drives but when used for directories on iCloud it results in copying in files with very different contents than what is on the original files in iCloud and with names changed to have a "." prepended and ".iCloud" postpended

Body:
I have an iOS application that uses UIDocumentPickerController to present the user with a dialog where they can pick the location of a directory containing files for upload

This is working just fine in most cases but if they pick a directory that is located on their iCloud account, DocumentPickerViewController returns a URL that produces unusable file URLs when enumerating the iCloud directory

Here is how I set it up:

var documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeFolder as String], in: .open)

documentPicker.delegate = self
sView.present(documentPicker, animated: true, completion: nil)

And here is how I enumerate the files in the iCloud directory that they have chosen:

NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { (url) in

  let access = url.startAccessingSecurityScopedResource()

  var directoryContents: [URL]

  do {
    let keys : [URLResourceKey] = [.nameKey, .isDirectoryKey]

    directoryContents = try FileManager.default.contentsOfDirectory(
     at: url,
     includingPropertiesForKeys: keys)

  } catch {
      print("error \(error))")
      if access {
          url.stopAccessingSecurityScopedResource()
      }
      return
  }

  if access {
     url.stopAccessingSecurityScopedResource()
  }
}

For each file, I pass it to FileManager to copy into the application's sandbox:

for fromURL in directoryContents {
   var lastPath = fromURL.lastPathComponent
   print("Lastpath is \(lastPath)")

   let toURL: URL = documentURL.appendingPathComponent(lastPath)

   print("fromURL - \(fromURL)")
   print("toURL \(toURL)")

   let fM = FileManager.default

   if(fM.fileExists(atPath: toURL.path)) {
        exists += 1
   } else {
        do {
         let access = url.startAccessingSecurityScopedResource()
         try fM.copyItem(at: fromURL, to: toURL)
         if access {
            url.stopAccessingSecurityScopedResource()
         }
         count += 1
        } catch {
         print("Error on file copy \(error)")
        }
    }
}

This works just fine if the directory is on, say, an external USB drive but if I point it to iCloud, this is what I get:

fromURL - file:///Users/greg/Library/Developer/CoreSimulator/Devices/FFDED20B-B142-4FC6-BA8F-C1DC193E2AB7/data/Library/Mobile%20Documents/com~apple~CloudDocs/Savvy/SavvyLink/SmallEngineDataRepo/.Flt0002_20180913P.csv.icloud
toURL file:///Users/greg/Library/Developer/CoreSimulator/Devices/FFDED20B-B142-4FC6-BA8F-C1DC193E2AB7/data/Containers/Data/Application/167AC69D-494C-4CB1-8A36-E230C5303F30/Documents/.Flt0002_20180913P.csv.icloud

Note the file names have a dot (.) prepended and a .iCloud postpended.  If I look in my application's sandbox I see the files in the Documents directory but the contents of the files are NOT the contents of the files on iCloud but instead look to be themselves some kind of a URL

Thanks for any insight into what is going on here and what I am missing

What I expect to happen is to be able to take the URLs returned when enumerating the files in the iCloud directory and then pass those URLs to FileManager.copyItems to copy them into my application's sandbox

As I said, this works just fine for directories located on (say) USB drives but when used for directories on iCloud it results in copying in files with very different contents than what is on the original files in iCloud and with names changed to have a "." prepended and ".iCloud" postpended


问:
ReactJS : Is it possible to increment the TableHead - TableCell based on data from JSON
My Data looks in JSON as below

```<code>
{
    "ModelName": "ObjectD",
    "ElementName": "573299",
    "ParameterInfos": [{
            "Name": "Bounding",
            "Value": "1"
        }, {
            "Name": "Dat",
            "Value": null
        }, {
            "Name": "Type",
            "Value": null
        }, {
            "Name": "Struct",
            "Value": "0"
        }, {
            "Name": "Base",
            "Value": "0"
        }
    ]
}
</code>```

I'm trying to create a new table in react using the column name from json as "Name", the data changes for each ModelName

Body:
My Data looks in JSON as below

{
    "ModelName": "ObjectD",
    "ElementName": "573299",
    "ParameterInfos": [{
            "Name": "Bounding",
            "Value": "1"
        }, {
            "Name": "Dat",
            "Value": null
        }, {
            "Name": "Type",
            "Value": null
        }, {
            "Name": "Struct",
            "Value": "0"
        }, {
            "Name": "Base",
            "Value": "0"
        }
    ]
}

I'm trying to create a new table in react using the column name from json as "Name", the data changes for each ModelName


问:
Flexget does not listen to my configuration
I have flexget in docker compose and it doesn't work for me

That is, I have this configuration that downloads files from an rss and renames and moves them. But flexget doesn't do any of that

```<code>web_server:
  bind: 0.0.0.0
  port: 5050
  web_ui: yes

schedules:
  - tasks: '*'
    interval:
      minutes: 1
templates:
  transmissionrpc:
    transmission:
      host: localhost
      port: 9091
      username: admin
      password: "123456"
    clean_transmission:
      host: localhost
      port: 9091
      username: admin
      password: "123456"
      transmission_seed_limits: yes
      delete_files: no
      enabled: Yes

  tv:
    thetvdb_lookup: yes
    quality: 720p
    series:
      group:
        - Criminal Minds
        - Rick and Morty
tasks:
  Drarbg task:
    rss: http://showrss.info/user/229110.rss?magnets=true&namespaces=true&name=null&quality=null&re=null
    priority: 1
    all_series: yes
    template:
      - tv
      - transmissionrpc
    set:
      path: /downloads/complete

  sort-series:
    metainfo_series: yes
    accept_all: yes
    filesystem:
      path: /downloads/complete
      regexp: '.*\.(avi|mkv|mp4)$'
      recursive: yes
    template: tv
    series:
      settings:
        group:
          parse_only: yes
    require_field: series_name
    move:
      to: '/storage/Series/{{series_name}}'
      rename: '{{series_name}} - S{{series_season|pad(2)}}E{{series_episode|pad(2)}}'
</code>```

in the flexget.log it does not give me any error.

I've tried various configurations but it still doesn't work. I don't know what to do anymore. I've opened a help ticket on their github but no one helps me.

My docker-compose:

```<code>  flexget:
    image: wiserain/flexget:3
    volumes:
      - ${CONFIG}:/config
      - ${STORAGE}/torrents:/downloads
      - ${MEDIA}:/storage
    ports:
      - 5050:5050
    environment:
      - TORRENT_PLUGIN=transmission
      - FG_WEBUI_PASSWD=123456
    restart: unless-stopped
    links:
      - transmission
</code>```

The web_ui does not work either, that is, when I put the ip of my machine followed by :5050 it tells me that the connection has been rejected

Body:
I have flexget in docker compose and it doesn't work for me

That is, I have this configuration that downloads files from an rss and renames and moves them. But flexget doesn't do any of that

web_server:
  bind: 0.0.0.0
  port: 5050
  web_ui: yes

schedules:
  - tasks: '*'
    interval:
      minutes: 1
templates:
  transmissionrpc:
    transmission:
      host: localhost
      port: 9091
      username: admin
      password: "123456"
    clean_transmission:
      host: localhost
      port: 9091
      username: admin
      password: "123456"
      transmission_seed_limits: yes
      delete_files: no
      enabled: Yes

  tv:
    thetvdb_lookup: yes
    quality: 720p
    series:
      group:
        - Criminal Minds
        - Rick and Morty
tasks:
  Drarbg task:
    rss: http://showrss.info/user/229110.rss?magnets=true&namespaces=true&name=null&quality=null&re=null
    priority: 1
    all_series: yes
    template:
      - tv
      - transmissionrpc
    set:
      path: /downloads/complete

  sort-series:
    metainfo_series: yes
    accept_all: yes
    filesystem:
      path: /downloads/complete
      regexp: '.*\.(avi|mkv|mp4)$'
      recursive: yes
    template: tv
    series:
      settings:
        group:
          parse_only: yes
    require_field: series_name
    move:
      to: '/storage/Series/{{series_name}}'
      rename: '{{series_name}} - S{{series_season|pad(2)}}E{{series_episode|pad(2)}}'

in the flexget.log it does not give me any error.

I've tried various configurations but it still doesn't work. I don't know what to do anymore. I've opened a help ticket on their github but no one helps me.

My docker-compose:

  flexget:
    image: wiserain/flexget:3
    volumes:
      - ${CONFIG}:/config
      - ${STORAGE}/torrents:/downloads
      - ${MEDIA}:/storage
    ports:
      - 5050:5050
    environment:
      - TORRENT_PLUGIN=transmission
      - FG_WEBUI_PASSWD=123456
    restart: unless-stopped
    links:
      - transmission

The web_ui does not work either, that is, when I put the ip of my machine followed by :5050 it tells me that the connection has been rejected


问:
NuxtJS/Vue3: V-for with async api data not working properly (TS)
I am currently working on a vue 3 project together with typescript.

I have an api, that sends me an array of objects containing the details of each server.

I have a script file under /server/api/serverData.ts that fetches me this data

```<code>//we want to fetch asnyc
export default defineEventHandler(async (event) => {
  //fetch from uri using $fetch from nuxt
  const data = await $fetch("https://game.aq3d.com/api/game/ServerList");
  //return data
  return data;
});
</code>```

Here is an example output

```<code>[
  {
    "ID": 1,
    "SortIndex": 1,
    "Name": "Red Dragon",
    "HostName": "nextdragon.aq3d.com",
    "Port": 5594,
    "UserCount": 754,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "Connections": 737,
    "GEMQueueLength": 2484,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "NA"
  },
  {
    "ID": 4,
    "SortIndex": 16,
    "Name": "Localhost",
    "HostName": "localhost",
    "Port": 5591,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-07-01T15:48:00",
    "AccessLevel": 100,
    "AlertLevel": -1,
    "Status": 0,
    "Region": "NA"
  },
  {
    "ID": 7,
    "SortIndex": 4,
    "Name": "Blue Dragon",
    "HostName": "game.dragon.aq3d.com",
    "Port": 5594,
    "UserCount": 180,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "Connections": 178,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "NA"
  },
  {
    "ID": 10,
    "SortIndex": 7,
    "Name": "Black Dragon",
    "HostName": "game.dragon.aq3d.com",
    "Port": 5593,
    "UserCount": 1,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "AccessLevel": 100,
    "Connections": 1,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "NA"
  },
  {
    "ID": 11,
    "SortIndex": 8,
    "Name": "Green Dragon  [EU]",
    "HostName": "nextdragon.aq3d.com",
    "Port": 5590,
    "UserCount": 128,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "Connections": 123,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "EU"
  },
  {
    "ID": 12,
    "SortIndex": 9,
    "Name": "Gold Dragon [SEA]",
    "HostName": "nextdragon.aq3d.com",
    "Port": 5591,
    "UserCount": 57,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "Connections": 55,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "AS"
  }
]
</code>```

I have a Player Info component under /Player/Info.vue with properties

```<code><script setup lang="ts">
interface PlayerProps {
    serverName: string;
    playerAmount: number;
    // maxPlayer: number;
    // connections: number;
}

const props = defineProps<PlayerProps>();

</script>
<template>
    <div>
        <h1>Player Information</h1>
        <h2>{{ serverName }}</h2>
        <h2>{{ playerAmount }}</h2>
    </div>
</template>
</code>```

I use it inside my app.vue inside the root dir like this:

```<code><script setup lang="ts">
const servers = ref<any>([]);
const apiData = await useFetch('/api/serverData')

//assign apiData to apiRef
servers.value = apiData
console.log(servers.value)

</script>
<template>
  <div>
    <h1>AQ3D Server Status Infos</h1>
    <PlayerInfo  v-for="(server, index) in servers" :serverName="Name" :playerAmount="UserCount" />
  </div>
</template>
</code>```

As you can see, it is not showing the data from the json I receive.
I tried tried to use the v-for differently, but this gave me only errors.

What did I miss - is my approach with the ref even current?
I basically just wanna iterate over my component for each server object inside the array like so

ServerName
PlayerAmount

ServerName
PlayerAmount

...

Body:
I am currently working on a vue 3 project together with typescript.

I have an api, that sends me an array of objects containing the details of each server.

I have a script file under /server/api/serverData.ts that fetches me this data

//we want to fetch asnyc
export default defineEventHandler(async (event) => {
  //fetch from uri using $fetch from nuxt
  const data = await $fetch("https://game.aq3d.com/api/game/ServerList");
  //return data
  return data;
});

Here is an example output

[
  {
    "ID": 1,
    "SortIndex": 1,
    "Name": "Red Dragon",
    "HostName": "nextdragon.aq3d.com",
    "Port": 5594,
    "UserCount": 754,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "Connections": 737,
    "GEMQueueLength": 2484,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "NA"
  },
  {
    "ID": 4,
    "SortIndex": 16,
    "Name": "Localhost",
    "HostName": "localhost",
    "Port": 5591,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-07-01T15:48:00",
    "AccessLevel": 100,
    "AlertLevel": -1,
    "Status": 0,
    "Region": "NA"
  },
  {
    "ID": 7,
    "SortIndex": 4,
    "Name": "Blue Dragon",
    "HostName": "game.dragon.aq3d.com",
    "Port": 5594,
    "UserCount": 180,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "Connections": 178,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "NA"
  },
  {
    "ID": 10,
    "SortIndex": 7,
    "Name": "Black Dragon",
    "HostName": "game.dragon.aq3d.com",
    "Port": 5593,
    "UserCount": 1,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "AccessLevel": 100,
    "Connections": 1,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "NA"
  },
  {
    "ID": 11,
    "SortIndex": 8,
    "Name": "Green Dragon  [EU]",
    "HostName": "nextdragon.aq3d.com",
    "Port": 5590,
    "UserCount": 128,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "Connections": 123,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "EU"
  },
  {
    "ID": 12,
    "SortIndex": 9,
    "Name": "Gold Dragon [SEA]",
    "HostName": "nextdragon.aq3d.com",
    "Port": 5591,
    "UserCount": 57,
    "MaxUsers": 900,
    "State": true,
    "Chat": true,
    "Language": "en",
    "IP": "",
    "LocalIP": "",
    "LastUpdated": "2022-12-30T15:22:00",
    "Connections": 55,
    "AlertLevel": 1,
    "Status": 1,
    "Region": "AS"
  }
]

I have a Player Info component under /Player/Info.vue with properties

<template>

Player Information

{{ serverName }}

{{ playerAmount }}

</template>

I use it inside my app.vue inside the root dir like this:

<template>

AQ3D Server Status Infos

    <PlayerInfo  v-for="(server, index) in servers" :serverName="Name" :playerAmount="UserCount" />

</template>

As you can see, it is not showing the data from the json I receive.
I tried tried to use the v-for differently, but this gave me only errors.

What did I miss - is my approach with the ref even current?
I basically just wanna iterate over my component for each server object inside the array like so

ServerName
PlayerAmount

ServerName
PlayerAmount

...


问:
What makes the multi-head self-attention matrices different?
Transformers (BERT) use one set of three matrices, Q, K, V for each attention head. BERT uses 12 attention heads in each layer, with each attention head having it's own set of three such matrices.

The actual values of these 36 matrices are  obtained via the training.

My question is: How does the model ensure that it doesn't end up with 12 sets of identical matrices? The only real difference between the attention heads seems to be the random initialization. It is very possible of course that the random initialization combined with the gradient descent training does ensure that the attention heads don't end up being identical. But this is not guaranteed, right?

Is there any other factor ensuring that the attention heads don't become identical over the course of the training?

This part is not clear from any of the papers I have seen online.


问:
Prometheus metric retruns no data
i have installed the prometheus-es-exporter for querying the elasticsearch and also i have written some queries.E.g one of the query looks like:

```<code>[query_database_connection_exception]
QueryIntervalSecs = 300
QueryIndices = logs.*
QueryJson = {
  "size": 0,
  "query": {
    "query_string": {
      "query": "message: \"com.microsoft.sqlserver.jdbc.SQLServerException: \" AND @timestamp:(>=now-1h AND <now)"
    }
  },
  "aggs": {
    "application": {
      "terms": {
        "field": "kubernetes.labels.app.keyword"
        }
      }
    }
  }
</code>```

ES-Exporter exposes after the configuration the metric database_connection_exception_application_doc_count but i face the issue that sometimes i get in prometheus the error message:

This happens not only for this query but for other queries as well.My understanding and expectation is that if my query does not find the string com.microsoft.sqlserver.jdbc.SQLServerException for the last 1h it must return the value=0 in prometheus but for some reason it returns no data.How should i understand this?
ES-Exporter is running smoothly,health check of ES-Exporter and Elastic shows no error,all elastic nodes are at state green.

Title: Prometheus metric retruns no data

Body:
i have installed the prometheus-es-exporter for querying the elasticsearch and also i have written some queries.E.g one of the query looks like:

[query_database_connection_exception]
QueryIntervalSecs = 300
QueryIndices = logs.*
QueryJson = {
  "size": 0,
  "query": {
    "query_string": {
      "query": "message: \"com.microsoft.sqlserver.jdbc.SQLServerException: \" AND @timestamp:(>=now-1h AND <now)"
    }
  },
  "aggs": {
    "application": {
      "terms": {
        "field": "kubernetes.labels.app.keyword"
        }
      }
    }
  }

ES-Exporter exposes after the configuration the metric database_connection_exception_application_doc_count but i face the issue that sometimes i get in prometheus the error message:

This happens not only for this query but for other queries as well.My understanding and expectation is that if my query does not find the string com.microsoft.sqlserver.jdbc.SQLServerException for the last 1h it must return the value=0 in prometheus but for some reason it returns no data.How should i understand this?
ES-Exporter is running smoothly,health check of ES-Exporter and Elastic shows no error,all elastic nodes are at state green.


问:
Hiding the application page when the user account is approved
```<code>//Verification
ConstraintLayout applyVerification = findViewById(R.id.applyVerification);

applyVerification.setOnClickListener(v -> {
    Intent intent4 = new Intent(getApplicationContext(), VerifyActivity.class);
    startActivity(intent4);
});

FirebaseDatabase.getInstance().getReference().child("Users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if (snapshot.exists()){
            if (snapshot.hasChild(FirebaseAuth.getInstance().getCurrentUser().getUid())){
                applyVerification.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});
</code>```

Hello, I want the application page to be hidden when the user submits an application for approval and is approved and receives a check mark, but my code did not work, even if the user is approved, the confirmation page still appears, the user can still request it.

Where is the error in my code?

Body:
//Verification
ConstraintLayout applyVerification = findViewById(R.id.applyVerification);

applyVerification.setOnClickListener(v -> {
    Intent intent4 = new Intent(getApplicationContext(), VerifyActivity.class);
    startActivity(intent4);
});

FirebaseDatabase.getInstance().getReference().child("Users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if (snapshot.exists()){
            if (snapshot.hasChild(FirebaseAuth.getInstance().getCurrentUser().getUid())){
                applyVerification.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});

Hello, I want the application page to be hidden when the user submits an application for approval and is approved and receives a check mark, but my code did not work, even if the user is approved, the confirmation page still appears, the user can still request it.

Where is the error in my code?


问:
caught error @ main DriverPackageNotInstalledError: Postgres package has not been found installed
I'm trying to start up my postgresql with typeorm on a node.js server and I'm getting this error: caught error @ main DriverPackageNotInstalledError: Postgres package has not been found installed. Try to install it: npm install pg --save

I've checked pg is installed in my docker container

deps versions:
"pg": "^8.8.0",
"typeorm": "^0.2.34",

My docker-compose:

version: '3.7'

services:
  api:
    profiles: ['api', 'web']
    container_name: slots-api
    stdin_open: true
    build:
      context: ./
      dockerfile: api/Dockerfile
      target: dev
    environment:
      NODE_ENV: development
    ports:
      - 8000:8000
      - 9229:9229 # for debugging
    volumes:
      - ./api:/app/api
      - /app/node_modules/ # do not mount node_modules
      - /app/api/node_modules/ # do not mount node_modules
    depends_on:
      - database
    command: yarn dev:api

  database:
    container_name: slots-database
    image: postgres:alpine
    restart: unless-stopped
    ports:
      - 5432:5432
    depends_on:
      - adminer
    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: admin
      POSTGRES_DB: dev
      POSTGRES_HOST: 127.0.0.1
```
<p>my dockerfile:</p>
```FROM node:16-alpine AS builder

WORKDIR /app
COPY package*.json ./
COPY yarn.lock ./
RUN yarn install

FROM node:16-alpine AS dev

WORKDIR /app
COPY --from=builder /app/ /app/
COPY . .
RUN yarn build:api

EXPOSE 8000

CMD ["yarn", "dev"]
```
<p>My typeorm config:</p>
```import { Connection, createConnection, DatabaseType } from 'typeorm';
import * as entities from '@/entities';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';

export const shouldCache = (): boolean => {
  return !['test', 'development'].includes(process.env.NODE_ENV ?? '');
};

export default async function postgresConnection(): Promise<Connection> {
  const config = {
    database: 'dev',
    entities: Object.values(entities),
    host: '127.0.0.1',
    password: 'admin',
    port: 5432,
    type: 'postgres' as DatabaseType,
    username: 'admin',
    synchronize: false,
    dropSchema:
      process.env.NODE_ENV !== 'production' &&
      process.env.POSTGRES_DROP_SCHEMA === 'true',
    migrations: ['dist/migrations/*.js'],
    migrationsRun: true,
    cache: shouldCache(),
  } as PostgresConnectionOptions;

  return await createConnection(config);
}
```
<p>my <code>server.ts</code> file:</p>
```...
  await postgresConnection().then(async () => {
    console.info('Database connected!');
  });
...
```

It works without issues running the server locally, with the database and adminer running on docker

Body:
I'm trying to start up my postgresql with typeorm on a node.js server and I'm getting this error: caught error @ main DriverPackageNotInstalledError: Postgres package has not been found installed. Try to install it: npm install pg --save

I've checked pg is installed in my docker container

deps versions:
"pg": "^8.8.0",
"typeorm": "^0.2.34",

My docker-compose:

version: '3.7'

services:
  api:
    profiles: ['api', 'web']
    container_name: slots-api
    stdin_open: true
    build:
      context: ./
      dockerfile: api/Dockerfile
      target: dev
    environment:
      NODE_ENV: development
    ports:
      - 8000:8000
      - 9229:9229 # for debugging
    volumes:
      - ./api:/app/api
      - /app/node_modules/ # do not mount node_modules
      - /app/api/node_modules/ # do not mount node_modules
    depends_on:
      - database
    command: yarn dev:api

  database:
    container_name: slots-database
    image: postgres:alpine
    restart: unless-stopped
    ports:
      - 5432:5432
    depends_on:
      - adminer
    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: admin
      POSTGRES_DB: dev
      POSTGRES_HOST: 127.0.0.1

my dockerfile:

FROM node:16-alpine AS builder

WORKDIR /app
COPY package*.json ./
COPY yarn.lock ./
RUN yarn install

FROM node:16-alpine AS dev

WORKDIR /app
COPY --from=builder /app/ /app/
COPY . .
RUN yarn build:api

EXPOSE 8000

CMD ["yarn", "dev"]

My typeorm config:

import { Connection, createConnection, DatabaseType } from 'typeorm';
import * as entities from '@/entities';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';

export const shouldCache = (): boolean => {
  return !['test', 'development'].includes(process.env.NODE_ENV ?? '');
};

export default async function postgresConnection(): Promise<Connection> {
  const config = {
    database: 'dev',
    entities: Object.values(entities),
    host: '127.0.0.1',
    password: 'admin',
    port: 5432,
    type: 'postgres' as DatabaseType,
    username: 'admin',
    synchronize: false,
    dropSchema:
      process.env.NODE_ENV !== 'production' &&
      process.env.POSTGRES_DROP_SCHEMA === 'true',
    migrations: ['dist/migrations/*.js'],
    migrationsRun: true,
    cache: shouldCache(),
  } as PostgresConnectionOptions;

  return await createConnection(config);
}

my server.ts file:

...
  await postgresConnection().then(async () => {
    console.info('Database connected!');
  });
...

It works without issues running the server locally, with the database and adminer running on docker


问:
Most efficient way to have a vector take the contents of an array?
I know myvec.data() returns a pointer to the vector's data. In this case, I'd like to set the vector's internal data to point to my own array, allocated like so:

```<code>double* my_array = new double[amount];
</code>```

I know I could do this:

```<code>std::vector<double> my_vec;

for (double i : my_array) my_vec.push_back(i);

delete [] my_array;
</code>```

but I'm asking if there's a way to have it be done without O(n) of extra memory (i.e, just make it point to my array and provide some info about it).

Would something like:

```<code>my_vec.insert(std::end(my_vec), std::begin(my_array), std::end(my_array));
</code>```

do the job? I have a feeling std::move may be needed, but I'm not sure where?

According to the comments, this is a horrible idea, and no you cannot, so let's say my_array is now another vector, would this work:

```<code>my_vec = std::vector<double>(std::move(my_other_vec))
</code>```

?

Body:
I know myvec.data() returns a pointer to the vector's data. In this case, I'd like to set the vector's internal data to point to my own array, allocated like so:

double* my_array = new double[amount];

I know I could do this:

std::vector<double> my_vec;

for (double i : my_array) my_vec.push_back(i);

delete [] my_array;

but I'm asking if there's a way to have it be done without O(n) of extra memory (i.e, just make it point to my array and provide some info about it).

Would something like:

my_vec.insert(std::end(my_vec), std::begin(my_array), std::end(my_array));

do the job? I have a feeling std::move may be needed, but I'm not sure where?

According to the comments, this is a horrible idea, and no you cannot, so let's say my_array is now another vector, would this work:

my_vec = std::vector<double>(std::move(my_other_vec))

?


问:
Wix and Zoho Inventory integration using Zapier
I am trying to use Zapier (Catch Hook in Webhooks by Zapier) to push Wix's Order to Zoho Inventory's Sale Order. Zapier creates a Webhook URL for me to put into Wix's Webhook (Create Order). And when I try to test the trigger. Zapier couldn't catch any information. The manual says that it will catch the recent result, and I also created new data, but Zapier couldn't receive anything.
Can you provide support on this matter? Thank you

I tried wix's automation, but it didn't provide me enough details to math with Zoho Inventory's API. I expect to use Zapier's Catch hook to get more details and information.


问:
Javascript equivalent of $(document).on('click', '#myElement', function()
What is the (vanilla) javascript equivalent of

```<code>$(document).on('click', '#myElement', function() {/*do something*/});
</code>```

Is there something shorter than

```<code>document.addEventListener('click', function(e){
  if (e.target.id=='myElement'){
    /*do something*/
  }
});
</code>```

I'm wondering if the latter is heavy handed as it will proceed to process all clicks, but the jquery version only proceeds with clicks on the required element, so perhaps there is a more elegant javascript version than this?

I want the handler at document level to deal with subsequently dynamically added elements.

Body:
What is the (vanilla) javascript equivalent of

$(document).on('click', '#myElement', function() {/*do something*/});

Is there something shorter than

document.addEventListener('click', function(e){
  if (e.target.id=='myElement'){
    /*do something*/
  }
});

I'm wondering if the latter is heavy handed as it will proceed to process all clicks, but the jquery version only proceeds with clicks on the required element, so perhaps there is a more elegant javascript version than this?

I want the handler at document level to deal with subsequently dynamically added elements.


问:
How to rollback all successful to_sql() attempts if there is an error with one of them?
So I've got a script where I'm taking in data and spitting out the data into multiple tables into my database. I'm trying to account for the case in which one table would fail, but there had already been successful to_sql executions before it. The reason this is a problem is because my script will re-try to run the file about 5 times, which would cause duplication into the tables that the data is successfully imported into. I could make my script only run once, but even then, when I go to fix the error and run the file again, there would still be a 2x duplication into the tables that had successfully ran before the error in the initial run of the file.

Is there a way to rollback all successful to_sql() attempts if there is an error with one of them?


问:
Creating a new starter project in Android Studio fails :-(
I was trying to revive an Android project that I had been working on about 4 years ago and that is maybe 80% completed, but I got stuck again.
I had installed the latest version of Android Studio and imported the old project but AS fails to build it ("Unable to find Gradle tasks to build: [:]." ?!?).

I thus tried to start over by first creating me a new, essentially empty project first with the intention to then copy the old project over "bit by bit".

So I selected "Basic Activity" as project type and had the "Wizard" create the project but also that does not build but fails with the error message:

```<code>Duplicate class androidx.lifecycle.ViewModelLazy found in modules lifecycle-viewmodel-2.5.1-runtime (androidx.lifecycle:lifecycle-viewmodel:2.5.1) and lifecycle-viewmodel-ktx-2.3.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1)
</code>```

Is this indeed the sorry state of Android Development? What am I missing here? Is there a project type or template that somewhat reliably works "out-of-the-box" so one can at least get a working base-line to start from?

This is using AS 2021.3.1 Patch 1.

Body:
I was trying to revive an Android project that I had been working on about 4 years ago and that is maybe 80% completed, but I got stuck again.
I had installed the latest version of Android Studio and imported the old project but AS fails to build it ("Unable to find Gradle tasks to build: [:]." ?!?).

I thus tried to start over by first creating me a new, essentially empty project first with the intention to then copy the old project over "bit by bit".

So I selected "Basic Activity" as project type and had the "Wizard" create the project but also that does not build but fails with the error message:

Duplicate class androidx.lifecycle.ViewModelLazy found in modules lifecycle-viewmodel-2.5.1-runtime (androidx.lifecycle:lifecycle-viewmodel:2.5.1) and lifecycle-viewmodel-ktx-2.3.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1)

Is this indeed the sorry state of Android Development? What am I missing here? Is there a project type or template that somewhat reliably works "out-of-the-box" so one can at least get a working base-line to start from?

This is using AS 2021.3.1 Patch 1.


问:
how to run an external function with variables from State?
this function must be run in the file where the bot is located

```<code>def start_pars():
    from mainaio import data
    username_input = driver.find_element(By.XPATH,
                                         '/html/body/div/div/main/div/div/div/div[1]/form/div[1]/div[1]/div/input')
    username_input.clear()
    username_input.send_keys(data["username"])
    pass_input = driver.find_element(By.XPATH,
                                     '/html/body/div/div/main/div/div/div/div[1]/form/div[1]/div[2]/div/input')
    pass_input.clear()
    pass_input.send_keys(data["password"])
    driver.find_element(By.XPATH, '/html/body/div/div/main/div/div/div/div[1]/form/div[2]/button').click()
    time.sleep(1)
    username1 = driver.find_element(By.XPATH, '/html/body/div[1]/nav[2]/div[2]/div/div[2]/div[2]/div')
    print(username1.text)
    less1 = []
    lessundscore = driver.find_elements(By.XPATH, '/html/body/div[1]/div/main/div/div[2]/div/div[3]/div[1]')
    for value in zip(lessundscore):
        less1 += value
    for val in less1:
        print(val.text)
    return username1, less1
</code>```

items from the state must be transferred to the sending keys

```<code>class Registration(StatesGroup):
    username = State()
    password = State()

</code>```
```<code>username = message.text
await state.update_data(username=username)
</code>```
```<code>assword = message.text
await state.update_data(password=password)
data = await state.get_data()
</code>```

I tried to run in the last registration function start_pars(data['username'], data['password'])

Body:
this function must be run in the file where the bot is located

def start_pars():
    from mainaio import data
    username_input = driver.find_element(By.XPATH,
                                         '/html/body/div/div/main/div/div/div/div[1]/form/div[1]/div[1]/div/input')
    username_input.clear()
    username_input.send_keys(data["username"])
    pass_input = driver.find_element(By.XPATH,
                                     '/html/body/div/div/main/div/div/div/div[1]/form/div[1]/div[2]/div/input')
    pass_input.clear()
    pass_input.send_keys(data["password"])
    driver.find_element(By.XPATH, '/html/body/div/div/main/div/div/div/div[1]/form/div[2]/button').click()
    time.sleep(1)
    username1 = driver.find_element(By.XPATH, '/html/body/div[1]/nav[2]/div[2]/div/div[2]/div[2]/div')
    print(username1.text)
    less1 = []
    lessundscore = driver.find_elements(By.XPATH, '/html/body/div[1]/div/main/div/div[2]/div/div[3]/div[1]')
    for value in zip(lessundscore):
        less1 += value
    for val in less1:
        print(val.text)
    return username1, less1

items from the state must be transferred to the sending keys

class Registration(StatesGroup):
    username = State()
    password = State()

username = message.text
await state.update_data(username=username)

assword = message.text
await state.update_data(password=password)
data = await state.get_data()

I tried to run in the last registration function start_pars(data['username'], data['password'])


问:
After dynamically importing modules using importlib.import_module, I am getting the error "AttributeError: 'str' object has no attribute..."
I am writing code to parse a protobuff file.  I want to be able to tell analyzer.py to parse all files in a folder.
I have dynamically imported this folder using this code

```<code>tree = os.listdir('/home/kolbe/Documents/protobuf_generator/analyzed_output/output')
myList = []
for i in range(len(tree)):
  sub = '.py'
  length = len(sub)
  tree[i] = tree[i][:-length]
  pb = 'pb2'
  if pb in tree[i]:
    myList.append(tree[i])
for i in myList:
  importlib.import_module(i)
</code>```

basically I used os.listdir() to make a list of file names in the appropriate folder.  I then stripped the .py ending and imported all of these files into my current file analyzer.py.
I can confirm that these files have been imported using

```<code> results = [m.__name__ for m in sys.modules.values() if m]
</code>```

With this I am able to verify that all modules have been imported.
but then when I try to parse any of these imported files by using

```<code>  print(parserObj.parse(myList[0].DESCRIPTOR))

</code>```

I get the error:

```<code>Traceback (most recent call last):
  File "/home/kolbe/Documents/protobuf_generator/analyzed_output/output/analyzer.py", line 60, in <module>
    print(parserObj.parse(myList[0].DESCRIPTOR))
AttributeError: 'str' object has no attribute 'DESCRIPTOR'
</code>```

What am I doing wrong here, its something to do with referencing the dynamic input, if I do things manually my code works great for example:

```<code>  import myFile
  print(parserObj.parse(myFile.DESCRIPTOR))

</code>```

I am quite fresh to programming, any and all help is much appreciated

I have tried different methods of importing files like using glob

```<code>from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
</code>```

and it produces the same result.  I cannot find any forum posts or the like with someone experiencing this problem.

Body:
I am writing code to parse a protobuff file.  I want to be able to tell analyzer.py to parse all files in a folder.
I have dynamically imported this folder using this code

tree = os.listdir('/home/kolbe/Documents/protobuf_generator/analyzed_output/output')
myList = []
for i in range(len(tree)):
  sub = '.py'
  length = len(sub)
  tree[i] = tree[i][:-length]
  pb = 'pb2'
  if pb in tree[i]:
    myList.append(tree[i])
for i in myList:
  importlib.import_module(i)

basically I used os.listdir() to make a list of file names in the appropriate folder.  I then stripped the .py ending and imported all of these files into my current file analyzer.py.
I can confirm that these files have been imported using

 results = [m.__name__ for m in sys.modules.values() if m]

With this I am able to verify that all modules have been imported.
but then when I try to parse any of these imported files by using

  print(parserObj.parse(myList[0].DESCRIPTOR))

I get the error:

Traceback (most recent call last):
  File "/home/kolbe/Documents/protobuf_generator/analyzed_output/output/analyzer.py", line 60, in <module>
    print(parserObj.parse(myList[0].DESCRIPTOR))
AttributeError: 'str' object has no attribute 'DESCRIPTOR'

What am I doing wrong here, its something to do with referencing the dynamic input, if I do things manually my code works great for example:

  import myFile
  print(parserObj.parse(myFile.DESCRIPTOR))

I am quite fresh to programming, any and all help is much appreciated

I have tried different methods of importing files like using glob

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

and it produces the same result.  I cannot find any forum posts or the like with someone experiencing this problem.


问:
Automatically wrap elements to fit parent width and on demand
Is there a way have a responsive design where elements are automatically moved to new row
to fit width of the container and also move elements with a specific class and its following siblings to a new row ?

For example I have a list of elements, and I need to display newRow elements on a new row

.box>*{width:4em;border:1px solid;padding:0.2em;display:inline-block;vertical-align:top}
.box>*>*{display:inline-block;width:1em;height:1em;background-color:lightblue;border:1px solid;margin:0.1em}
.newRow{background-color:pink;border-radius:33%}
.box>*::before{content:attr(class);display:block;text-align:center;border-bottom:1px solid;margin-bottom:0.2em}
.expected{background-color:lightgreen}

/* attempts */
.block >.newRow
{
  display: block;
}

.before-nl >.newRow::before
{
  content: "\a";
  white-space: pre;
}

.float >.newRow
{
  float:left;
}

/* changes go here */
.default
{
}

.default > *
{
}

.default > .newRow
{
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="expected">
     <div></div><div></div><div></div><div></div><br><div class="newRow"></div><div></div><br><div class="newRow"></div><div></div><div></div><div></div><div></div><br><div class="newRow"></div><div></div><div></div><br><div class="newRow"></div><br><div class="newRow"></div><div></div>
  </div>
  <div class="default">
    <div></div><div></div><div></div><div></div><div class="newRow"></div><div></div><div class="newRow"></div><div></div><div></div><div></div><div></div><div class="newRow"></div><div></div><div></div><div class="newRow"></div><div class="newRow"></div><div></div>
  </div>
  <div class="block">
     <div></div><div></div><div></div><div></div><div class="newRow"></div><div></div><div class="newRow"></div><div></div><div></div><div></div><div></div><div class="newRow"></div><div></div><div></div><div class="newRow"></div><div class="newRow"></div><div></div>
  </div>
  <div class="before-nl">
     <div></div><div></div><div></div><div></div><div class="newRow"></div><div></div><div class="newRow"></div><div></div><div></div><div></div><div></div><div class="newRow"></div><div></div><div></div><div class="newRow"></div><div class="newRow"></div><div></div>
  </div>
  <div class="float">
     <div></div><div></div><div></div><div></div><div class="newRow"></div><div></div><div class="newRow"></div><div></div><div></div><div></div><div></div><div class="newRow"></div><div></div><div></div><div class="newRow"></div><div class="newRow"></div><div></div>
  </div>
</div></code>```

I'm trying to avoid adding new elements into HTML (aka wrapping sections into containers)

Any tips?

The proposed "answer" doesn't cover the part where children wrapped on demand.

Body:
Is there a way have a responsive design where elements are automatically moved to new row
to fit width of the container and also move elements with a specific class and its following siblings to a new row ?

For example I have a list of elements, and I need to display newRow elements on a new row

.box>*{width:4em;border:1px solid;padding:0.2em;display:inline-block;vertical-align:top}
.box>*>*{display:inline-block;width:1em;height:1em;background-color:lightblue;border:1px solid;margin:0.1em}
.newRow{background-color:pink;border-radius:33%}
.box>*::before{content:attr(class);display:block;text-align:center;border-bottom:1px solid;margin-bottom:0.2em}
.expected{background-color:lightgreen}

/* attempts */
.block >.newRow
{
  display: block;
}

.before-nl >.newRow::before
{
  content: "\a";
  white-space: pre;
}

.float >.newRow
{
  float:left;
}

/* changes go here */
.default
{
}

.default > *
{
}

.default > .newRow
{
}

I'm trying to avoid adding new elements into HTML (aka wrapping sections into containers)

Any tips?

The proposed "answer" doesn't cover the part where children wrapped on demand.


问:
How to fix ModuleNotFoundError: No module named 'PySide2',
The am using docker container ubuntu 18.04, I have installed python 3.7. The program works on ubuntu 18.04 with GUI.

pip -version or pip3 -version

Output: pip 22.3.1 from /usr/local/lib/python3.7/dist-packages/pip (python 3.7)

I am facin the following error:
ModuleNotFoundError: No module named 'PySide2'

I have tried installing it by running:
pip install PySide2
But this is the error I get:

```<code>Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement PySide2 (from versions: none)
ERROR: No matching distribution found for PySide2
</code>```

I have also tried:
pip3 install PySide2
But still get the same error:

```<code>Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement PySide2 (from versions: none)
ERROR: No matching distribution found for PySide2
</code>```

I was initally using python 3.8. But read somewhere that it does not suppose it. So I installed python 3.7. I have got the same error with python 3.6 and python 3.5

I have also adding --user, that is,
pip install PySide2 --user and pip3 install PySide2 --user
I still continue to get the same error.

```<code>ERROR: Could not find a version that satisfies the requirement PySide2 (from versions: none)
ERROR: No matching distribution found for PySide2
</code>```

I have also tired sudo apt-get install PySide2
Then I get this error:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package PySide2
</code>```

I even tired installing the wheel directly from https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyqt4

and then run it. It doesn't work.

I would really apprecite if someone can help me out here!

Body:
The am using docker container ubuntu 18.04, I have installed python 3.7. The program works on ubuntu 18.04 with GUI.

pip -version or pip3 -version

Output: pip 22.3.1 from /usr/local/lib/python3.7/dist-packages/pip (python 3.7)

I am facin the following error:
ModuleNotFoundError: No module named 'PySide2'

I have tried installing it by running:
pip install PySide2
But this is the error I get:

Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement PySide2 (from versions: none)
ERROR: No matching distribution found for PySide2

I have also tried:
pip3 install PySide2
But still get the same error:

Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement PySide2 (from versions: none)
ERROR: No matching distribution found for PySide2

I was initally using python 3.8. But read somewhere that it does not suppose it. So I installed python 3.7. I have got the same error with python 3.6 and python 3.5

I have also adding --user, that is,
pip install PySide2 --user and pip3 install PySide2 --user
I still continue to get the same error.

ERROR: Could not find a version that satisfies the requirement PySide2 (from versions: none)
ERROR: No matching distribution found for PySide2

I have also tired sudo apt-get install PySide2
Then I get this error:

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package PySide2

I even tired installing the wheel directly from https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyqt4

and then run it. It doesn't work.

I would really apprecite if someone can help me out here!