问:
How to know the hostname/IP address of the computer who is doing changes in the shared folder on server
I have to monitor a shared folder on the server for changes taking place in that folder by a computer connected in the network(it's hostname). I implemented monitoring of directory and files using C#. But, it only monitors events like Created, Renamed, Changed, Deleted and Error events.
I also need help with monitoring the hostname/IP address of the computer accessing or doing changes to the shared folder and the time when the event took place.
Here is my code :

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace a1ashiishFileSystemWatcher
{
    public partial class MainForm : Form
    {
        public ListBoxlistBox;
        public const String startMonitoring = “Start Minitoring…”;
        public const String stopMonitoring = “Stop Minitoring…”;
        public MainForm()
        {
            InitializeComponent();
            //Create a listBox to show activities of all Events.
            listBox = new ListBox();
            listBox.FormattingEnabled = true;
            listBox.Location = new System.Drawing.Point(23, 121);
            listBox.Name = “listBox”;
            listBox.Size = new System.Drawing.Size(571, 238);
            listBox.TabIndex = 2;
            this.Controls.Add(listBox);
        }
        private voidbutton1_Click(object sender, EventArgs e)
        {
            // Create FolderBrowserDialog object.
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            // Show a button to create a new folder.
            folderBrowserDialog.ShowNewFolderButton = true;
            DialogResult dialogResult = folderBrowserDialog.ShowDialog();
            // Get selected path from FolderBrowserDialog control.
            if (dialogResult == DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog.SelectedPath;
                Environment.SpecialFolderroot = folderBrowserDialog.RootFolder;
            }
        }
        private voidbutton2_Click(object sender, EventArgs e)
        {
            // Create a new FileSystemWatcher object.
            FileSystemWatcher fsWatcher = new FileSystemWatcher();
            switch (button2.Text)
            {
                // Start Monitoring…
                case startMonitoring:
                    if (!textBox1.Text.Equals(String.Empty))
                    {
                        listBox.Items.Add(“Started FileSystemWatcher Service…”);
                        fsWatcher.Path = textBox1.Text;
                        // Set Filter.
                        fsWatcher.Filter = (textBox2.Text.Equals(String.Empty)) ? “*.*” : textBox2.Text;
                        // Monitor files and subdirectories.
                        fsWatcher.IncludeSubdirectories = true;
                        // Monitor all changes specified in the NotifyFilters.
                        fsWatcher.NotifyFilter = NotifyFilters.Attributes |
                                                 NotifyFilters.CreationTime |
                                                 NotifyFilters.DirectoryName |
                                                 NotifyFilters.FileName |
                                                 NotifyFilters.LastAccess |
                                                 NotifyFilters.LastWrite |
                                                 NotifyFilters.Security |
                                                 NotifyFilters.Size;
                        fsWatcher.EnableRaisingEvents = true;
                        // Raise Event handlers.
                        fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
                        fsWatcher.Created += new FileSystemEventHandler(OnCreated);
                        fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted);
                        fsWatcher.Renamed += new RenamedEventHandler(OnRenamed);
                        fsWatcher.Error += new ErrorEventHandler(OnError);
                        button2.Text = stopMonitoring;
                        textBox1.Enabled = false;
                        textBox2.Enabled = false;
                    }
                    else
                    {
                        listBox.Items.Add(“Please select folder to monitor….”);
                    }
                    break;
                // Stop Monitoring…
                case stopMonitoring:
                default:
                    fsWatcher.EnableRaisingEvents = false;
                    fsWatcher = null;
                    button2.Text = startMonitoring;
                    textBox1.Enabled = true;
                    textBox2.Enabled = true;
                    listBox.Items.Add(“Stopped FileSystemWatcher Service…”);
                    break;
            }
        }
        // FileSystemWatcher – OnCreated Event Handler
        public voidOnCreated(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
        }
        // FileSystemWatcher – OnChanged Event Handler
        public voidOnChanged(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
        }
        // FileSystemWatcher – OnRenamed Event Handler
        public voidOnRenamed(object sender, RenamedEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1} to “{2}””, e.FullPath, e.ChangeType, e.Name)); });
        }
        // FileSystemWatcher – OnDeleted Event Handler
        public voidOnDeleted(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
        }
        // FileSystemWatcher – OnError Event Handler
        public void OnError(object sender, ErrorEventArgse)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Error : {0}”, e.GetException().Message)); });
        }
    }
}
</code>```

I have tried this approach, but still I am not able to get the hostname. Please help me where I am going wrong.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace MonitorShare
{
    public partial class Monitor : ServiceBase
    {
        public Monitor()
        {
            InitializeComponent();
            string dDirectory = @"E:\SharedFolder\Shares";
            DirectoryInfo info = new DirectoryInfo(dDirectory);
            string[] filePath = Directory.GetFiles(dDirectory, "*.*");

            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.BeginInit();
            watcher.filePath = dDirectory;
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite |

NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.Created += new FileSystemEventHandler(watcher_Created);
            watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
            watcher.Filter = "*.*";
            watcher.EnableRaisingEvents = true;
            watcher.EndInit();
        }

        protected void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            var process = new Process();
            process.StartInfo.FileName = "openfiles.exe";
            process.StartInfo.Arguments = "/query /FO CSV /v";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            try
            {
                process.Start();
                if ((process.StandardOutput != null))
                {
                    var result = process.StandardOutput.ReadToEnd().Trim().Replace("\"",

"");
                    var lines = result.Split('\n');

                    var firstLineIndex = 1 + lines.Cast<string>().ToList().FindIndex(l =>

l.Contains("Hostname"));
                    for (var i = firstLineIndex; i < lines.Count() && firstLineIndex > 0; i

++)
                    {
                        var fields = lines[i].Split(',');
                        var time = DateTime.Now;
                        FileStream fs = new FileStream(@"C:\SFD\log.txt", FileMode.Append);
                        StreamWriter sw = new StreamWriter(fs);

                        if(firstLineIndex.ToString()=="Hostname")
                        {
                             Console.SetOut(sw);
                             Console.WriteLine(e.FullPath + "\t" + e.ChangeType + "\t" +

time + "\t" + e.Name + "\t" + fields[0]);
                             sw.Close();
                        }
                    }
                }
                process.WaitForExit();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                process.Close();
            }
        }

        protected void watcher_Created(object sender, FileSystemEventArgs e)
        {
            var process = new Process();
            process.StartInfo.FileName = "openfiles.exe";
            process.StartInfo.Arguments = "/query /FO CSV /v";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            try
            {
                process.Start();
                if ((process.StandardOutput != null))
                {
                    var result = process.StandardOutput.ReadToEnd().Trim().Replace("\"",

"");
                    var lines = result.Split('\n');

                    var firstLineIndex = 1 + lines.Cast<string>().ToList().FindIndex(l =>

l.Contains("Hostname"));
                    for (var i = firstLineIndex; i < lines.Count() && firstLineIndex > 0; i

++)
                    {
                        var fields = lines[i].Split(',');
                        var time = DateTime.Now;
                        FileStream fs = new FileStream(@"C:\SFD\log.txt", FileMode.Append);
                        StreamWriter sw = new StreamWriter(fs);

                        if(firstLineIndex.ToString()=="Hostname")
                        {
                             Console.SetOut(sw);
                             Console.WriteLine(e.FullPath + "\t" + e.ChangeType + "\t" +

time + "\t" + e.Name + "\t" + fields[0]);
                             sw.Close();
                        }
                    }
                }
                process.WaitForExit();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                process.Close();
            }

        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}
</code>```

答:
To my knowledge you can use WMI to at least get the ones which are connected to the share. You need to reference System.Management.dll, create an instance of ManagementObjectSearcher and there you go.

The problem is usally finding the correct classes, the reference for WMI can be found here under WMI Reference. For your use case you will need the Win32_ConnectionShare class. Take into consideration that the application needs to run with admin priviledges in order to access data from that class.

A little example code for your use case (according to the above mentioned documentation antecedent represents the server side while dependent represents the client side):

```<code>// Create a query
SelectQuery query = new SelectQuery("SELECT * FROM Win32_ConnectionShare");

// Initialize an object searcher with this query
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

// Get the resulting collection and loop through it
foreach (ManagementObject mo in searcher.Get())
{
    string antecedent = mo["antecedent"].ToString();
    string dependent = mo["dependent"].ToString();

    ManagementObject share = new ManagementObject(antecedent);
    ManagementObject server = new ManagementObject(dependent);

    Console.WriteLine(server["UserName"].ToString());
    Console.WriteLine(server["ComputerName"].ToString());
    Console.WriteLine(server["ShareName"].ToString());
}
</code>```

Body:
I have to monitor a shared folder on the server for changes taking place in that folder by a computer connected in the network(it's hostname). I implemented monitoring of directory and files using C#. But, it only monitors events like Created, Renamed, Changed, Deleted and Error events.
I also need help with monitoring the hostname/IP address of the computer accessing or doing changes to the shared folder and the time when the event took place.
Here is my code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace a1ashiishFileSystemWatcher
{
    public partial class MainForm : Form
    {
        public ListBoxlistBox;
        public const String startMonitoring = “Start Minitoring…”;
        public const String stopMonitoring = “Stop Minitoring…”;
        public MainForm()
        {
            InitializeComponent();
            //Create a listBox to show activities of all Events.
            listBox = new ListBox();
            listBox.FormattingEnabled = true;
            listBox.Location = new System.Drawing.Point(23, 121);
            listBox.Name = “listBox”;
            listBox.Size = new System.Drawing.Size(571, 238);
            listBox.TabIndex = 2;
            this.Controls.Add(listBox);
        }
        private voidbutton1_Click(object sender, EventArgs e)
        {
            // Create FolderBrowserDialog object.
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            // Show a button to create a new folder.
            folderBrowserDialog.ShowNewFolderButton = true;
            DialogResult dialogResult = folderBrowserDialog.ShowDialog();
            // Get selected path from FolderBrowserDialog control.
            if (dialogResult == DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog.SelectedPath;
                Environment.SpecialFolderroot = folderBrowserDialog.RootFolder;
            }
        }
        private voidbutton2_Click(object sender, EventArgs e)
        {
            // Create a new FileSystemWatcher object.
            FileSystemWatcher fsWatcher = new FileSystemWatcher();
            switch (button2.Text)
            {
                // Start Monitoring…
                case startMonitoring:
                    if (!textBox1.Text.Equals(String.Empty))
                    {
                        listBox.Items.Add(“Started FileSystemWatcher Service…”);
                        fsWatcher.Path = textBox1.Text;
                        // Set Filter.
                        fsWatcher.Filter = (textBox2.Text.Equals(String.Empty)) ? “*.*” : textBox2.Text;
                        // Monitor files and subdirectories.
                        fsWatcher.IncludeSubdirectories = true;
                        // Monitor all changes specified in the NotifyFilters.
                        fsWatcher.NotifyFilter = NotifyFilters.Attributes |
                                                 NotifyFilters.CreationTime |
                                                 NotifyFilters.DirectoryName |
                                                 NotifyFilters.FileName |
                                                 NotifyFilters.LastAccess |
                                                 NotifyFilters.LastWrite |
                                                 NotifyFilters.Security |
                                                 NotifyFilters.Size;
                        fsWatcher.EnableRaisingEvents = true;
                        // Raise Event handlers.
                        fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
                        fsWatcher.Created += new FileSystemEventHandler(OnCreated);
                        fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted);
                        fsWatcher.Renamed += new RenamedEventHandler(OnRenamed);
                        fsWatcher.Error += new ErrorEventHandler(OnError);
                        button2.Text = stopMonitoring;
                        textBox1.Enabled = false;
                        textBox2.Enabled = false;
                    }
                    else
                    {
                        listBox.Items.Add(“Please select folder to monitor….”);
                    }
                    break;
                // Stop Monitoring…
                case stopMonitoring:
                default:
                    fsWatcher.EnableRaisingEvents = false;
                    fsWatcher = null;
                    button2.Text = startMonitoring;
                    textBox1.Enabled = true;
                    textBox2.Enabled = true;
                    listBox.Items.Add(“Stopped FileSystemWatcher Service…”);
                    break;
            }
        }
        // FileSystemWatcher – OnCreated Event Handler
        public voidOnCreated(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
        }
        // FileSystemWatcher – OnChanged Event Handler
        public voidOnChanged(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
        }
        // FileSystemWatcher – OnRenamed Event Handler
        public voidOnRenamed(object sender, RenamedEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1} to “{2}””, e.FullPath, e.ChangeType, e.Name)); });
        }
        // FileSystemWatcher – OnDeleted Event Handler
        public voidOnDeleted(object sender, FileSystemEventArgs e)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}”   || Action : {1}”, e.FullPath, e.ChangeType)); });
        }
        // FileSystemWatcher – OnError Event Handler
        public void OnError(object sender, ErrorEventArgse)
        {
            // Add event details in listbox.
            this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Error : {0}”, e.GetException().Message)); });
        }
    }
}

I have tried this approach, but still I am not able to get the hostname. Please help me where I am going wrong.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace MonitorShare
{
    public partial class Monitor : ServiceBase
    {
        public Monitor()
        {
            InitializeComponent();
            string dDirectory = @"E:\SharedFolder\Shares";
            DirectoryInfo info = new DirectoryInfo(dDirectory);
            string[] filePath = Directory.GetFiles(dDirectory, "*.*");

            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.BeginInit();
            watcher.filePath = dDirectory;
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite |

NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.Created += new FileSystemEventHandler(watcher_Created);
            watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
            watcher.Filter = "*.*";
            watcher.EnableRaisingEvents = true;
            watcher.EndInit();
        }

        protected void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            var process = new Process();
            process.StartInfo.FileName = "openfiles.exe";
            process.StartInfo.Arguments = "/query /FO CSV /v";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            try
            {
                process.Start();
                if ((process.StandardOutput != null))
                {
                    var result = process.StandardOutput.ReadToEnd().Trim().Replace("\"",

"");
                    var lines = result.Split('\n');

                    var firstLineIndex = 1 + lines.Cast<string>().ToList().FindIndex(l =>

l.Contains("Hostname"));
                    for (var i = firstLineIndex; i < lines.Count() && firstLineIndex > 0; i

++)
                    {
                        var fields = lines[i].Split(',');
                        var time = DateTime.Now;
                        FileStream fs = new FileStream(@"C:\SFD\log.txt", FileMode.Append);
                        StreamWriter sw = new StreamWriter(fs);

                        if(firstLineIndex.ToString()=="Hostname")
                        {
                             Console.SetOut(sw);
                             Console.WriteLine(e.FullPath + "\t" + e.ChangeType + "\t" +

time + "\t" + e.Name + "\t" + fields[0]);
                             sw.Close();
                        }
                    }
                }
                process.WaitForExit();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                process.Close();
            }
        }

        protected void watcher_Created(object sender, FileSystemEventArgs e)
        {
            var process = new Process();
            process.StartInfo.FileName = "openfiles.exe";
            process.StartInfo.Arguments = "/query /FO CSV /v";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            try
            {
                process.Start();
                if ((process.StandardOutput != null))
                {
                    var result = process.StandardOutput.ReadToEnd().Trim().Replace("\"",

"");
                    var lines = result.Split('\n');

                    var firstLineIndex = 1 + lines.Cast<string>().ToList().FindIndex(l =>

l.Contains("Hostname"));
                    for (var i = firstLineIndex; i < lines.Count() && firstLineIndex > 0; i

++)
                    {
                        var fields = lines[i].Split(',');
                        var time = DateTime.Now;
                        FileStream fs = new FileStream(@"C:\SFD\log.txt", FileMode.Append);
                        StreamWriter sw = new StreamWriter(fs);

                        if(firstLineIndex.ToString()=="Hostname")
                        {
                             Console.SetOut(sw);
                             Console.WriteLine(e.FullPath + "\t" + e.ChangeType + "\t" +

time + "\t" + e.Name + "\t" + fields[0]);
                             sw.Close();
                        }
                    }
                }
                process.WaitForExit();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                process.Close();
            }

        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}

Body:
To my knowledge you can use WMI to at least get the ones which are connected to the share. You need to reference System.Management.dll, create an instance of ManagementObjectSearcher and there you go.

The problem is usally finding the correct classes, the reference for WMI can be found here under WMI Reference. For your use case you will need the Win32_ConnectionShare class. Take into consideration that the application needs to run with admin priviledges in order to access data from that class.

A little example code for your use case (according to the above mentioned documentation antecedent represents the server side while dependent represents the client side):

// Create a query
SelectQuery query = new SelectQuery("SELECT * FROM Win32_ConnectionShare");

// Initialize an object searcher with this query
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

// Get the resulting collection and loop through it
foreach (ManagementObject mo in searcher.Get())
{
    string antecedent = mo["antecedent"].ToString();
    string dependent = mo["dependent"].ToString();

    ManagementObject share = new ManagementObject(antecedent);
    ManagementObject server = new ManagementObject(dependent);

    Console.WriteLine(server["UserName"].ToString());
    Console.WriteLine(server["ComputerName"].ToString());
    Console.WriteLine(server["ShareName"].ToString());
}


来源: stackexchange

问:
How to get the current day in Java using LocalDateTime in Java?
I'm trying to get the current local day using:

```<code>LocalDateTime now = LocalDateTime.now();
DayOfWeek  CurrentDay = DayOfWeek.of(now.getDayOfMonth());
</code>```

For me it's Monday but I get Thursday. Why and how can I resolve this?

答:
Using LocalDateTime.getDayOfMonth will give you the actual day in the month (beetween 1 - 31)

You are trying to convert that value into the DayOfWeek enum using DayOfWeek.of(int) method accept a value between 1 to 7

The int value follows the ISO-8601 standard, from 1 (Monday) to 7 (Sunday)

Simply use LocalDateTime.getDayOfWeek that return the enum directly.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get the current local day using:

LocalDateTime now = LocalDateTime.now();
DayOfWeek  CurrentDay = DayOfWeek.of(now.getDayOfMonth());

For me it's Monday but I get Thursday. Why and how can I resolve this?


问:
Test app for iPad mini
I am developing application for ipad. I have tested application for ipad 9.7 inch. I want to test app for ipad-mini which is a client requirement. How can i test my app for iPad mini. Although ipad-mini and ipad 9.7 inch have same pixel ratio but according to client there is still an issue on ipad-mini.
I am currently using xcode 8.3.
There is no simulator device available for iPad mini.

答: There's no simulator for iPad mini. Either get one physical device or test on older version of ipad with similar resolution (or screen ratio)</p>

Title: Test app for iPad mini


问:
Reactjs Module not found | Css import
I will try to be concise, I must work on a Reactjs project for school project, my task is to take a existing html/css theme and and put it in React components.

But I have a problem since the start, I used CreateReactApp for a clean start and import index.css of the theme.
Create a basic form base on the theme and have this error. (She disapear when I delete index.css)

Error I see
Failed to compile

./src/css/index.css

Module not found: Can't resolve '../images/category-1-bg.jpg' in
  'C:\Users\50031\Documents\React-Project-master\src\css'

Structure of the project is that
Structure project

Thanks so much, I already check for an answer but I suck as hell in code and understand nothing.... Sorry

答: Your images directory is not inside css directory and that is what the error says. This is because somewhere in your index.css you have not assigned correct path for the images. Assign correct paths to the images in your index.css and the app should compile.

Title: Reactjs Module not found | Css import


问:
CODEIGNITER How to output 0 if select is NULL?
i want to ask, how to output 0 when its null ?
i have try IFNULL and COALESCE, it's not working.

```<code>$this->db->select('produk_tb.kode_produk, produk_tb.nama,  kategori_tb.nama as namakategori');
$this->db->from('produk_tb');

$this->db->join('penjualan_detail_tb', 'produk_tb.kode_produk = penjualan_detail_tb.kode_produk', 'inner');
$this->db->select_sum('penjualan_detail_tb.jumlah','jual');

$this->db->join('pembelian_detail_tb', 'produk_tb.kode_produk = pembelian_detail_tb.kode_produk', 'inner');
$this->db->select_sum('pembelian_detail_tb.jumlah','beli');

$this->db->join('kategori_tb', 'produk_tb.kode_kategori = kategori_tb.kode_kategori', 'inner');

$this->db->group_by('kode_produk');
$kontak = $this->db->get()->result();
$this->response($kontak, 200);
</code>```

Thanks in advance

答:
$this->db->select('select COALESCE(field_name, 0) as field_name_alias');

$this->db->from('your_table');

try this one

Body:
i want to ask, how to output 0 when its null ?
i have try IFNULL and COALESCE, it's not working.

$this->db->select('produk_tb.kode_produk, produk_tb.nama,  kategori_tb.nama as namakategori');
$this->db->from('produk_tb');

$this->db->join('penjualan_detail_tb', 'produk_tb.kode_produk = penjualan_detail_tb.kode_produk', 'inner');
$this->db->select_sum('penjualan_detail_tb.jumlah','jual');

$this->db->join('pembelian_detail_tb', 'produk_tb.kode_produk = pembelian_detail_tb.kode_produk', 'inner');
$this->db->select_sum('pembelian_detail_tb.jumlah','beli');

$this->db->join('kategori_tb', 'produk_tb.kode_kategori = kategori_tb.kode_kategori', 'inner');

$this->db->group_by('kode_produk');
$kontak = $this->db->get()->result();
$this->response($kontak, 200);

Thanks in advance


问:
Exception in onSurfaceTextureUpdated when Thread.start() is invoked
I'am writing Tess-two based OCR system for android and stumbled upon strange obstacle. I actually use TextureView connected with deprecated Camera and when I try to execute this code on my Huawei P8:

```<code>@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
    Log.d("frame", "update frame");
    if(btmQueue.size()<10)
        btmQueue.add(mTextureView.getBitmap());
    System.out.println(mOCRWorker.isAlive());
    if(mOCRWorker.isAlive()==false)
    {
        mOCRWorker.start();
    }
}

Thread mOCRWorker = new Thread(new Runnable() {

    @Override
    public void run() {
        Log.d("Ocr:", "Running thread!");
        if(apiInit==true) {
            if (btmQueue.size() > 0) {
                Bitmap bmp = btmQueue.pollFirst();
                baseAPI.setImage(bmp);
                String recognizedText = baseAPI.getUTF8Text();
                Log.d("Recognized: ", recognizedText);
            }
        }
        Log.d("Ocr:", "Thread finished!");

    }
});
</code>```

I get this error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.myApp, PID: 18386
java.lang.IllegalThreadStateException: Thread already started
at java.lang.Thread.checkNotStarted(Thread.java:864)
at java.lang.Thread.start(Thread.java:1074) [...]
</code>```

I thought that that if isAlive() gives me false then my Thread is actually dead. Do you have any clue what is going on?

答:
Okey, I figured it out:
Method start() can't be invoked more than once for any Thread - even and especially when Thread were executed. I put while(ocrShouldWork) loop inside my Thread to keep it working till I turn it off. </p>

Body:
I'am writing Tess-two based OCR system for android and stumbled upon strange obstacle. I actually use TextureView connected with deprecated Camera and when I try to execute this code on my Huawei P8:

@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
    Log.d("frame", "update frame");
    if(btmQueue.size()<10)
        btmQueue.add(mTextureView.getBitmap());
    System.out.println(mOCRWorker.isAlive());
    if(mOCRWorker.isAlive()==false)
    {
        mOCRWorker.start();
    }
}

Thread mOCRWorker = new Thread(new Runnable() {

    @Override
    public void run() {
        Log.d("Ocr:", "Running thread!");
        if(apiInit==true) {
            if (btmQueue.size() > 0) {
                Bitmap bmp = btmQueue.pollFirst();
                baseAPI.setImage(bmp);
                String recognizedText = baseAPI.getUTF8Text();
                Log.d("Recognized: ", recognizedText);
            }
        }
        Log.d("Ocr:", "Thread finished!");

    }
});

I get this error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.myApp, PID: 18386
java.lang.IllegalThreadStateException: Thread already started
at java.lang.Thread.checkNotStarted(Thread.java:864)
at java.lang.Thread.start(Thread.java:1074) [...]

I thought that that if isAlive() gives me false then my Thread is actually dead. Do you have any clue what is going on?


问:
How to store a state in localstorage for react?
I'm trying to store my checkbox checked value into the localstorage in my react app. But everytime I store, it will store a previous state. Below is my code:

For render side:

```<code>  render () {
    return (
                      <Checkbox
                        checked={this.state.checkedCheckpoint}
                        onChange={() => this.onChange('checkpoint')}
                      >
                      </Checkbox>
          )
</code>```

For the onchange method:

```<code>  onChange (value){
    const { checkedCheckpoint } = this.state

    if (value === 'checkpoint')
    {
      if (checkedCheckpoint)
      {
        this.setState({checkedCheckpoint : false})
        console.log(checkedCheckpoint)
      }
      else
      {
        this.setState({checkedCheckpoint : true})
        console.log(checkedCheckpoint)
      }
    }
    localStorage.setObject('checkedCheckpoint', checkedCheckpoint)
</code>```

What I mean by previous state is:
If I initialize my checkpoint to be true, after I unchecked, I should get checkpoint: false right? But I get checkedCheckpoint: true. If I checked it, I should get checkedCheckpoint: true right? I will get checkedCheckpoint: false. Seems like it will always follow the previous state in localstorage. Anyone knows what's wrong?

答:
Perhaps, you can do something like this:

```<code><Checkbox
    checked={this.state.checkedCheckpoint}
    onChange={() => this.setState((prevState) => ({checkedCheckpoint: !prevState.checkedCheckpoint}),
    () =>{console.log(this.state.checkedCheckpoint)})}
>
</Checkbox>
</code>```

Also, the issue with your code was that it doesn't account for the fact that state in react setState happens asynchronously. As a consequence, it'll always show a previous state while logging.

Body:
I'm trying to store my checkbox checked value into the localstorage in my react app. But everytime I store, it will store a previous state. Below is my code:

For render side:

  render () {
    return (
                      <Checkbox
                        checked={this.state.checkedCheckpoint}
                        onChange={() => this.onChange('checkpoint')}
                      >
                      </Checkbox>
          )

For the onchange method:

  onChange (value){
    const { checkedCheckpoint } = this.state

    if (value === 'checkpoint')
    {
      if (checkedCheckpoint)
      {
        this.setState({checkedCheckpoint : false})
        console.log(checkedCheckpoint)
      }
      else
      {
        this.setState({checkedCheckpoint : true})
        console.log(checkedCheckpoint)
      }
    }
    localStorage.setObject('checkedCheckpoint', checkedCheckpoint)

What I mean by previous state is:
If I initialize my checkpoint to be true, after I unchecked, I should get checkpoint: false right? But I get checkedCheckpoint: true. If I checked it, I should get checkedCheckpoint: true right? I will get checkedCheckpoint: false. Seems like it will always follow the previous state in localstorage. Anyone knows what's wrong?

Body:
Perhaps, you can do something like this:

<Checkbox
    checked={this.state.checkedCheckpoint}
    onChange={() => this.setState((prevState) => ({checkedCheckpoint: !prevState.checkedCheckpoint}),
    () =>{console.log(this.state.checkedCheckpoint)})}
>
</Checkbox>

Also, the issue with your code was that it doesn't account for the fact that state in react setState happens asynchronously. As a consequence, it'll always show a previous state while logging.


问:
What are the differences between editor templates and partial views?
I am simply looking for how these two are different and what are their pros and cons?

It seems you can do all with partial views that you can do with templates.

答:
If you are referring to EditorTemplates (rather than inline timeplates), then there are some big differences.  First, partial views require you to specify your view when you use them, while templates work on the type of the data object.

Second, because templates work on data types, then when you make a change to the template, it changes it everywhere that type is used, not just where the partial view is used (this can be a disadvantage as well in some cases).

Third, templates are passed additional information that partial views are not, in particular you recieve Model Metadata, such as that created by attributes.

ContentLicense: CC BY-SA 2.5


问:
Why does fopen() not recognize my file's name?
The programm should be able to open a file like myFile.txt,
alltough it's real name is myFile without the extension .txt.
So I wrote the function called removeFileExtension() in order
to achieve that.

It does open my file by copying the string from text into filename:

```<code>strcpy(filename,text);
FILE *fp = fopen(filename, "r");
</code>```

So I tried to check what the difference between text and my processed
string from removeFileExtension is.

To check if it even works I mate a function called strComparison(),
which returns either 0 when it is qual or 1 if unequal.
The thing is, after removing the file extension, it shows that both strings
are qual, but I am still not able to open the file.

When I type in ./a.out myFile.txt my comparison function returns 0,
it is equal, but fopen() still is not able to open the file,
respectively I allways get a Segmentation fault.

Does anyone see the problem here?
Why am I getting a Segmentation fault?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removeFileExtension(char *haystack);
int strComparison(char *one, char *two);

int main(int argc, char const *argv[])
{
  //----------------------------------------------------------------------------
  // CHECK INPUT VALIDITY
  //
  if (argc != 2)
  {
    printf("Usage: ./ass2 [file-name]\n");
    return 1;
  }

  //----------------------------------------------------------------------------
  // OPEN FILE (INITIAL)
  //
  char filename[32];
  strcpy(filename, argv[1]);
  FILE *fp = fopen(filename, "r");                                       //FOPEN
  //FILE *fp = fopen("start_of_story\0txt", "r");   // this way does work
  if (fp == NULL)
  {
    // IF NOT FOUND: REMOVE EXTENSION
    removeFileExtension(filename);
    char text[] = "myFile\0";
    int ret_val = -1;
    ret_val = strComparison(filename, text);
    if (ret_val == 0)
      printf("[DEBUG] equal\n");
    else
      printf("[DEBUG] unequal\n");

    printf("[DEBUG] ret_val: %d\n", ret_val);
    printf("[DEBUG] '%s'\n", filename);
    FILE *fp = fopen(filename, "r");                                     //FOPEN

    // IF STILL DOESN'T WORK: ERROR
    if (fp == NULL)
    {
      printf("[ERR] Could not read file %s.\n", filename);
      return 3;
    }
  }

  //--------------------------------------------------------------------------
  // READ DATA (INITIAL)
  //
  int bufsize = 1024;
  char *buffer = malloc(bufsize * sizeof(char));                      //MALLOC
  if (!buffer)
  {
    printf("[ERR] Out of memory.\n");
    return 2;
  }
  fseek(fp, 0, SEEK_SET);
  fread(buffer, bufsize, 1, fp);

  printf("[DEBUG] %s\n", buffer);
  fclose(fp);                                                           //FCLOSE

  free(buffer);
  buffer = NULL;
  return 0;
}

void removeFileExtension(char *haystack)
{
  char needle[1] = ".";
  char *retp;   // return pointer
  retp = strstr(haystack,needle);
  if (*retp == '.')
  {
    while (*retp != '\0')
    {
      *retp++ = '\0';
    }
    printf("[DEBUG] %s\n", haystack);
  }
}

int strComparison(char *one, char *two)
{
  do
  {
    printf("[DEBUG] '%c' == '%c'\n", *one, *two);
    if (*one++ != *two++)
    {
      return 1; // return 1 if unqual
    }
  }
  while ( (*one != '\0') || (*two != '\0') );
  return 0; // return 0 if qual
}
</code>```

Resulting output:

```<code>user@host ~/Desktop $ ./a.out myFile.txt
[DEBUG] myFile
[DEBUG] 'm' == 'm'
[DEBUG] 'y' == 'y'
[DEBUG] 'F' == 'F'
[DEBUG] 'i' == 'i'
[DEBUG] 'l' == 'l'
[DEBUG] 'e' == 'e'
[DEBUG] equal
[DEBUG] ret_val: 0
[DEBUG] 'myFile'
[ERR] Could not read file myFile.
user@host ~/Desktop $
</code>```

答:
Quoting C11, chapter 7.24.5.7

```<code>char *strstr(const char *s1, const char *s2);
</code>```

The strstr function locates the first occurrence in the string pointed to by s1 of the
  sequence of characters (excluding the terminating null character) in the string pointed to
  by s2.

So, both the arguments passed to strstr has to be  strings. In your case,

```<code> char needle[1] = ".";
</code>```

is not a string. You did not allow the space for the null-terminator. Either use

char needle[2] = ".";, at least, or,

char needle[ ] = ".";, or,

char const* needle = ".";

As a side effect, whenever the call to removeFileExtension() is reached, you'll face with undefined behavior

That said, beware!!

You are doing something like

```<code>retp = strstr(haystack,needle);
  if (*retp == '.')
</code>```

i.e., dereferencing the returned pointer from strstr(). If, strstr() returns a NULL pointer, you'll again be trapped in UB.

EDIT:

For those who still has confusion about string, check definition in chapter §7.1.1 (emphasis mine)

A string is a contiguous sequence of characters terminated by and including the first null
  character. [...]

Body:
The programm should be able to open a file like myFile.txt,
alltough it's real name is myFile without the extension .txt.
So I wrote the function called removeFileExtension() in order
to achieve that.

It does open my file by copying the string from text into filename:

strcpy(filename,text);
FILE *fp = fopen(filename, "r");

So I tried to check what the difference between text and my processed
string from removeFileExtension is.

To check if it even works I mate a function called strComparison(),
which returns either 0 when it is qual or 1 if unequal.
The thing is, after removing the file extension, it shows that both strings
are qual, but I am still not able to open the file.

When I type in ./a.out myFile.txt my comparison function returns 0,
it is equal, but fopen() still is not able to open the file,
respectively I allways get a Segmentation fault.

Does anyone see the problem here?
Why am I getting a Segmentation fault?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removeFileExtension(char *haystack);
int strComparison(char *one, char *two);

int main(int argc, char const *argv[])
{
  //----------------------------------------------------------------------------
  // CHECK INPUT VALIDITY
  //
  if (argc != 2)
  {
    printf("Usage: ./ass2 [file-name]\n");
    return 1;
  }

  //----------------------------------------------------------------------------
  // OPEN FILE (INITIAL)
  //
  char filename[32];
  strcpy(filename, argv[1]);
  FILE *fp = fopen(filename, "r");                                       //FOPEN
  //FILE *fp = fopen("start_of_story\0txt", "r");   // this way does work
  if (fp == NULL)
  {
    // IF NOT FOUND: REMOVE EXTENSION
    removeFileExtension(filename);
    char text[] = "myFile\0";
    int ret_val = -1;
    ret_val = strComparison(filename, text);
    if (ret_val == 0)
      printf("[DEBUG] equal\n");
    else
      printf("[DEBUG] unequal\n");

    printf("[DEBUG] ret_val: %d\n", ret_val);
    printf("[DEBUG] '%s'\n", filename);
    FILE *fp = fopen(filename, "r");                                     //FOPEN

    // IF STILL DOESN'T WORK: ERROR
    if (fp == NULL)
    {
      printf("[ERR] Could not read file %s.\n", filename);
      return 3;
    }
  }

  //--------------------------------------------------------------------------
  // READ DATA (INITIAL)
  //
  int bufsize = 1024;
  char *buffer = malloc(bufsize * sizeof(char));                      //MALLOC
  if (!buffer)
  {
    printf("[ERR] Out of memory.\n");
    return 2;
  }
  fseek(fp, 0, SEEK_SET);
  fread(buffer, bufsize, 1, fp);

  printf("[DEBUG] %s\n", buffer);
  fclose(fp);                                                           //FCLOSE

  free(buffer);
  buffer = NULL;
  return 0;
}

void removeFileExtension(char *haystack)
{
  char needle[1] = ".";
  char *retp;   // return pointer
  retp = strstr(haystack,needle);
  if (*retp == '.')
  {
    while (*retp != '\0')
    {
      *retp++ = '\0';
    }
    printf("[DEBUG] %s\n", haystack);
  }
}

int strComparison(char *one, char *two)
{
  do
  {
    printf("[DEBUG] '%c' == '%c'\n", *one, *two);
    if (*one++ != *two++)
    {
      return 1; // return 1 if unqual
    }
  }
  while ( (*one != '\0') || (*two != '\0') );
  return 0; // return 0 if qual
}

Resulting output:

user@host ~/Desktop $ ./a.out myFile.txt
[DEBUG] myFile
[DEBUG] 'm' == 'm'
[DEBUG] 'y' == 'y'
[DEBUG] 'F' == 'F'
[DEBUG] 'i' == 'i'
[DEBUG] 'l' == 'l'
[DEBUG] 'e' == 'e'
[DEBUG] equal
[DEBUG] ret_val: 0
[DEBUG] 'myFile'
[ERR] Could not read file myFile.
user@host ~/Desktop $

Body:
Quoting C11, chapter 7.24.5.7

char *strstr(const char *s1, const char *s2);

The strstr function locates the first occurrence in the string pointed to by s1 of the
  sequence of characters (excluding the terminating null character) in the string pointed to
  by s2.

So, both the arguments passed to strstr has to be  strings. In your case,

 char needle[1] = ".";

is not a string. You did not allow the space for the null-terminator. Either use

char needle[2] = ".";, at least, or,

char needle[ ] = ".";, or,

char const* needle = ".";

As a side effect, whenever the call to removeFileExtension() is reached, you'll face with undefined behavior

That said, beware!!

You are doing something like

retp = strstr(haystack,needle);
  if (*retp == '.')

i.e., dereferencing the returned pointer from strstr(). If, strstr() returns a NULL pointer, you'll again be trapped in UB.

EDIT:

For those who still has confusion about string, check definition in chapter §7.1.1 (emphasis mine)

A string is a contiguous sequence of characters terminated by and including the first null
  character. [...]


问:
Filter pcap pap protocol without pyshark
I want to access data in pap packets, currently i'm using pyshark with the following code

```<code>import pyshark,sys

cap = pyshark.FileCapture('test.pcap',display_filter='ppp && not ppp.length')

for packet in cap:
        if packet.pap.get_field_value('peer_id'):
            print ('user: '+packet.pap.peer_id+" logged in")
</code>```

and it works fine on my pc and raspberrypi unfortunately i want to use this code on openwrt/lede router on which pyshark can't be installed due to ccache error:

```<code>unable to execute 'ccache_cc': no such file or directory
</code>```

which i assumed that openwrt lacks some compiler features so I tried to install other pcap parsing libraries and could install scapy, dpkt and pypcapfile and they all installed fine so how can I convert my code to use one of these libraries

答:
With Scapy (use the development version from GitHub), you can try:</p>

```<code>from scapy.all import PcapReader, PPP_PAP_Request

for pkt in PcapReader('test.pcap'):
    if PPP_PAP_Request in pkt:
        print(pkt.sprintf('user: %PPP_PAP_Request.username% logged in'))
</code>```

Body:
I want to access data in pap packets, currently i'm using pyshark with the following code

import pyshark,sys

cap = pyshark.FileCapture('test.pcap',display_filter='ppp && not ppp.length')

for packet in cap:
        if packet.pap.get_field_value('peer_id'):
            print ('user: '+packet.pap.peer_id+" logged in")

and it works fine on my pc and raspberrypi unfortunately i want to use this code on openwrt/lede router on which pyshark can't be installed due to ccache error:

unable to execute 'ccache_cc': no such file or directory

which i assumed that openwrt lacks some compiler features so I tried to install other pcap parsing libraries and could install scapy, dpkt and pypcapfile and they all installed fine so how can I convert my code to use one of these libraries

Body:
With Scapy (use the development version from GitHub), you can try:

from scapy.all import PcapReader, PPP_PAP_Request

for pkt in PcapReader('test.pcap'):
    if PPP_PAP_Request in pkt:
        print(pkt.sprintf('user: %PPP_PAP_Request.username% logged in'))


问:
iOS 11.2 beta released, but not a corresponding Xcode beta
I've just installed iOS 11.2 Beta and downloaded the latest Xcode (which is 9.1 - beta 2. 9B46).

But when I try to run the app on the device it says it doesn't have the necessary support files.

So how am I supposed to develop with 11.2 beta if there's no corresponding Xcode yet?

答:
As a temporal solution, you could download Xcode beta 9.2b2 and use device support from that Xcode.

```<code>sudo ln -s /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.2\ \(15C5097c\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.2\ \(15C5097c\)
</code>```

after that restart Xcode and replug device

Body:
As a temporal solution, you could download Xcode beta 9.2b2 and use device support from that Xcode.

sudo ln -s /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.2\ \(15C5097c\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.2\ \(15C5097c\)

after that restart Xcode and replug device


问:
Karate API Testing - Access variable value across scenario in a feature file
I am running into this situation (similar to this) when trying to do the following:

```<code>Scenario: Create User
Given path 'user'
    And request read('user.json');
    When method post
    Then status 200
    And def user_id = response.userId

Scenario: Test A
   Given path 'user/' + user_id <- Received javascript error here
   ...

Scenario: Test B
   Given path 'user/' + user_id <- Received javascript error here
   ...

Scenario: Test A
   Given path 'user/' + user_id <- Received javascript error here
   ...
</code>```

Basically what i am trying to do is create a user in my database first, then run it through a series of test and use a last scenario to delete this user. Therefore, i need to share the user_id value across multiple scenarios. Background doesn't work for me because that means i have to create a new user for each scenario. I have seen in the demo that a simple way would be to put all test under 1 scenario but i don't feel that it is right to put all tests on 1 scenario

I have reviewed the karate demo but i did not come across any sample code that will help my situation. May i know the right way to do this in Karate? Thanks.

答:
I think you are missing the callonce keyword. Understand it and then look at the demos, for example, this one: callonce.feature.

You will need to move the 'common' code into a separate feature, but that is the right thing to do, because you will typically want it re-usable by multiple feature files as well.

Body:
I am running into this situation (similar to this) when trying to do the following:

Scenario: Create User
Given path 'user'
    And request read('user.json');
    When method post
    Then status 200
    And def user_id = response.userId

Scenario: Test A
   Given path 'user/' + user_id <- Received javascript error here
   ...

Scenario: Test B
   Given path 'user/' + user_id <- Received javascript error here
   ...

Scenario: Test A
   Given path 'user/' + user_id <- Received javascript error here
   ...

Basically what i am trying to do is create a user in my database first, then run it through a series of test and use a last scenario to delete this user. Therefore, i need to share the user_id value across multiple scenarios. Background doesn't work for me because that means i have to create a new user for each scenario. I have seen in the demo that a simple way would be to put all test under 1 scenario but i don't feel that it is right to put all tests on 1 scenario

I have reviewed the karate demo but i did not come across any sample code that will help my situation. May i know the right way to do this in Karate? Thanks.


问:
Liquibase changelog without MD5SUM
I have a database here which is updated using Liquibase. If I understand correctly, Liquibase will apply a changeset and write a line to the DATABASECHANGELOG table with the execution date and an MD5 checksum. This way, Liquibase can find out when a changeset (unexpectedly) changes.

However, in this database, many (most) of the MD5SUM entries are NULL. I have no idea why that should be the case. Is this in any way a normal mode of operation?

When using the Liquibase status command, I see many ‘unapplied’ changes. How can Liquibase determine that without the MD5 sum? Or are changesets without MD5 sums considered changed.

答:
The DATABASECHANGELOG in question was used by two different programs. This may be questionable, but used to work quite well.

Until… the programs started to use different versions of Liquibase with different formats of the MD5SUM. Upon detecting this, Liquibase writes NULL to the whole column (which is questionable in itself), thereby removing all the checksums for all the other programs. Depending on the order of Liquibase runs, different sets of checksums remained NULL in the end.

Title: Liquibase changelog without MD5SUM


问:
React Native: pass touch events through ScrollView to elements lower in the z plane
I'm trying to write a parallax element that has multiple panes which scroll at different rates.

To achieve this, I have multiple View absolutely positioned and stacked in the z plane, with a ScrollView on top to capture the drag events, from which I'll animate the top position and opacity of the lower panes. (Reason for using a ScrollView is to benefit from the bouncing and momentum animation that gives us.)

However, the lower panes may contain elements that want to accept touches (as opposed to scrolls). The problem I'm having is that the ScrollView captures these touches, and there doesn't seem to be a mechanism to pass them on. Basically, I want the ScrollView to respond to drags, but the lower elements to respond to touches.

Is there a way to achieve that?

答:
I've successfully used https://github.com/rome2rio/react-native-touch-through-view for that on iOS.

However on Android, somehow click events are not getting trough while swiping works for underlying view.


问:
csv export data with utf-8 encoding is garbled php
So I have this page that converts the database into csv.

Database is set to utf8, also when converting is set to utf8.

problem is after opening the csv file in excel, data is garbled. It looks like this:

```<code>KN01001     | 荳陦帙,admin@listmaster.com"  | List Master          |                |
KN01002     | 譌ｭ譚ｾ                        | information@e877.jp  |   Info Master  |
</code>```

but when I try to drag-open the file into notepad, data is alright, it shows:

```<code>"KN01001","荳陦帙","admin@listmaster.com","List Master"
"KN01002","譌ｭ譚ｾ蝣","information@e877.jp","Info Master"
</code>```

How can I make it look alright in excel?

UPDATE:

I tried adding PHPExcel as suggested, still gives me same garbled output.

I included my code here, maybe someone could help edit the codes.

Controller:

```<code>public function bg_convcsv($sendTo, $searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax) {

        $sendTo = rawurldecode($sendTo);

        $headerArray = array("foreign key", "prefecture_id", "industry_id", "offset", "name", "email", "tel", "fax", "address", "url", "flexible_1", "flexible_2", "flexible_3", "flexible_4", "flexible_5", "sequence", "del_flg", "create_date", "create_user", "update_date", "update_user", "site_name");

        // Header
        $header = str_replace(",", "", $headerArray);

        $datas = implode(',', $header) . "\r\n";

        // Body
        $limit = 50000;
        $start = 0;
        do {
            $list = $this->user_model->get_users($searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax, $limit, $start);
            foreach($list as $body)
            {
                $email = //some codes to clean email
                $url = // some codes to clean url
                $datas .= '"' .$body["id"].'"'.",".'"' .$body["prefecture_id"].'"'.",".'"' .$body["industry_id"].'"'.",".'"' .$body["offset"].'"'.",".'"' .$body["name"].'"'.",".'"' .$email .'"'. ",".'"' .$body["tel"].'"'. ",".'"' .$body["fax"].'"'.",".'"' .$body["address"].'"'.",".'"' .$url.'"'.",".'"' .$body["flexible_1"].'"'.",".'"' .$body["flexible_2"].'"'.",".'"' .$body["flexible_3"].'"'.",".'"' .$body["flexible_4"].'"'.",".'"' .$body["flexible_5"].'"'.",".'"' .$body["sequence"].'"'.",".'"' .$body["del_flg"].'"'.",".'"' .$body["create_date"].'"'.",".'"' .$body["create_user"].'"'.",".'"' .$body["update_date"].'"'.",".'"' .$body["update_user"].'"'.",".'"' .$body["site_name"].'"'."\r\n";

            }

            $start += $limit;
        }while(count($list) > 0);

        $fileName = "listmaster_".date('YmdHis').".csv";
        $csv_handler = fopen ('/var/www/citest/csv/'.$fileName,'w');
        fwrite ($csv_handler,$datas);
        fclose ($csv_handler);
}

public function download() {

            log_message('debug', 'starting download.');
            $file = $_GET['file'];
            $filePath = '/var/www/citest/csv/'.$file;

            if(!$file){ // file does not exist
                die('file not found');
            } else {
                header('HTTP/1.1 200 OK');
                header('Cache-Control: no-cache, must-revalidate');
                header("Pragma: no-cache");
                header("Expires: 0");
                header("Content-type: text/csv; charset=UTF-8");
                header("Content-Disposition: attachment; filename=$file");

                // read the file from disk
                log_message('debug', 'reading file.');
                readfile($filePath);
                log_message('debug', 'reading file done');
            }
    }
</code>```

UPDATE 2:

Here's How I did it using PHPExcel

```<code>require_once('/var/www/citest/application/third_party/PHPExcel-1.8/Classes/PHPExcel.php');
require_once('/var/www/citest/application/third_party/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php');

...
...

public function bg_convcsv($sendTo, $searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax) {

        $sendTo = rawurldecode($sendTo);

        //Create a new Object
        $objPHPExcel = new PHPExcel();
        // Set the active Excel worksheet to sheet 0
        $objPHPExcel->setActiveSheetIndex(0);

        $headerArray = array("foreign key", "prefecture_id", "industry_id", "offset", "name", "email", "tel", "fax", "address", "url", "flexible_1", "flexible_2", "flexible_3", "flexible_4", "flexible_5", "sequence", "del_flg", "create_date", "create_user", "update_date", "update_user", "site_name");

        // Header
        $rowNumberH = 1; //set in which row title is to be printed
        $colH = 'A'; //set in which column title is to be printed

        foreach($headerArray as $h){
            $objPHPExcel->getActiveSheet()->setCellValue($colH.$rowNumberH,$h);
            $colH++;
        }

        // Body
        $limit = 50000;
        $start = 0;
        do {
            $list = $this->user_model->get_users($searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax, $limit, $start);
            $rowCount = 2; // set the starting row from which the data should be printed
            log_message('debug', "Query: offset:{$start} limit:{$limit} done");
            foreach($list as $body)
            {
                //$email =

                //$url =

                $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $body['id']);
                $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $body['prefecture_id']);
                $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $body['industry_id']);
                $objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $body['offset']);
                $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount, $body['name']);
                $objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount, $email);
                $objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount, $body['tel']);
                $objPHPExcel->getActiveSheet()->SetCellValue('H'.$rowCount, $body['fax']);
                $objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount, $body['address']);
                $objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount, $url);
                $objPHPExcel->getActiveSheet()->SetCellValue('K'.$rowCount, $body['flexible_1']);
                $objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount, $body['flexible_2']);
                $objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount, $body['flexible_3']);
                $objPHPExcel->getActiveSheet()->SetCellValue('N'.$rowCount, $body['flexible_4']);
                $objPHPExcel->getActiveSheet()->SetCellValue('O'.$rowCount, $body['flexible_5']);
                $objPHPExcel->getActiveSheet()->SetCellValue('P'.$rowCount, $body['sequence']);
                $objPHPExcel->getActiveSheet()->SetCellValue('Q'.$rowCount, $body['del_flg']);
                $objPHPExcel->getActiveSheet()->SetCellValue('R'.$rowCount, $body['create_date']);
                $objPHPExcel->getActiveSheet()->SetCellValue('S'.$rowCount, $body['create_user']);
                $objPHPExcel->getActiveSheet()->SetCellValue('T'.$rowCount, $body['update_date']);
                $objPHPExcel->getActiveSheet()->SetCellValue('U'.$rowCount, $body['update_user']);
                $objPHPExcel->getActiveSheet()->SetCellValue('V'.$rowCount, $body['site_name']);
                $rowCount++;

            }

            $start += $limit;
        }while(count($list) > 0);

        $fileName = "listmaster_".date('YmdHis').".csv";

        $objPHPExcel->getActiveSheet()->setTitle($fileName);

        $objPHPExcel->setActiveSheetIndex(0);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->setDelimiter(',');
        $objWriter->save('/var/www/citest/csv/' . $fileName);

}
</code>```

答:
As @luhuiya mentioned, you can use phpexcel in order to have the correct format.

Supposed you already installed phpexcel with composer.

Here is a working example:

```<code><?php

require_once __DIR__ . '/vendor/autoload.php';

/*
You query your data into an array here
$data = ...
*/

$data = [
    [ 'KN01001', '荳陦帙', 'admin@listmaster.com', 'List Master', '' ],
    [ 'KN01002', '譌ｭ譚ｾ', 'information@e877.jp', 'Info Master', '' ],
];

$phpXls = new PHPExcel();

// Fill worksheet from values in array
$phpXls->getActiveSheet()->fromArray($data, null, 'A1');

// Work on PHPExcel object, set worksheet metadata
// Change the ... parts according to your needs
$phpXls->getProperties()->setCreator("...")
    ->setLastModifiedBy("...")
    ->setTitle("...")
    ->setSubject("...")
    ->setDescription("...")
    ->setKeywords("...");

$phpXls->getActiveSheet()->setTitle('...');

// I saw in your examlpe data, that you can have long strings in some columns
// Therefore You can widen the excel columns in order to be readable at full length.
// Get Excel column range and dynamically resize columns
$highestColumn = $phpXls->getActiveSheet()->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
foreach (range(0, $highestColumnIndex) as $columnIndex) {
    $phpXls->getActiveSheet()->getColumnDimensionByColumn($columnIndex)->setAutoSize(true);
}

 // Set active sheet index to the first sheet, so Excel opens this as the first sheet
$phpXls->setActiveSheetIndex(0);

// Save Excel 2007 file
$xlsWriter = PHPExcel_IOFactory::createWriter($phpXls, 'Excel2007');

$xlsWriter->save('your_data.xlsx');
</code>```

Body:
So I have this page that converts the database into csv.

Database is set to utf8, also when converting is set to utf8.

problem is after opening the csv file in excel, data is garbled. It looks like this:

KN01001     | 荳陦帙,admin@listmaster.com"  | List Master          |                |
KN01002     | 譌ｭ譚ｾ                        | information@e877.jp  |   Info Master  |

but when I try to drag-open the file into notepad, data is alright, it shows:

"KN01001","荳陦帙","admin@listmaster.com","List Master"
"KN01002","譌ｭ譚ｾ蝣","information@e877.jp","Info Master"

How can I make it look alright in excel?

UPDATE:

I tried adding PHPExcel as suggested, still gives me same garbled output.

I included my code here, maybe someone could help edit the codes.

Controller:

public function bg_convcsv($sendTo, $searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax) {

        $sendTo = rawurldecode($sendTo);

        $headerArray = array("foreign key", "prefecture_id", "industry_id", "offset", "name", "email", "tel", "fax", "address", "url", "flexible_1", "flexible_2", "flexible_3", "flexible_4", "flexible_5", "sequence", "del_flg", "create_date", "create_user", "update_date", "update_user", "site_name");

        // Header
        $header = str_replace(",", "", $headerArray);

        $datas = implode(',', $header) . "\r\n";

        // Body
        $limit = 50000;
        $start = 0;
        do {
            $list = $this->user_model->get_users($searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax, $limit, $start);
            foreach($list as $body)
            {
                $email = //some codes to clean email
                $url = // some codes to clean url
                $datas .= '"' .$body["id"].'"'.",".'"' .$body["prefecture_id"].'"'.",".'"' .$body["industry_id"].'"'.",".'"' .$body["offset"].'"'.",".'"' .$body["name"].'"'.",".'"' .$email .'"'. ",".'"' .$body["tel"].'"'. ",".'"' .$body["fax"].'"'.",".'"' .$body["address"].'"'.",".'"' .$url.'"'.",".'"' .$body["flexible_1"].'"'.",".'"' .$body["flexible_2"].'"'.",".'"' .$body["flexible_3"].'"'.",".'"' .$body["flexible_4"].'"'.",".'"' .$body["flexible_5"].'"'.",".'"' .$body["sequence"].'"'.",".'"' .$body["del_flg"].'"'.",".'"' .$body["create_date"].'"'.",".'"' .$body["create_user"].'"'.",".'"' .$body["update_date"].'"'.",".'"' .$body["update_user"].'"'.",".'"' .$body["site_name"].'"'."\r\n";

            }

            $start += $limit;
        }while(count($list) > 0);

        $fileName = "listmaster_".date('YmdHis').".csv";
        $csv_handler = fopen ('/var/www/citest/csv/'.$fileName,'w');
        fwrite ($csv_handler,$datas);
        fclose ($csv_handler);
}

public function download() {

            log_message('debug', 'starting download.');
            $file = $_GET['file'];
            $filePath = '/var/www/citest/csv/'.$file;

            if(!$file){ // file does not exist
                die('file not found');
            } else {
                header('HTTP/1.1 200 OK');
                header('Cache-Control: no-cache, must-revalidate');
                header("Pragma: no-cache");
                header("Expires: 0");
                header("Content-type: text/csv; charset=UTF-8");
                header("Content-Disposition: attachment; filename=$file");

                // read the file from disk
                log_message('debug', 'reading file.');
                readfile($filePath);
                log_message('debug', 'reading file done');
            }
    }

UPDATE 2:

Here's How I did it using PHPExcel

require_once('/var/www/citest/application/third_party/PHPExcel-1.8/Classes/PHPExcel.php');
require_once('/var/www/citest/application/third_party/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php');

...
...

public function bg_convcsv($sendTo, $searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax) {

        $sendTo = rawurldecode($sendTo);

        //Create a new Object
        $objPHPExcel = new PHPExcel();
        // Set the active Excel worksheet to sheet 0
        $objPHPExcel->setActiveSheetIndex(0);

        $headerArray = array("foreign key", "prefecture_id", "industry_id", "offset", "name", "email", "tel", "fax", "address", "url", "flexible_1", "flexible_2", "flexible_3", "flexible_4", "flexible_5", "sequence", "del_flg", "create_date", "create_user", "update_date", "update_user", "site_name");

        // Header
        $rowNumberH = 1; //set in which row title is to be printed
        $colH = 'A'; //set in which column title is to be printed

        foreach($headerArray as $h){
            $objPHPExcel->getActiveSheet()->setCellValue($colH.$rowNumberH,$h);
            $colH++;
        }

        // Body
        $limit = 50000;
        $start = 0;
        do {
            $list = $this->user_model->get_users($searchName, $searchAdd, $prefKey, $searchKey, $withEmail, $withTel, $withFax, $limit, $start);
            $rowCount = 2; // set the starting row from which the data should be printed
            log_message('debug', "Query: offset:{$start} limit:{$limit} done");
            foreach($list as $body)
            {
                //$email =

                //$url =

                $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $body['id']);
                $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $body['prefecture_id']);
                $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $body['industry_id']);
                $objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $body['offset']);
                $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount, $body['name']);
                $objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount, $email);
                $objPHPExcel->getActiveSheet()->SetCellValue('G'.$rowCount, $body['tel']);
                $objPHPExcel->getActiveSheet()->SetCellValue('H'.$rowCount, $body['fax']);
                $objPHPExcel->getActiveSheet()->SetCellValue('I'.$rowCount, $body['address']);
                $objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount, $url);
                $objPHPExcel->getActiveSheet()->SetCellValue('K'.$rowCount, $body['flexible_1']);
                $objPHPExcel->getActiveSheet()->SetCellValue('L'.$rowCount, $body['flexible_2']);
                $objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount, $body['flexible_3']);
                $objPHPExcel->getActiveSheet()->SetCellValue('N'.$rowCount, $body['flexible_4']);
                $objPHPExcel->getActiveSheet()->SetCellValue('O'.$rowCount, $body['flexible_5']);
                $objPHPExcel->getActiveSheet()->SetCellValue('P'.$rowCount, $body['sequence']);
                $objPHPExcel->getActiveSheet()->SetCellValue('Q'.$rowCount, $body['del_flg']);
                $objPHPExcel->getActiveSheet()->SetCellValue('R'.$rowCount, $body['create_date']);
                $objPHPExcel->getActiveSheet()->SetCellValue('S'.$rowCount, $body['create_user']);
                $objPHPExcel->getActiveSheet()->SetCellValue('T'.$rowCount, $body['update_date']);
                $objPHPExcel->getActiveSheet()->SetCellValue('U'.$rowCount, $body['update_user']);
                $objPHPExcel->getActiveSheet()->SetCellValue('V'.$rowCount, $body['site_name']);
                $rowCount++;

            }

            $start += $limit;
        }while(count($list) > 0);

        $fileName = "listmaster_".date('YmdHis').".csv";

        $objPHPExcel->getActiveSheet()->setTitle($fileName);

        $objPHPExcel->setActiveSheetIndex(0);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->setDelimiter(',');
        $objWriter->save('/var/www/citest/csv/' . $fileName);

}

Body:
As @luhuiya mentioned, you can use phpexcel in order to have the correct format.

Supposed you already installed phpexcel with composer.

Here is a working example:

<?php

require_once __DIR__ . '/vendor/autoload.php';

/*
You query your data into an array here
$data = ...
*/

$data = [
    [ 'KN01001', '荳陦帙', 'admin@listmaster.com', 'List Master', '' ],
    [ 'KN01002', '譌ｭ譚ｾ', 'information@e877.jp', 'Info Master', '' ],
];

$phpXls = new PHPExcel();

// Fill worksheet from values in array
$phpXls->getActiveSheet()->fromArray($data, null, 'A1');

// Work on PHPExcel object, set worksheet metadata
// Change the ... parts according to your needs
$phpXls->getProperties()->setCreator("...")
    ->setLastModifiedBy("...")
    ->setTitle("...")
    ->setSubject("...")
    ->setDescription("...")
    ->setKeywords("...");

$phpXls->getActiveSheet()->setTitle('...');

// I saw in your examlpe data, that you can have long strings in some columns
// Therefore You can widen the excel columns in order to be readable at full length.
// Get Excel column range and dynamically resize columns
$highestColumn = $phpXls->getActiveSheet()->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
foreach (range(0, $highestColumnIndex) as $columnIndex) {
    $phpXls->getActiveSheet()->getColumnDimensionByColumn($columnIndex)->setAutoSize(true);
}

 // Set active sheet index to the first sheet, so Excel opens this as the first sheet
$phpXls->setActiveSheetIndex(0);

// Save Excel 2007 file
$xlsWriter = PHPExcel_IOFactory::createWriter($phpXls, 'Excel2007');

$xlsWriter->save('your_data.xlsx');


问:
use regular expression to subscribe Kafka topic in Apache Flink
I want to use a regular expression to specify Kafka topics for consuming in Apache Flink, just something like SubscribePatternin Apache Kafka. But it seems there is no method for doing that!

Is there any way to do so?

Thanks!

答:
No, this feature is not available yet but there is a JIRA issue FLINK-8190.

The Flink community is in the process of finalizing the Flink 1.4.0 release. It might be included in 1.4.0 or be part of 1.5.0.


问:
how does client set the certificate chain in the keystore?
Our client need connect server with Two-way SSL authentication.In my case,I use 'keytool -genkey' to generate a keystore and use 'keytool -certreq' to export a csr file.The server side get my csr file and sign it by a CA,and then return me a new cer file signed by CA and the Root CA cer.
The question is how should I update my keystore to finish the server side authentication?
Here is my step to generate keystore.

```<code>keytool -genkey -alias client -keyalg RSA -keystore D://key/client.keystore -validity 3650
keytool -certreq -alias client -keystore D://key/client.keystore -file client.csr
</code>```

Using wireshark,I can find my client send a cert that was generated by my keystore which is self-signed,but the server side actually import the cer file which is signed by CA as the client cer into it's truststore,this made the handshake fail everytime.

PS:The server's cer file is already import to my truststore,so the question is only on the client cer file.Here is the wireshake capture

答:
You need to import the signed certificate and chain into the same keystore that generated the keypair and CSR, using the same alias, and not using the -trustcacerts option.

However your capture shows that the problem is with the server certficate. The client certificate hasn't even been asked for, let alone sent.

Body:
Our client need connect server with Two-way SSL authentication.In my case,I use 'keytool -genkey' to generate a keystore and use 'keytool -certreq' to export a csr file.The server side get my csr file and sign it by a CA,and then return me a new cer file signed by CA and the Root CA cer.
The question is how should I update my keystore to finish the server side authentication?
Here is my step to generate keystore.

keytool -genkey -alias client -keyalg RSA -keystore D://key/client.keystore -validity 3650
keytool -certreq -alias client -keystore D://key/client.keystore -file client.csr

Using wireshark,I can find my client send a cert that was generated by my keystore which is self-signed,but the server side actually import the cer file which is signed by CA as the client cer into it's truststore,this made the handshake fail everytime.

PS:The server's cer file is already import to my truststore,so the question is only on the client cer file.Here is the wireshake capture


问:
How to execute awk command inside python
I am trying to run the following awk command inside python but I get a syntax error related to the quotes:

```<code>import subprocess
COMMAND = "df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"

subprocess.call(COMMAND, shell=True)
</code>```

I tried to escape the quotes but I am still getting the same error.

答:
Try this:</p>

```<code>import subprocess
COMMAND="df /dev/sda1 | awk 'NR==2 {sub(\"%\",\"\",$5); if ($5 >= 80) {printf \"Warning! Space usage is %d%%\", $5}}'"

subprocess.Popen(COMMAND,stdin=subprocess.PIPE,stdout=subprocess.PIPE, shell=True).stdout.read()
</code>```

Body:
I am trying to run the following awk command inside python but I get a syntax error related to the quotes:

import subprocess
COMMAND = "df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"

subprocess.call(COMMAND, shell=True)

I tried to escape the quotes but I am still getting the same error.

Body:
Try this:

import subprocess
COMMAND="df /dev/sda1 | awk 'NR==2 {sub(\"%\",\"\",$5); if ($5 >= 80) {printf \"Warning! Space usage is %d%%\", $5}}'"

subprocess.Popen(COMMAND,stdin=subprocess.PIPE,stdout=subprocess.PIPE, shell=True).stdout.read()


问:
Will domain pointed at multiple IPs randomly redirect?
Question: will a domain name with multiple A records pointed to different domains actually pick one at random for each user? I have seen people claim that, but is that really how it works?

Or would it behave more like -- everyone in New York goes to one IP, everyone somewhere else goes to another, etc?

I realize the more correct solution is to use a load balancer, but still want to know the answer to this.

答:
In its basics Round-Robin (what pointing a domain to multiple IPs or just having multiple records of the same type pointed to different destinations is) returns all IPs in "random" order and the client (the browser or other software the user uses) decides which IP to use.
Commonly the first IP in the list is used. The next time there is a request for this record type the already used IP goes at the last place in the list and the second becomes first and so on.
This type of configuration by itself does not care where the request comes from or if this particular client already made a request and receive the same list.</p>


问:
Why isn't there a format that like fat binaries will allow an executable to run with different instruction sets but on the same architecture?
It would make it possible to have optimized binaries for several processors.

If done right it wouldn't even need to duplicate much data.

答:
If I get the question right, you're asking a format with builds optimized for different CPU's of the same family.

The downside of this is that there is need for more testing. You're not likely to find anything, but it's so embarresing if your final build mistakenly contains the wrong version of the code.

The gains may also not be that great: usually compilers optimize such that they avoid known performance issues with common CPU architectures. You may argue that your software will benefit from SSE instructions on new hardware, but if your application is so demanding that it needs SSE instructions even on recent hardware, your software will be close to unusable on older CPUs.


问:
pointer from one class to another
Hello I want to point "seller" to "name"
but it gives me an error. please help.
I get the error"name was not defined "
how can I make a method to assign seller to an Apartment?
Thank you</p>

```<code>class Person {
    public:
        friend class Apartment;
        Person() {
          cout << "~ ";
        }//constructor
        string name = "Mr.Smith\n";
        string TelNumber = "01";
        int age = 0;
};

class Apartment {
    public:

        string Address = "jyu";
        double Area = 74.0;
        double Price = 320.0;
        int numberOfRooms = 3;
        //string name = "d";
        string *Seller = &name;
        //Apartment(string *Seller = null) {

        //}
        // constructor for seller
         Apartment () {
            string *Seller=nullptr;
         }
       // Apartment::Apartment();
};
</code>```

答:
I add the error. please show me by code

Well, at the time I wrote this answer, still a promise... Anyway, the compilation error you mention likely is the one provoked by this line:

```<code>string* Seller = &name;
</code>```

Explanation: You try to refer to some variable called name. The way you wrote the code, this would initialise the pointer to a class member variable of class appartment (this->name), which does not exist, though, as you commented it out. But even if it existed, it would not be the string object you desired, as you wanted a pointer to the seller's name, not the appartment's name...

Then, there are quite a lot of things that are – uhm – let's just say 'unconventional'...

First, you only have public members in your Person class – so why would you need any friend classes at all??? Even if you make the members private, you should not make Appartment a friend. Instead, provide appropriate public getters. Friendship provides access to private members, and typically these two friends then are very closely related one to another. Imagine you have one class X managing several instances of another one Y. Class Y shall only provide very limited access to its member, but contains some management data that class X relies on. Then you would make X a friend of Y so that X, but no one else, can access the management data. Quite often (but far not always) this is the case if Y is an inner class of X, but still part of Xs public interface...

OK, back to your class:

I assume you want to be able to have different persons with different names, and each having its own phone number - or possibly some having none. I further assume that you do not want these contents to be changed by anybody. So: set them in the constructor and make them private:

```<code>class Person
{
    std::string name;
    std::string phoneNo;
public:
    Person(std::string name, std::string no = "")
        : name(name), phoneNo(no)
    {
          std::cout << "~ ";
    }
};
</code>```

I left out age - actually, prefer the birth day instead: The age not only can, but will change for sure (unless you are programming some game of which the play time is shorter than a year or people simply do not age in...). By using birth day, you do not need to update your person regularly and can calculate the age whenever needed. Oh, and don't add comment's like constructor - every minimally experienced C++ programmer is able to recognise a constructor just by seeing a function with no return value with the name of the class - so you are just spoiling your code.

OK, quite likely, you need to read the person's members, so we yet need some getters to the public section of your class:

```<code>std::string getName() { return name; }
// or alternatively:
std::string name() { return m_name; }
</code>```

I personally prefer the second variant (only a matter of taste, though!), but that requires renaming the member variable (I chose m_name, could as well have been _name or name_ or (almost!) what ever you like; _Name, though, would have been reserved: any identifier starting with underscore followed by upper case letter is as well as any one with two subsequent underscores).

Now you can construct your person's like this:

```<code>Person smith("Mr.Smith", "01");
Person me("Aconcagua"); // no phone number; did you notice the default parameter?
</code>```

The apartment is now quite similar:

```<code>class Apartment
{
    std::string _address;
    // all the other members

    std::string* _seller;
public:
    Apartment(std::string address, /* and other ones as needed! */);

    // getters (and setters?) as needed

    std::string* seller() { return _seller; }
    void seller(Person* person) { _seller = &person->_name; } // big oops!!!
};
</code>```

Aha, not you got me... This way, the apartment would need private access to the person (or person another getter returning the pointer...). Before trying to fix that, I ask you, however: Why would you want to just store the name and not the entire person instead? By storing the pointer, you always get the name via the person's getter, but you additionally have access to all the other information of the person whenever needed... Then you should ask yourself yet another question: Is it relevant that every apartment has a seller or do apartments exist without one? In the latter case, you can add the person to the constructor as parameter, if it appears useful to you, in the former case, you should (and check, if the parameter is nullptr, and if so, e. g. throw some exception...).

I assume now that you can apply this change yourself, so no further code example...

But still some thoughts about organising your data: person's names and addresses consist of different sub-parts, such as forename(s!) and surename or street, house number, post code, city and potentially country (code + name?). Now imagine how ugly it gets if you wanted to search for all appartments e. g. in Neu-Ulm (city in Germany - guess, I live there...). You now would have to parse all addresses in your application - if you have city as a separate member, you can just do string comparisions. One step further: if you manage your cities as separate objects, you reduce the search to simple pointer comparisons - on the one hand, very efficient, on the other, you avoid problems accompanied by the redundancies you introduce by storing the cities' names (large database, and in there, you find all of these: "Neu-Ulm", "Neuulm", "New Ulm", "new Ulm" - just because different users entered the name differently...).

Title: pointer from one class to another

Body:
Hello I want to point "seller" to "name"
but it gives me an error. please help.
I get the error"name was not defined "
how can I make a method to assign seller to an Apartment?
Thank you

class Person {
    public:
        friend class Apartment;
        Person() {
          cout << "~ ";
        }//constructor
        string name = "Mr.Smith\n";
        string TelNumber = "01";
        int age = 0;
};

class Apartment {
    public:

        string Address = "jyu";
        double Area = 74.0;
        double Price = 320.0;
        int numberOfRooms = 3;
        //string name = "d";
        string *Seller = &name;
        //Apartment(string *Seller = null) {

        //}
        // constructor for seller
         Apartment () {
            string *Seller=nullptr;
         }
       // Apartment::Apartment();
};

Body:
I add the error. please show me by code

Well, at the time I wrote this answer, still a promise... Anyway, the compilation error you mention likely is the one provoked by this line:

string* Seller = &name;

Explanation: You try to refer to some variable called name. The way you wrote the code, this would initialise the pointer to a class member variable of class appartment (this->name), which does not exist, though, as you commented it out. But even if it existed, it would not be the string object you desired, as you wanted a pointer to the seller's name, not the appartment's name...

Then, there are quite a lot of things that are – uhm – let's just say 'unconventional'...

First, you only have public members in your Person class – so why would you need any friend classes at all??? Even if you make the members private, you should not make Appartment a friend. Instead, provide appropriate public getters. Friendship provides access to private members, and typically these two friends then are very closely related one to another. Imagine you have one class X managing several instances of another one Y. Class Y shall only provide very limited access to its member, but contains some management data that class X relies on. Then you would make X a friend of Y so that X, but no one else, can access the management data. Quite often (but far not always) this is the case if Y is an inner class of X, but still part of Xs public interface...

OK, back to your class:

I assume you want to be able to have different persons with different names, and each having its own phone number - or possibly some having none. I further assume that you do not want these contents to be changed by anybody. So: set them in the constructor and make them private:

class Person
{
    std::string name;
    std::string phoneNo;
public:
    Person(std::string name, std::string no = "")
        : name(name), phoneNo(no)
    {
          std::cout << "~ ";
    }
};

I left out age - actually, prefer the birth day instead: The age not only can, but will change for sure (unless you are programming some game of which the play time is shorter than a year or people simply do not age in...). By using birth day, you do not need to update your person regularly and can calculate the age whenever needed. Oh, and don't add comment's like constructor - every minimally experienced C++ programmer is able to recognise a constructor just by seeing a function with no return value with the name of the class - so you are just spoiling your code.

OK, quite likely, you need to read the person's members, so we yet need some getters to the public section of your class:

std::string getName() { return name; }
// or alternatively:
std::string name() { return m_name; }

I personally prefer the second variant (only a matter of taste, though!), but that requires renaming the member variable (I chose m_name, could as well have been _name or name_ or (almost!) what ever you like; _Name, though, would have been reserved: any identifier starting with underscore followed by upper case letter is as well as any one with two subsequent underscores).

Now you can construct your person's like this:

Person smith("Mr.Smith", "01");
Person me("Aconcagua"); // no phone number; did you notice the default parameter?

The apartment is now quite similar:

class Apartment
{
    std::string _address;
    // all the other members

    std::string* _seller;
public:
    Apartment(std::string address, /* and other ones as needed! */);

    // getters (and setters?) as needed

    std::string* seller() { return _seller; }
    void seller(Person* person) { _seller = &person->_name; } // big oops!!!
};

Aha, not you got me... This way, the apartment would need private access to the person (or person another getter returning the pointer...). Before trying to fix that, I ask you, however: Why would you want to just store the name and not the entire person instead? By storing the pointer, you always get the name via the person's getter, but you additionally have access to all the other information of the person whenever needed... Then you should ask yourself yet another question: Is it relevant that every apartment has a seller or do apartments exist without one? In the latter case, you can add the person to the constructor as parameter, if it appears useful to you, in the former case, you should (and check, if the parameter is nullptr, and if so, e. g. throw some exception...).

I assume now that you can apply this change yourself, so no further code example...

But still some thoughts about organising your data: person's names and addresses consist of different sub-parts, such as forename(s!) and surename or street, house number, post code, city and potentially country (code + name?). Now imagine how ugly it gets if you wanted to search for all appartments e. g. in Neu-Ulm (city in Germany - guess, I live there...). You now would have to parse all addresses in your application - if you have city as a separate member, you can just do string comparisions. One step further: if you manage your cities as separate objects, you reduce the search to simple pointer comparisons - on the one hand, very efficient, on the other, you avoid problems accompanied by the redundancies you introduce by storing the cities' names (large database, and in there, you find all of these: "Neu-Ulm", "Neuulm", "New Ulm", "new Ulm" - just because different users entered the name differently...).


问:
Initiating a job on another project from a gitlab job
I have been searching the internet for an answer but cannot find anything.

I have a gitlab yml file in one project and would like to start a job for a different project.

If this is possible I would be grateful if someone could point me in the right direction

Thanks

答:
This is possible, answered a similar question a few days ago, check it: Can I combine two branches into a GitLab CI build?

Bottomline, you can use pipeline triggers.


问:
Workaround to Hero Card as attachment markdown formatting?
I know that markdown is supported on the HeroCard "text" field value, even though I couldn't make it work(Tested on MSTeams):

Code

```<code>this.bot.dialog("sendCard", (session, args, next) => {
    session.sendTyping();
    const card = new builder.HeroCard(session);

    card.title("Title");
    card.subtitle("Subtitle");
    card.text("This is some *mardown* text! \n\n - one \n\n - two");

    const msg = new builder.Message(session);

    msg.textFormat("markdown");
    msg.attachments([
        card,
    ]);
    session.endDialog(msg);
});
</code>```

I am wondering how can I achieve this formatting(From mailclark bot in MSTeams):

As you can see, it is a carousel of what I think it might be HeroCards, but they are formatted with bold, code and unordered lists on new paragraphs.

It seems to be a known issue that message attachments do not receive formatting, but how could the mailclark guys achieve it?

Edit:
Unordered list example:

Bold and code example:

答:
MailClark here. You're right: it's a carousel of Hero Cards.

As Gary said, it's mostly simple HTML with a few  and  tags.

But this is the real secret: the list is not HTML it's just regular text and the 3 lines are starting with a good old bullet character: • (we didn't like the style produced by

).

Body:
I know that markdown is supported on the HeroCard "text" field value, even though I couldn't make it work(Tested on MSTeams):

Code

this.bot.dialog("sendCard", (session, args, next) => {
    session.sendTyping();
    const card = new builder.HeroCard(session);

    card.title("Title");
    card.subtitle("Subtitle");
    card.text("This is some *mardown* text! \n\n - one \n\n - two");

    const msg = new builder.Message(session);

    msg.textFormat("markdown");
    msg.attachments([
        card,
    ]);
    session.endDialog(msg);
});

I am wondering how can I achieve this formatting(From mailclark bot in MSTeams):

As you can see, it is a carousel of what I think it might be HeroCards, but they are formatted with bold, code and unordered lists on new paragraphs.

It seems to be a known issue that message attachments do not receive formatting, but how could the mailclark guys achieve it?

Edit:
Unordered list example:

Bold and code example:

Body:
MailClark here. You're right: it's a carousel of Hero Cards.

As Gary said, it's mostly simple HTML with a few <code> and <strong> tags.

But this is the real secret: the list is not HTML it's just regular text and the 3 lines are starting with a good old bullet character: • (we didn't like the style produced by <ul><li>).


问:
Kill a stuck thread on a running VM (JBoss Instance) in Java?
A bug in a third party library is causing an infinite loop in a worker thread on a JBoss instance of mine.  Do you know of a way to kill this "stuck" thread without restarting the server?  We'd like to be able to recover from this  until a fix is deployed, preferably without having to restart.

I've seen a few people mention using Thread.interrupt() - if I were to code my own MBean, how would I get a handle to the thread in question in order to interrupt it?

Update: Wasn't able to solve using any of these methods.  I did come across another thread about the same issue that had a link to why Thread.stop() is deprecated. Someone else has asked a similar question with similar results. It seems like more sophisticated containers should provide this kind of health mechanism, but I guess their hands are tied w/r/t the JVM.

答:
I suppose the most difficult part is to identify the hanging thread. You provide no info about it, but perhaps you can build some rules around the thread's name or its current stack trace.

If you can identify the thread by its name, I would get all threads in the VM by getting my own thread group with Thread.currentThread().getThreadGroup(), then walk up the thread group hierarchy by calling getParent() on the thread group until it returns null. You now have the top level thread group. You can now fill a preallocated array with all threads using the enumerate(Thread[] list) method on the top level thread group.

If you need the stack traces anyway to identify the thread, you can also use the static utility method Map<Thread,StackTraceElement[]> Thread.getAllStackTraces() to get all threads. Computing the stack traces is however quite expensive, so this might not be the best solution if you don't actually need them.

After identifying the thread you must call the stop() method on it. Interrupting it won't help, unless the implementation of the running code actually evaluates the thread's interrupted flag and behaves as you expect it to. Not that the stop() method is deprecated and that using it may have many funny side effects. You can find more details in the API documentation.