text:
Q: Deleting any node inside BST - Clojure I'm studying algorithms and at the class we were asked to create a BST with structures, I'm trying really hard to create a delete function but the one I created isn't efficient and doesn't work. I searched in google for something similar, but most of the questions are about vectors and not record/structures. If you have any recommendations, I would really appreciate it.
This is the basic creating of the root and node:

(let [bst (make-bst)]
  (bst-empty? bst)
  (make-bst-node 10))

(defrecord BST [root])

(defn bst? [bst]
  (= (class bst) BST))

(defn make-bst []
  (BST. (ref nil)))

(defn bst-empty? [bst]
  (nil? @(:root bst)))

(defrecord BSTnode [data left right])

(defn make-bst-node [val]
  (BSTnode. val (ref nil) (ref nil)))

(defn bst-insert! [bst val]
  (loop [node (:root bst)]
    (if (nil? @node)
      (dosync
       (ref-set node (make-bst-node val)))
      (let [data (:data bst)]
        (if (< val data)
          (recur (:left @node))
          (if (val data)
            (recur (:right @node))))))))

This is the delete function:

(defn bst-del [bst val]
  (if (nil? @(:root bst))
    false
    (do
    (if (= (:data @(:root bst)) val)
     (if (nil? (and (:right bst) (:left bst)))
      (dosync
       (ref-set (:root bst) nil))
       (if (not (nil? (:right bst)))
         (dosync
          (ref-set (:root bst) @(:right bst)))
         (if (not (nil? (:left bst)))
           (dosync
            (ref-set (:root bst) @(:left bst)))
           (if (not (nil? (and (:right bst) (:left bst))))
             (dosync
              (ref-set (:root bst) @(:left bst))
              (ref-set (:root bst) (:right bst))) false))))))))

(defn node-del [bst val]
  (loop [node @(:root bst)]
    (if (nil? node)
      false
      (if (true? bst-del)
        (println "somthing got deleted")
        (if (< val (:data node))
          (recur @(:left node))
          (recur @(:right node)))))))

I tried to search in google but all the function or examples were for maps and vectors, not my case, as well as, reading theoretical material about the subject and references from different languages.

A: this code of yours seems to be overly complicated and hard to debug (or event understand an algorithm)
I would propose implementing this recursive algorithm for deletion, which works quite nice with that mutable structure of yours:
Node delete(root : Node, z : T):
  if root == null
    return root
  if z < root.key
    root.left = delete(root.left, z)
  else if z > root.key
    root.right = delete(root.right, z)
  else if root.left != null and root.right != null
    root.key = minimum(root.right).key
    root.right = delete(root.right, root.key)
  else
    if root.left != null
      root = root.left
    else if root.right != null
      root = root.right
    else
      root = null
  return root

so, i would start with the following type defs:
(defrecord Tree [root])

(defn make-tree [root-node]
  (->Tree (ref root-node)))

(defrecord Node [data left right])

(defn make-node [data & {:keys [left right]}]
  (->Node (ref data)
          (ref left)
          (ref right)))

first thing we want is insertion + traversal functions for tree creating/debug. let's implement them for Node (and employ in Tree later):
(defn insert-node [{:keys [data left right] :as node} item]
  (if (nil? node)
    (make-node item)
    (dosync (alter (if (< item @data) left right)
                   insert-node
                   item)
            node)))

(defn traverse-node [node]
  (when-some [{:keys [data left right]} node]
    (concat (traverse-node @left)
            [@data]
            (traverse-node @right))))

user> (reduce insert-node nil [3 1 2])
;; {:data #<Ref@1a28bd3f: 3>,
;;  :left
;;  #<Ref@514133ef:
;;    {:data #<Ref@5617f393: 1>,
;;     :left #<Ref@637de49b: nil>,
;;     :right
;;     #<Ref@6efa5317:
;;       {:data #<Ref@14ef556b: 2>,
;;        :left #<Ref@7fe0e031: nil>,
;;        :right #<Ref@5a16bba5: nil>}>}>,
;;  :right #<Ref@4eec6b9f: nil>}

user> (traverse-node (reduce insert-node nil [3 1 2]))
;; (1 2 3)

so, this seems to work ok.
Next, we will implement the deletion algorithm.
there's an utility function minimum in the aforementioned algorithm, so we start with that one:
(defn minimum-node [{:keys [data left right] :as node}]
  (cond (nil? node) nil
        (nil? @left) @data
        :else (recur @left)))

user> (minimum-node (reduce insert-node nil (shuffle (range 10 20))))
;; 10

after that the deletion implementation looks trivial:
(defn del-node [node item]
  (when-some [{:keys [data left right]} node]
    (cond (< item @data) (dosync (alter left del-node item)
                                 node)
          (> item @data) (dosync (alter right del-node item)
                                 node)
          (and (some? @left) (some? @right)) (let [m (-> right deref minimum-node)]
                                               (dosync
                                                (ref-set data m)
                                                (alter right del-node m))
                                               node)
          (some? @left) @left
          (some? @right) @right)))

user> (traverse-node (del-node
                      (reduce insert-node nil (shuffle (range 10 20)))
                      13))
;;=> (10 11 12 14 15 16 17 18 19)

this seems to be working mutable algorithm.
Let's then go back to the Tree structure. I would start with the BST protocol, to be used by both Node and Tree:
(defprotocol BST
  (traverse [self])
  (insert [self item])
  (minimum [self])
  (del [self item]))

(extend-protocol BST
  Node
  (traverse [self]
    (traverse-node self))
  (insert [self item]
    (insert-node self item))
  (minimum [self]
    (minimum-node self))
  (del [self item]
    (del-node self item)))

(extend-protocol BST
  Tree
  (traverse [self] (-> self :root deref traverse))
  (insert [self item]
    (dosync
     (if (-> self :root deref some?)
       (alter (:root self) insert item)
       (ref-set (:root self) (make-node item))))
    self)
  (minimum [self] (-> self :root deref minimum))
  (del [self item]
    (dosync
     (when (-> self :root deref some?)
       (alter (:root self) del item)))
    self))

and that's it. Now just use it:
user> (reduce del
              (reduce insert (make-tree nil) [1 2 3 4])
              [2 4])
;; {:root
;;  #<Ref@273f7854:
;;    {:data #<Ref@67d4f4d0: 1>,
;;     :left #<Ref@26329ec3: nil>,
;;     :right
;;     #<Ref@5636f9f8:
;;       {:data #<Ref@3cd02119: 3>,
;;        :left #<Ref@7d62fb13: nil>,
;;        :right #<Ref@1f25eeb7: nil>}>}>}

A: After the class, I understood how to delete a function and I implemented it similarly inside a dictionary binary tree. It is really similar, the only difference is with "key" value, but the logic is the same.
(defn dict-find-leftmost-node[start-node]
  (loop [node start-node]
    (if (nil? @(:left @node))
      node
      (recur (:left @node)))))

(defn dict-remove! [dict key]
  (let [node-to-remove (dict-get-node dict key)]
    (when (not (nil? node-to-remove))
      (if (dict-node-leaf? node-to-remove)
        (dosync
         (ref-set node-to-remove nil))
        (if (nil? @(:left @node-to-remove))
          (dosync
           ;;(println "I need to pull up the right branch")
           (ref-set node-to-remove
                    @(:right @node-to-remove)))
          (if (nil? @(:right @node-to-remove))
            (dosync
             ;;(println "I need to pull up the left branch")
             (ref-set node-to-remove
                      @(:left @node-to-remove)))
            (let [leftmost-node
                  (dict-find-leftmost-node
                   (:right @node-to-remove))]
              (dosync
               (ref-set (:left @leftmost-node)
                        @(:left @node-to-remove))
               (ref-set node-to-remove
                        @(:right @node-to-remove))))

              ;;(println "I don't know what to do yet!")
        ;; this is where we remove the node
        ))))))

(defn dict-node-leaf? [node]
  (and (nil? @(:left @node))
       (nil? @(:right @node))))


text:
Q: How to stop a onclick event when other button is clicked? When the #terminateButton is clicked, I want #myButton to not show the alert when clicked and remove the onclick event. I tried to add removeEventListener but it did not work.

let element = document.getElementById("myButton");

element.onclick = a
document.getElementById("terminateButton").onclick = function () {
  element.innerHTML = "Does Nothing";
  element.removeEventListener('click',a)
};

function a(){
    alert('You clicked the button');
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <button id='myButton'>Shows alert</button>
    <button id='terminateButton'>Dont show alert when other button clicked</button>
    <script src="script.js"></script>
</body>
</html>

A: You need to add your event listener with addEventListener function to be able to remove it with removeEventListener, like below. Here what mdn says:

The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target.

let element = document.getElementById("myButton");

element.addEventListener("click", a)

document.getElementById("terminateButton").onclick = function () {
  element.innerHTML = "Does Nothing";
  element.removeEventListener('click', a)
};

function a(){
    alert('You clicked the button');
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <button id='myButton'>Shows alert</button>
    <button id='terminateButton'>Dont show alert when other button clicked</button>
    <script src="script.js"></script>
</body>
</html>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling a Module and a Class within a Form I have an Employee class where I call my database connection Module to make a query.
I am getting "Compile Error: Expected function or variable", which I'm not understanding, because I have the empObj set at the top of the form.
I would like to return the value from the Employee.getEmployee method. Can someone please show me how to call the Employee class from my form? Do I have to import the class first? I don't believe VB6 supports the Imports keyword.
This is my form:
Option Explicit

Private empObj As New Employee

Private Sub Form_Load()
  'For testing only
  MsgBox (empObj.getEmployee)
End Sub

This is my class:
Public Sub getEmployee()
  'ConnectSQL is a database connection
  return ConnectSQL
End Sub

And this is the module:
Public Function ConnectSQL()
  Set SQLMyconn = New ADODB.Connection
  Set SQLRecset = New ADODB.Recordset
  SQLMyconn.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"
End Function

A: The basic shell of what you want to do is like this:
Option Explicit

Private empObj As Employee

Private Sub Form_Load()
   Set empObj = New Employee
   MsgBox empObj.getEmployee
End Sub

Public Function getEmployee() As String
   getEmployee = ConnectSQL
End Function

Public Function ConnectSQL() As String
   Set SQLMyconn = New ADODB.Connection
   Set SQLRecset = New ADODB.Recordset
   SQLMyconn.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"

   ConnectSQL = "data from your DB lookup"
End Function

Almost every line is different than what you posted, so carefully look at the code.
EDIT:
Based on a comment, here's how to modify the code to return a connection object:
Option Explicit

Private empObj As Employee

Private Sub Form_Load()
   Set empObj = New Employee
   MsgBox empObj.getEmployee

   Dim MyConnection As ADODB.Connection
   Set MyConnection = ConnectSQL()

   'you can grab and use the connection in your form, too.
End Sub

Public Function getEmployee() As String
   Dim MyConnection As ADODB.Connection
   Set MyConnection = ConnectSQL()

   'use the connection to grab data

   getEmployee = "data from your DB lookup"
End Function

Public Function ConnectSQL() As ADODB.Connection
   Set ConnectSQL = New ADODB.Connection
   ConnectSQL.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"
End Function

Don't forget to close your connection after you are done with it.  To sum up the changes:

*

*empObj - you should declare and instantiate your objects separately.

*MsgBox - no need for the ().

*Functions vs Subs - the first returns data, the second does not.  Make sure you declare the return type of a function.

*return - this statement is obsolete and doesn't do what you want.  Instead, assign a value to the name of the function.


text:
Q: JBL 500BT bluetooth headset, Unable to keep connection I have a JBL 500BT bluetooth headset. When I try to connect it to Ubuntu, it connects for 3 seconds, disconnects, and then stops being detected.
I tried to use blueman, but it fails to pair. I tried to install bluez and pulseaudio but it's still the same. I also tried sudo pactl load-module module-bluetooth-discover but it fails to connect.
I am running Ubuntu 20.04 LTS. Any ideas?

A: I ran
sudo apt-get install pulseaudio-module-bluetooth
sudo killall pulseaudio
pulseaudio --start
sudo systemctl restart bluetooth
and now everyting is working fine


text:
Q: How to download python from command-line? I'm on windows, but I'm using a putty shell to connect to a linux machine, and want to install python 2.7. Can't figure out how to do it. How can I download python from command line?

A: wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz
cd Python-2.7.11

Now read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.
./configure
make
sudo make install

For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
For other versions and the most up to date download links:
http://www.python.org/getit/

A: apt-get install python2.7 will work on debian-like linuxes. The python website describes a whole bunch of other ways to get Python.

A: Well if you are getting into a linux machine you can use the package manager of that linux distro.
If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)
You could use yum in fedora and do the same.
if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it


text:
Q: How to add a check box and a multicolumn combo controls in DevXpress Grid Control? Is it possible to add check box, multi-column combo controls in DevXpress Grid Control? Could anyone guide me on this requirement?

A: The grid control enables you to assign different types of in-place editors to data cells.
You can find a detailed explanation here:  In-place Editors Overview


text:
Q: Unable to get "user computer name" as mentioned above after doing lot of try & error I still stuck at this, all the reference I found till now still unable to solve this issue as I can't get the real computer name at all, instead most of example I tried before will return server name or the closest one will return "10" no matter how many user it captured. I'm making a log function for my system, so far I can get domain name, user ip address, user id like in my code below :
Please somebody guide me on how to get "User Computer Name"...TQ Everyone
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Mail;
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    {
        SPSite spSite = SPContext.Current.Site;
        SPSite spConvSite = new SPSite("www.mywebsite.com");
        SPWeb spWeb = SPContext.Current.Web;
        SPWeb spConvWeb = spConvSite.OpenWeb();
        SPUser spUser = spWeb.CurrentUser;

        string strDateLogCreated = DateTime.Now.ToString("ddMMyyyy-hhmmsstt", CultureInfo.InvariantCulture);
        string LogFolder = "D:\\Logs\\Client";
        string[] LocalComputerName = System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName.Split(new Char[] { '.' });
        String ecn = System.Environment.MachineName;
        string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
        string hostName = Dns.GetHostName();
        IPGlobalProperties  ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        string testHost = ipProperties.HostName;
        string testDomain = ipProperties.DomainName;
        string strLocalIPAddress = HttpContext.Current.Request.UserHostAddress.ToString();

        string hName = "";
        System.Net.IPHostEntry host = new System.Net.IPHostEntry();
        host = System.Net.Dns.GetHostEntry(HttpContext.Current.Request.ServerVariables["REMOTE_HOST"]);

        //Split out the host name from the FQDN
        if (host.HostName.Contains("."))
        {
        string[] sSplit = host.HostName.Split('.');
        hName = sSplit[0].ToString();
        }
        else
        {
        hName = host.HostName.ToString();
        }
        //return hName;

        StreamWriter swLogFile = File.AppendText(String.Format(@"{0}\Client-{1}.log", LogFolder, strDateLogCreated));

        swLogFile.WriteLine("*** Date & Time : " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture));
        swLogFile.WriteLine("*** Initiated By : " + spUser.Name.ToString());
        swLogFile.WriteLine("*** LAN ID : " + spUser.LoginName.ToString());
        swLogFile.WriteLine("*** Computer Name : " + LocalComputerName[0].ToString());
        swLogFile.WriteLine("*** IP Address : " + strLocalIPAddress.ToString());
        swLogFile.WriteLine("---------------------------------------------------");
        swLogFile.WriteLine(DateTime.Now.ToString("hh:mm:ss tt", CultureInfo.InvariantCulture) + " - " + "Successfully captured.");
        swLogFile.WriteLine("=====================================================================================================");
        swLogFile.WriteLine("Test 1 : " + domainName.ToString());
        swLogFile.WriteLine("Test 2 : " + hostName.ToString());
        swLogFile.WriteLine("Test 3 : " + testHost.ToString());
        swLogFile.WriteLine("Test 4 : " + System.Environment.GetEnvironmentVariable("COMPUTERNAME"));
        swLogFile.WriteLine("Test 5 : " + System.Net.Dns.GetHostEntry(Request.ServerVariables["REMOTE_HOST"]).HostName);
        swLogFile.WriteLine("Test 6 : " + hName.ToString());
        swLogFile.Flush();
    }

Example of the output like this :
Date & Time : 18/02/2013 11:45:26 AM

Initiated By : USER NAME

LAN ID : DOMAIN\ID99999

Computer Name : 10 //I don't get the real user computer name here!

IP Address : 99.999.99.999

//-----------------------------------//

11:45:26 AM - Successfully captured.

//===================================//

Test 1 : DOMAIN.COMPANYDOMAIN.com

Test 2 : SERVERNAME

Test 3 : SERVERNAME

Test 4 : SERVERNAME

Test 5 : 99.999.99.999

Test 6 : 10 //Also return the same result

UPDATE :
I manage to get the answer now, the answer link to my answer on another post here :
https://stackoverflow.com/a/38953637/1785641
An updated version from Kelsey post on the link above :
$(function GetInfo() {
    var network = new ActiveXObject('WScript.Network');
        alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
        document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
        document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
        document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;
});

To store the value, add these control :
<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />

Where you also can calling it from behind like this :
Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);

A: Well, you're setting LocalComputerName to
System.Net.Dns.GetHostEntry(
Request.ServerVariables["remote_addr"]).HostName.Split(new Char[] { '.' })

What happens if you change that to:
System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"])

If you end up with an IP address, try using nslookup on that and seeing if you get a hostname. If you don't, your problem is in DNS resolution.
By the way, does the actual IP address start with 10. ?

A: I'm getting close now, here is the code for my .ascx file :
<style type="text/css">
    .hiddenText
    {
        display: none;
    }
</style>
<script type="text/jscript">
<!--
    $(document).ready(function () {
        var net = new ActiveXObject("WScript.Network");
        var vPCName = net.ComputerName;
        document.getElementById('<%= txtPCName.ClientID %>').value = vPCName;
    });
//-->
</script>

And this the textbox to hold the computer name, it suppose to be hidden but it won't work if it's hidden.
<asp:TextBox ID="txtPCName" runat="server" />

This is the code behind :
    protected void Page_Load(object sender, EventArgs e)
    {
        Collector();
    }
    protected void Collector()
    {
        if (txtPCName.Text != null || txtPCName.Text != "")
        {
            SPSite spSite = SPContext.Current.Site;
            SPSite spConvSite = new SPSite("https://www.mywebsite.com");
            SPWeb spWeb = SPContext.Current.Web;
            SPWeb spConvWeb = spConvSite.OpenWeb();
            SPUser spUser = spWeb.CurrentUser;

            string strDateLogCreated = DateTime.Now.ToString("ddMMyyyy-hhmmsstt", CultureInfo.InvariantCulture);
            string LogFolder = "D:\\Logs\\Client";
            string[] LocalComputerName = System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName.Split(new Char[] { '.' });
            String ecn = System.Environment.MachineName;
            string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            string hostName = Dns.GetHostName();
            string strLocalIPAddress = HttpContext.Current.Request.UserHostAddress.ToString();

            StreamWriter swLogFile = File.AppendText(String.Format(@"{0}\Client-{1}.log", LogFolder, strDateLogCreated));

            swLogFile.WriteLine("*** Date & Time : " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture));
            swLogFile.WriteLine("*** Initiated By : " + spUser.Name.ToString());
            swLogFile.WriteLine("*** LAN ID : " + spUser.LoginName.ToString());
            swLogFile.WriteLine("*** Computer Name : " + txtPCName.Text);
            swLogFile.WriteLine("*** IP Address : " + strLocalIPAddress.ToString());
            swLogFile.WriteLine("---------------------------------------------------");
            swLogFile.WriteLine(DateTime.Now.ToString("hh:mm:ss tt", CultureInfo.InvariantCulture) + " - " + "Successfully captured.");
            swLogFile.WriteLine("=====================================================================================================");
            swLogFile.Flush();
        }
    }

But the problem is, txtPCName cannot be hidden either by using Visible="false" or Style="display: none" cause it will not be able to store the value from Javascript to txtPCName. How do I solve this? I cannot let the textbox showing on the page.


text:
Q: How do I use PHP CLI to automate FTP when I don't have access to PHP's native FTP handle? I'm writing an automation script on a production server that, among other things, needs to grab a list of remote files via FTP (FTP is the only option for interacting with the remote filesystem) and selectively download them.
Why I can't use PHP's native FTP wrappers
This is a production server in a very brittle environment.  I'm writing it using PHP CLI, since most of the existing automation scripts are written this way.  However, although I have a very new PHP 5.1.2 installation, I'm not able to recompile it with --with-ftp, and that option is not enabled.
The remaining options
So, my options are to connect, get my file list, and selectively download using shell_exec() or the php_filesystem functions using an FTP stream and the PHP native filesystem functions.
Unfortunately, I'm not able to find good code examples of either.  When I try to shell_exec using FTP commands, the program hangs, presumably because control stays at the shell once I open up the FTP prompt.
$ftp_connect_command = "ftp -v -n $bl_ftp_host";
$ftp_login_command = "user $bl_ftp_user $bl_ftp_password";
$ftp_bye_command = "bye";

$ftp_connect_response = shell_exec("$ftp_connect_command");
// this never executes, because it hangs here waiting for a return to shell
$ftp_login_response = shell_exec($ftp_login_command);

Or, I imagine the stream based way to do this would be:
$ftp_path = "ftp://$bl_ftp_user:$bl_ftp_user@$bl_ftp_host/";
$stream_options = array('ftp' => array('overwrite' => false));
$context = stream_context_create();
if ($dh = opendir($ftp_path, $context))
{
    while (filename = readdir($dh))
    {
        print($filename);
    }
}

But I'm not sure if this is considered a reliable method.
Can anyone provide code samples showing how to capture a directory list and download files by either of these methods?

A: Apparently, wordpress uses pemftp for pure-PHP FTP (on systems compiled without FTP support)

A: Have you looked at the native PHP FTP library?
http://us2.php.net/ftp


text:
Q: Eclipse PDT: Syntax Errors with valid PHP Namespace Syntax I'm using Eclipse 3.6 (Helios) with PDT 2.2, and I'm getting syntax errors when trying to "use" namespaces.
Is there something I can do to fix this?
Example:
use Tables\Exceptions\Exception as Exception;

The PHP Parser recognizes "Tables" as a syntax error on this line and others like it.

A: This is probably related to your interpreter settings in Eclipse.
Go to the Project menu and select Properties. Once you have the Properties screen up you can go to PHP Interpreter and adjust the PHP Version, either at the project level or the Workspace level.
Set the PHP Version to 5.3 or higher for proper highlighting.
If your project is in PHP 5.2 than you won't be able to use namespaces. See here: Namespaces in php 5.2


text:
Q: Mapping this design in Fluent NHibernate I'm trying to figure out the best way to accomplish a design that's persisted with NHibernate. Here's what the data would ideally look like:
Person
===============
Id (int)
Name (nvarchar)

Privileges
==============
Person_Id
Right (int)
AccessLevel (int)

Ideally, I'd be able to create classes like this (pretend I have all the NHibernate virtual modifiers):
public enum Rights
{
    Read = 0,
    Save = 1,
    Delete = 2
}

public enum AccessLevels
{
    LevelOne = 0,
    LevelTwo = 1,
    LevelThree = 2
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Dictionary<Rights, AccessLevels> Privileges { get; set; }
}

Originally I considered the design described in this blog post, but I don't want to make the Rights enum a class because I'd like to be able to test for it without having to keep track of the Id of a given right. A pair of enumerations would be easiest I think.
Anyway, I've been striking out figuring out how to accomplish this in NHibernate, much less Fluent NHibernate. I'm hoping some NH gurus might be able to help.

A: I'm not sure if it's possible... but try something like this (I did not test):
 HasMany(x => x.Privileges)
            .WithTableName("Privileges")
            .KeyColumnNames.Add("Person_Id")
            .Cascade.All()
            .AsMap<string>(
                index => index.WithColumn("Right").WithType<Rights>(),
                element => element.WithColumn("AccessLevel").WithType<AccessLevels>()
            );
    }

Or something like this:
References(x => x.Privileges).AsMap<Rights>("Right").Element("AccessLevel", c => c.Type<AccessLevels>());.

Take a look at this thread: How do I map a dictionary using Fluent NHibernate automapping?


text:
Q: Slow Powershell script for CSV modification I'm using a powershell script to append data to the end of a bunch of files.
Each file is a CSV around 50Mb (Say 2 millionish lines), there are about 50 files.
The script I'm using looks like this:
$MyInvocation.MyCommand.path

$files = ls *.csv

foreach($f in $files)
{
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($f)
$year = $basename.substring(0,4)

Write-Host "Starting" $Basename

$r = [IO.File]::OpenText($f)
while ($r.Peek() -ge 0) {
    $line = $r.ReadLine()
    $line + "," + $year | Add-Content $(".\DR_" + $basename + ".CSV")
}
$r.Dispose()

}

Problem is, it's pretty slow. It's taken about 12 hours to get through them.
It's not super complex, so I wouldn't expect it to take that long to run.
What could I do to speed it up?

A: Reading and writing a file row by row can be a bit slow. Maybe your antivirus is contributing to slowness as well. Use Measure-Command to see which parts of the script are the slow ones.
As a general advise, rather write a few large blocks instead of lots of small ones. You can achieve this by storing some content in a StringBuilder and appending its contents into the output file every, say, 1000 processed rows. Like so,
$sb = new-object Text.StringBuilder # New String Builder for stuff
$i = 1 # Row counter
while ($r.Peek() -ge 0) {
    # Add formatted stuff into the buffer
    [void]$sb.Append($("{0},{1}{2}" -f $r.ReadLine(), $year, [Environment]::NewLine ) )

    if(++$i % 1000 -eq 0){ # When 1000 rows are added, dump contents into file
      Add-Content $(".\DR_" + $basename + ".CSV") $sb.ToString()
      $sb = new-object Text.StringBuilder # Reset the StringBuilder
    }
}
# Don't miss the tail of the contents
Add-Content $(".\DR_" + $basename + ".CSV") $sb.ToString()

A: Don't go into .NET Framework static methods and building up strings when there are cmdlets that can do the work on objects. Collect your data, add the year column, then export to your new file. You're also doing a ton of file I/O and that'll also slow you down.
This will probably require a little bit more memory. But it reads the whole file at once, and writes the whole file at once. It also assumes that your CSV files have column headings. But it's much easier for someone else to look at and understand exactly what's going on (write your scripts so they can be read!).
# Always use full cmdlet names in scripts, not aliases
$files = get-childitem *.csv;

foreach($f in $files)
{
    #basename is a property of the file object in PowerShell, there's no need to call a static method
    $basename = $f.basename;
    $year = $f.basename.substring(0,4)

    # Every time you use Write-Host, a puppy dies
    "Starting $Basename";

    # If you've got CSV data, treat it as CSV data. PowerShell can import it into a collection natively.
    $data = Import-Csv $f;
    $exportData = @();
    foreach ($row in $data) {
# Add a year "property" to each row object
        $row |Add-Member -membertype NoteProperty -Name "Year" -Value $year;
# Export the modified row to the output file
        $row |Export-Csv -NoTypeInformation -Path $("r:\DR_" + $basename + ".CSV") -Append -NoClobber
    }
}


text:
Q: web service (bpel) and unstructured data combination I have a dilemma. My existing transactional system (behind bpel) is web service based (xml data transport) and for some new features such as mobile apps I need to use legacy web services and innovative solutions such as node+mongo to store unstructured data and files.
  My question is should I use bpel front end for both mongo and legacy system so that my mobile app has only one end point to talk to. If so there is a problem of two data format handling (xml and json).
  OR
 Should my mobile client talk to both thus have two end points.

A: I assume that BPEL uses SOAP protocol which supports only XML. I have used Oracle BPEL 11g. I am not sure about other BPEL products from other companies.
If it is RESTFul service, then a web service endpoint can produce the response in different formats (such as XML, JSON etc.) based on the ACCEPT attribute in HTTP header.
If the consuming application/service set the acceptable format (i.e. ACCEPT attribute) in HTTP header, then the web service can produce the response in that format.
If the web service is unable to produce response in the acceptable format, it should throw "HTTP 406 error".


text:
Q: JavaFX wait until value is set I am struggling with the following problem:
I have something like a popup in my javafx application, that should block the application, until the user made some input. It is NOT a seperate stage, where i can call showAndWait() and then return the input of the stage. The popup is realized as a pane, that is placed over the other components. And now i do something like this:
PopupPane pp = new PopupPane()
stackPane.add(new PopupPane()); //show pane
//... waiting until user terminates popup
return pp.getInput(); //returns input when user terminates popup

So i want pp.getInput() to wait, until the user presses the OK/CANCEL/APPLY/... button in my popup. How can i realize something like showAndWait() in this situation?

A: One possible way to do this would be to utilize an additional pane that can be disabled while the "popup" is being displayed.
For example, say the root layout pane of your Scene is a StackPane. You could wrap all the rest of your interface in another Pane that you'll disable or enable as needed.
When the "popup" needs to be displayed, add it to your StackPane and disable the "content" pane.  When the popup closes, just remove it from your StackPane and re-enable the "content" pane.
Here's a quick and admittedly unattractive example of the concept:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class SimulatedPopupExample extends Application {

    private static StackPane root;
    private static BorderPane content;

    public static void main(String[] args) {
        launch(args);
    }

    private static void showPopup() {

        // Disable the main layout pain
        content.setDisable(true);

        VBox popup = new VBox();
        popup.setPadding(new Insets(10));
        popup.setAlignment(Pos.CENTER);
        popup.setStyle("-fx-border-color: black; -fx-background-color: -fx-base;");
        popup.setMaxSize(200, 200);

        popup.getChildren().add(
                new Button("Close Popup") {{
                    setOnAction(event -> {
                        // Re-enable the pane
                        content.setDisable(false);

                        // Remove popup from root layout
                        root.getChildren().remove(popup);

                    });
                }}
        );

        // Add popup to root layout
        root.getChildren().add(popup);
    }

    @Override
    public void start(Stage primaryStage) {

        // Simple Interface
        root = new StackPane();
        content = new BorderPane(
                new Button("Show \"Popup\"") {{
                    setOnAction(e -> showPopup());
                }},
                new Button("Top Button"),
                new Button("Right Button"),
                new Button("Bottom Button"),
                new Button("Left Button")
        );

        root.getChildren().add(content);

        // Show the stage
        primaryStage.setScene(new Scene(root));
        primaryStage.setWidth(500);
        primaryStage.setHeight(400);
        primaryStage.setTitle("SimulatedPopupExample Sample");
        primaryStage.show();

    }
}

The Result:

A: Here is a Custom Dialog that can not be closed or accepted until the user enter data in the TextField
    private void showInputTextDialog(){

            Label lblAmt = new Label("Enter Amount");
            Button btnOK = new Button("OK");
            TextField txtAmt = new TextField();

            AnchorPane customDialog = new AnchorPane();
            customDialog.setStyle("-fx-border-color:red;-fx-border-width:10px; -fx-background-color: lightblue;");
            customDialog.getChildren().addAll(lblAmt,btnOK,txtAmt);
            lblAmt.setLayoutX(30);
            lblAmt.setLayoutY(30);
            txtAmt.setLayoutX(164);
            txtAmt.setLayoutY(25);
            txtAmt.setMaxWidth(116);
            btnOK.setLayoutX(190);
            btnOK.setLayoutY(100);
            btnOK.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");
            lblAmt.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");
            txtAmt.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");

            Scene secondScene = new Scene(customDialog, 300, 180);

            EventHandler<ActionEvent> filter = event -> {
            if(txtAmt.getText().isEmpty()) {
    event.consume();
            }
            };

            // New window (Stage)
            Stage newWindow = new Stage();
            //newWindow.initStyle(StageStyle.UNDECORATED);
            newWindow.initModality(Modality.APPLICATION_MODAL);
            newWindow.setResizable(false);
            //newWindow.setTitle("Custom Dialog");
            newWindow.setScene(secondScene);
            btnOK.addEventHandler(ActionEvent.ACTION,filter);
            btnOK.setOnAction(evt -> {
            String str = txtAmt.getText();
            System.out.println("@@@@@@@@@@@@@@@@ str "+str);
            if(txtAmt.getText().trim().equals("")) {
                evt.consume();
                txtAmt.clear();
                txtAmt.requestFocus();
            }else{
                txAMT = Double.valueOf(str);
                newWindow.close();
            }
            });

            newWindow.setOnCloseRequest(event -> {
                if(txtAmt.getText().isEmpty()) {
                event.consume();
            }
            });
            txtAmt.requestFocus();
            newWindow.showAndWait();
}


text:
Q: Heroku, namecheap and email forwarding I have a free dyno on heroku for an app myapp and I've just bought a domain myapp.co. I would like to configure Namecheap so both of the following are true:

*

*A user enters myapp.co in the URL -> my Heroku app is displayed under myapp.co URL

*A user enters www.myapp.co in the RUL -> my Heroku app is displayed under myapp.co URL

What I 've already done is added 2 domains in Heroku settings and they look like this:

*

*Domain name: myapp.co DNS Target: autogenerated-heroku-slug-1.herokudns.com

*Domain name: www.myapp.co DNS Target: autogenerated-heroku-slug-2.herokudns.com
I've already added 3 host records in the Advanced DNS section of Namecheap:

*

*Type: CNAME Record Host: @ Value: autogenerated-heroku-slug-1.herokudns.com.

*Type: CNAME Record Host: www Value: autogenerated-heroku-slug-2.herokudns.com.

*Type: URL Redirect Record Host: @ Value: http://myapp.co/   Unmasked
Trying to access myapp.co brings a page This page isn't redirecting properly.
How to properly configure both Heroku and Namecheap to make this work?
PS Not sure if this is an important part, but I would also like to user Namecheap email forwarding so emails sent to contact@myapp.co are redirected to my gmail account.

A: I would instead do:

*

*Type: CNAME Record Host: @ Value: yourappname.herokuapp.com

*Type: CNAME Record Host: www Value: yourappname.herokuapp.com

Wait for a couple of minutes for the DNS records to be configured and try again.


text:
Q: CreateItemFromTemplate Type mismatch I have code to generate an email based on data on a userform.
It worked for a long time across multiple machines, but when I changed machines it started throwing a run-time error 13 type mismatch on on the CreateItemFromTemplate method in the following section:
Private Sub AcaoEnviar_Click()
    Dim OutlookApp As New Outlook.Application
    Dim EmailKRI As Outlook.MailItem

    Set EmailKRI = OutlookApp.CreateItemFromTemplate(PATH_EMAIL_TEMPLATE)

The code still runs on other machines, suggesting the problem is local. My Outlook library is the same as on the other machines, and the only difference I´m aware of is that I´m running it on a 64-bit system and 32-bit office, while most others have 32-bit systems (one other has the same 64-bit setup and runs fine).
Changing the object declaration from Outlook.MailItem to Object seems to solve the problem, which I think eliminates problems with Outlook's programmatic access, and in any case, my Antivirus status is valid.
I'm still confused as to why such an error would occur only with me.
Is there any solution so that I can go back to early binding for that email object?

A: You will get that error if CreateItemFromTemplate returns something other than MailItem object. Are you sure the OFT file is for a regular mail item.
As a test, declare EmailKRI  as a generic Obejct and at run time check the value of the EmailKRI.Class property. It is supposed to be 43 (OlObjectClass.olMail) for the regular MailItem objects.


text:
Q: How can i find the minimum value in a list of number without using the min() method in python? I tried doing this looping through a for loop comparing every element in the list to each other but the way i did it only work if the number in the list are positive it does not work if they are all negative. does anyone how how i can do this?

A: Use
mini = scores[0]

instead of 0

A: scores = [1, 2, 3, 4, 5]

Any of these will work:
sorted(scores)[0]
sorted(scores, reverse=True)[-1]
[s for s in scores if all(s<=i for i in scores)][0]

def getMin(L):
    answer = L[0]
    for i in L:
        if i < answer:
            answer = i
    return answer
getMin(scores)


text:
Q: How to get fqdn of ip addresses in c#? On a machine there might be several IP addresses available. How can I find out all the belonging full qualified domain names (fqdn)?
Update:
I tried the following:
IPHostEntry he = Dns.GetHostEntry(Environment.UserDomainName);
foreach (IPAddress ipAddress in he.AddressList)
{
    string x = ipAddress.ToString();
    string y = Dns.GetHostEntry(ipAddress.ToString()).HostName;
}

I have a machine with 2 IP addresses, the ping using their fqdn returns the correct IPs. However, the code above always return me the one fqdn of the first IP.
My setup looks as follows:
IP1:
123.123.123.123
Name1
IP2:
456.456.456.456
Name2
Both ping and nslookup returns correct value.
The problem is that both rows
Dns.GetHostEntry("123.123.123.123").HostName;
Dns.GetHostEntry("456.456.456.456").HostName;

returns "Name1" (instead of "Name1" and "Name2").
However, the codes
Dns.GetHostEntry("Name1").HostName;
Dns.GetHostEntry("Name2").HostName;

work correctly.

A: You resolve each IP address to the netbios name.
Dim hostEntry As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry("192.168.115.54")
Console.WriteLine(hostEntry.HostName)

For example if I resolve my IP i get:
PC-MYNAME.MYDOMAIN.local

Then you can also use ActiveDirectory to enumerate the CurrentForrest (available domains).


text:
Q: Restoring my Tiny Tower progress from Game Center? Game Center says I have 66 floors, but when I go in the game the pop up about restoring my account doesn't appear.
I'm already logged into my Game Center and have tried:

*

*Uninstalling and reinstalling the app (countless attempts)

*Force Killing the application, but it didn't help.

*Looked at FAQs about restoring back my floors

I'm on iOS if it helps.


text:
Q: Redirects in Next.js app on Digital Ocean not working and must use .html suffix for all pages Is there a way to deploy a Next.js static site on Digital Ocean and get it to work "normally"?
I got an app deployed but every page has to be accessed via the .html suffix, and redirects specified in next.js.config don't seem to work. This breaks a lot of use-cases, and before I go back to Netlify, I wanted to make sure this isn't just a me problem.
I did follow the guide here to generate a static site.

A: When you export your Next.js site as static (as opposed to running it with node.js), you are serving static HTML, CSS and JS. That's why the redirects in next.config.js don't work.
To get those redirects working, there are multiple ways:
1. Serving the Next.js site with node.js
Next.js' all features including redirects will work if you run and serve it with node.js. How you can do is described in the "Deploying Next.js as a Custom Server" section of the page you shared.
2. Configuring your web server to handle the redirects
Since you didn't share what you use as web server, I can't add any details. But for example, searching "nextjs nginx redirect" might help in case you are using nginx.


text:
Q: dockerignore doesn't work even though it's written correctly My .dockerignore file
.gitlab-ci.yml
CHANGELOG
VERSION
README.md

My Dockerfile
FROM php:7.4-apache

#COPY SOURCE CODE
COPY . /var/www/html/

#INSTALL MYSQL EXTENSION
RUN docker-php-ext-install mysqli

My .gitlab-ci.yml on build stage
build image:
  stage: build
  rules:
    - if: $CI_COMMIT_TAG
    - if: $CI_OPEN_MERGE_REQUESTS
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: never
    - if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
  image: docker:latest
  services:
    - docker:dind
  dependencies:
    - generate tag
  before_script:
    - docker login -u "$DOCKER_USER" -p "$DOCKER_PASSWORD"
  script:
    - docker build --compress -t "$DOCKER_USER"/"$DOCKER_IMAGE_NAME":"$TAG" .
    - docker push "$DOCKER_USER"/"$DOCKER_IMAGE_NAME":"$TAG"

My file check results
$ ls
CHANGELOG
Dockerfile
README.md
VERSION
application
index.php
system
testci.sql
vendor

Why does this happen even when I have followed the guidelines on https://docs.docker.com/engine/reference/builder/#dockerignore-file ? Are there exceptions to certain files?

A: No there is no exception except lines starting with !.
My guess is that there is some mistake between the path of the .dockerignore and the root of the build context. To work in this case everything must be in the same directory. You can troubleshoot it out by adding extra wildcard characters * for example (*/*/CHANGELOG).
However, it could be simpler and safer to put everything that needs to be included in the build context in a dedicated folder (for example a docker sub-directory). With this setup you do not need .dockerignore (except to ignore the Dockerfile for example) and you will avoid to copy files (added during the life of the project and not properly ignored) unintentionally in the image. The consequences can be bigger image size, unnecessary rebuilds, secret exposure, etc.


text:
Q: Why does a physical theory need to be testable? We are generally not interested in physical theories that cannot be tested with the scientific method. This would seemingly apply even if the theory has other advantages, e.g. simpler, more general, more elegant. Of course the possibility exists that the "correct" theory may not be testable beyond what it is designed to explain, or may contain many untestable consequences. In this case we would be eliminating such a theory a priori. Isn't this a problem?

A:
may not be testable beyond what it is coming to explain, or may contain many untestable consequences. In this case we would be eliminating such a theory a priori. Isn't this a problem?

That's all well and good. Until you have a plethora of such "theories" to choose from. Which one do we pick? Which one do we fund?
If it is consistent with current theories and observations, and it can be shown to be equivalent to existing ones, it becomes another formalism. For example, the path integral formalism of quantum mechanics.
The scientific method is stringent on the falsifiability and that's where it gets its strength from. That's how we can safely pick one theory over the rest by seeing which theory best predicts what we observe. If we loosen this, then we lose the strength of the scientific method.

A:
This would seemingly apply even if the theory has other advantages,
e.g. simpler, more general, (more elegant?)

I beg to differ. If it is simpler or more general, it will be picked up sooner or later as main theory. If it is more elegant but not simpler nor more general, it will not get adopted in practice, but many people will study it just because of its elegance (albeit it seems to me the elegance is in physics equivalent to simplicity and generality, so "more elegant but less simple and general" seems to me as oxymoron). We are also not at the end of scientific investigation and the elegant ideas might prove to be useful for future theories.

A: Theorem. $\;$
A physical theory does not need to be testable.
Proof (by counterexample). $\;$
There has been a strong interest for string theory but it is not testable because of theoretical and mathematical difficulties and  because of the extremely high energies needed. $\; \Box$
Proposition. $\;$ String theory is not a mere mathematical theory.
Proof. $\;$
It is testable in principle (although not in practice). $\; \Box$

A: One obvious example of a "simpler, more general, more elegant" theory is that the big bang was initiated by a supernatural being that created the universe for a specific purpose, which we have so far been unable to discover.

In this case we would be eliminating such a theory a priori.
Isn't this a problem?

Is it "a problem" if science completely rejects this perhaps true theory and searches for different, but possibly testable, explanations?
Most scientists don't find it a problem to reject the concept of God.
Even those that do hold personal religious beliefs tend to keep them separate from their work.
That's how science works, and so far it doesn't seem to be a problem.


text:
Q: What is the purpose of List> if one can only insert a null value? Based on the information provided in the link, it says that:

It's important to note that List<Object> and List<?> are not the same. You can insert an Object, or any subtype of Object, into a List<Object>. But you can only insert null into a List<?>.

What is the use of using List<?> when only null can be inserted?
For example,
methodOne(ArrayList<?> l): We can use this method for ArrayList of any type but within the method we can't add anything to the List except null.
l.add(null);//(valid)
l.add("A");//(invalid)

A: You can get elements from your list.
List<?> is usually used as a type for a list of unknown-typed objects returned by a method or so, where you read elements from, rather than adding them.

A: You use the unbounded wildcards when the list (or the collection) is of unknown types.
Like the tutorial says, it's used when you want to get information about some list, like printing its content, but you don't know what type it might be containing:
public static void printList(List<?> list) {
    for (Object elem: list)
        System.out.print(elem + " ");
    System.out.println();
}

You shouldn't use it when you want to insert values to the list, since the only value allowed is null, because you don't know what values it contains..

A: List<?> is quite different. If we try and add objects into a List<?>, even if the object is of type Object, we can't do it. It says,

add(capture<?>) in java.util.List cannot be applied to (java.lang.Object)

Now that might seem a bit restrictive. If you can't have any values being passed as parameters, which is what I mean when I say put into a list, then, what can you do with it?
Well, let's see why that restriction exists. To begin with, we know that arrays are covariant. So what that means is we could take an array of Strings and put that into an Object Array.

So here, if we take that first object and we assign it to a random String, everything will be fine. And if we assign it to a new Object, if we add that in, then we will get an ArrayStoreException
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Object

because of the unsafety of covariant arrays.
Well, in the case of List<?>,  what the Java compiler is trying to do for us by banning us from adding values into a List<?> or a List<? extends Object> is put us into a position where this type can only be safely used. And in fact, the only value that you are allowed to put into a List<?> is the null value because null can be coerced into any type.


text:
Q: Batch System windows application I am working on a batch system windows application, SCADA system for feed process.
I used a Mitsubishi FX3G PLC, I have a 3 weight indicator connected serial RS232 to the computer, I have managed to get and process the data from the indicator, the next step was to control 11 tanks with barrels to feed the weight scale through the specified formula that the user want to execute, 9 tanks for raw materials and 2 tanks for liquids and the process goes like this => the 9 tanks for raw materials have a weight scale, the second weight scale for liquid 1, the third scale for liquid 2. .
so I have learned that in order to develop a UI for certain application that have a lot of interactions especially when you deal like feed process the user should see through the application the sequence of barrels when it turns on and off to produce the desired formula. So multiple threads or Tasks are the best suites for this kind of interaction, and I think tasks are better.
When I tried Tasks I created 3 Tasks.
Task 1 for weighing RawMaterial
Task 2 for weighing Oil
Task 3 for weighing Surf
Everything works fine the logic is fine the fetched data from the weight indicators works fine and all, when the start button click events fire the 3 tasks should start all in parallel except when the program start to execute the 3 tasks together it is so slow until the one task is done then it moves till it become smooth. Have a look at the code, I am not going to paste her the whole thing only a shortcut code as there are a lot of repeated steps.
using BatchSystem.DB;
using System;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ActUtlTypeLib;

namespace BatchSystem.Screens
{
    public partial class ProductionSystem : Form
    {
        BatchSystemEntities2 db = new BatchSystemEntities2();
        int id;
        int batchNo;
        int Currbatch;
        int DryMix;
        int WetMix;
        int MixerDisch;
        float T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11;
        int fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11;
        int halt1,halt2,halt3,halt4,halt5,halt6,halt7,halt8,halt9,halt10,halt11;
        float target1_fastspeed;
        float target1_slowspeed;
        float target2_fastspeed;
        float target2_slowspeed;
        float target3_fastspeed;
        float target3_slowspeed;
        float target4_fastspeed;
        float target4_slowspeed;
        float target5_fastspeed;
        float target5_slowspeed;
        float target6_fastspeed;
        float target6_slowspeed;
        float target7_fastspeed;
        float target7_slowspeed;
        float target8_fastspeed;
        float target8_slowspeed;
        float target9_fastspeed;
        float target9_slowspeed;
        float target10_fastspeed;
        float target10_slowspeed;
        float target11_fastspeed;
        float target11_slowspeed;
        float act1 = 0;
        float act2 = 0;
        float act3 = 0;
        float act4 = 0;
        float act5 = 0;
        float act6 = 0;
        float act7 = 0;
        float act8 = 0;
        float act9 = 0;
        float act10 = 0;
        float act11 = 0;
        float err1 = 0;
        float err2 = 0;
        float err3 = 0;
        float err4 = 0;
        float err5 = 0;
        float err6 = 0;
        float err7 = 0;
        float err8 = 0;
        float err9 = 0;
        float err10 = 0;
        float err11 = 0;
        int FB1;
        int FB2;
        int FB3;
        int FB4;
        int FB5;
        int FB6;
        int FB7;
        int FB8;
        int FB9;
        int FB10;
        int FB11;
        float RawMatScale;
        float Oilscale;
        float Surfscale;

        string readserialvalue;
        string readserialvalue2;
        char[] char1 = { 'G', 'S', ',', 'T', '+', '-', ' ', 'k', 'g' };
        public ActUtlType plc = new ActUtlType();

        public ProductionSystem()
        {

            InitializeComponent();

            plc.ActLogicalStationNumber = 5;
            plc.Open();

            loadData();
            Raw_mat_Scale.Text = "0.00";
            OilScale.Text = "0.00";
            SurfScale.Text = "0.00";

            lblPort1state.Text = "غير متصل";
            lblPort2state.Text= "غير متصل";

            WindowState = FormWindowState.Maximized;

        }

        public int TargetId
        {
            get { return id; }
            set { id = value; }
        }

        public int TolBatch
        {
            get { return batchNo; }
            set { batchNo = value; }
        }

        public int dryMix
        {
            get { return DryMix; }
            set { DryMix = value; }
        }

        public int wetMix
        {
            get { return WetMix; }
            set { WetMix = value; }
        }

        public int mixDisch
        {
            get { return MixerDisch; }
            set { MixerDisch = value; }
        }

      public  void loadData()
        {

            try {
                txtTolBatch.Text = batchNo.ToString();

                var formula = db.formulaNames.FirstOrDefault(x => x.ID == id);
                txtFormula.Text = formula.Formula_Name.ToString();

                var parameter = db.FormulaParameters.FirstOrDefault(p => p.ID == 1);
                var Fs = db.FormulaParameters.FirstOrDefault(X => X.ID == 1);

                txtMat1.Text = parameter.Material1.ToString();
                txtMat2.Text = parameter.Material2.ToString();
                txtMat3.Text = parameter.Material3.ToString();
                txtMat4.Text = parameter.Material4.ToString();
                txtMat5.Text = parameter.Material5.ToString();
                txtMat6.Text = parameter.Material6.ToString();
                txtMat7.Text = parameter.Material7.ToString();
                txtMat8.Text = parameter.Material8.ToString();
                txtMat9.Text = parameter.Material9.ToString();
                txtMat10.Text = parameter.Material10.ToString();
                txtMat11.Text = parameter.Material11.ToString();

                var target = db.Formula_Managers.FirstOrDefault(x => x.FormulaID == id);

                txtTarget1.Text = target.Target1.ToString();
                txtTarget2.Text = target.Target2.ToString();
                txtTarget3.Text = target.Target3.ToString();
                txtTarget4.Text = target.Target4.ToString();
                txtTarget5.Text = target.Target5.ToString();
                txtTarget6.Text = target.Target6.ToString();
                txtTarget7.Text = target.Target7.ToString();
                txtTarget8.Text = target.Target8.ToString();
                txtTarget9.Text = target.Target9.ToString();
                txtTarget10.Text = target.Target10.ToString();
                txtTarget11.Text = target.Target11.ToString();

                 T1 = (float)target.Target1;
            //1 T target
                fs1 = (int)Fs.FS1;
   //11 fs
                fs11 = (int)Fs.FS11;
                halt1 = (int)Fs.Halt1;
              //11 halt
            }
            catch
            {

            }
        }

        private void textBox15_TextChanged(object sender, EventArgs e)
        {

        }
        private void ProductionSystem_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            loadData();
        }

        public void ProductionSystem_Load(object sender, EventArgs e)
        {
            try
            {
                Scale1_Serial();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                lblPort1state.Text = "غير متصل";

            }
            try
            {
                Scale2_Serial();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                lblPort2state.Text = "غير متصل";
            }
            if (serialPort1.IsOpen)
                ReadSerialData1();
            if (serialPort2.IsOpen)
                ReadSerialData2();
        }

        #region Serial Comm        ///another 2 copies for the serial comm region

        public void Scale1_Serial()
        {
            var rawportid = db.RawMaterial_Port.Count();
            var finalrawport = db.RawMaterial_Port.FirstOrDefault(x => x.ID == rawportid);
            serialPort1.PortName = finalrawport.Raw_Material_PortNo.ToString();
            serialPort1.BaudRate = 9600;
            serialPort1.DataBits = 7;
            serialPort1.StopBits = StopBits.One;
            serialPort1.Parity = Parity.Even;
            serialPort1.Open();
            lblPort1state.Text = "متصل";
        }

        private void ReadSerialData1()
        {
            try
            {
                Thread ReadSerialDataThread1 = new Thread(ReadSerial1);
                ReadSerialDataThread1.Start();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

        }

        }
        private void ReadSerial1()
        {
            while (serialPort1.IsOpen )
            {
                try
                {
                readserialvalue = serialPort1.ReadLine();
                ShowSerialData1(readserialvalue);
                }
                catch { }
            }
        }

        private delegate void UpdateUi1TextDelegate(string r);
        private void ShowSerialData1(string s)
        {

            s = s.Trim(char1);
            s = s.TrimEnd('k', 'g', '\r', '\n');
            if (Raw_mat_Scale.InvokeRequired)
            {
                UpdateUi1TextDelegate updateUi1 = new UpdateUi1TextDelegate(ShowSerialData1);
                Invoke(updateUi1, readserialvalue);
            }
            else
            {
                Raw_mat_Scale.Text = s;

            }
        }

        #endregion Serial Comm
        public void btnStart_Click(object sender, EventArgs e)
        {
            try
            {

                // start process
                 Task.Run(() => WeighingRawMaterial());

                Task.Run(() => WeighingOil());

                Task.Run(() => WeighingSurf());

            }
            catch
            {

            }

        }

        public void WeighingRawMaterial()
        {
            #region
        RawMatScale = float.Parse(Raw_mat_Scale.Text);

         target1_fastspeed = (float) (T1 - (fs1));
         target1_slowspeed =  T1;

         // the logic for weighing raw material according to the formula repeated 9 times for another 9 different material
         #endregion

            try
            {
                for (Currbatch = 1; Currbatch <= TolBatch; Currbatch++) ;
                {
                 //   txtCurBatch.Text = Currbatch.ToString();
                // bin#1
                if (T1 != 0.00)
                    Batch_bin1();

                // bin#2
                if (T2 != 0.00)
                    Batch_bin2();

                // bin#3
                if (T3 != 0.00)
                    Batch_bin3();

                // bin#4
                if (T4 != 0.00)
                    Batch_bin4();

                // bin#5
                if (T5 != 0.00)
                    Batch_bin5();

                //bin#6
                if (T6 != 0.00)
                    Batch_bin6();

                // bin#7

                if (T7 != 0.00)
                    Batch_bin7();

                // bin#8
                if (T8 != 0.00)
                    Batch_bin8();

                // bin #9

                if (T9 != 0.00)
                    Batch_bin9();
                }

                txtControlState.Text = "Finished Weighing";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "Raw");
            }
        }

        #region bin 1-11

        #region bin1

        public  void Batch_bin1()
        {

          txtControlState.Text = "خزان 1";

            //Fast speed
            do
            {
                plc.SetDevice("M326", 1);

                //FB from PLC
                plc.GetDevice("M326", out FB1);
                UpdateFB1(FB1);
                act1 = RawMatScale;
                err1 = (float)((float)act1 - T1);
                UpdateActErr1(act1, err1);
            }
            while (RawMatScale <= target1_fastspeed);

            // Slow speed
            do
            {
                plc.SetDevice("M326", 0);
                plc.GetDevice("M326", out FB1);
                UpdateFB1(FB1);
                act1 = RawMatScale;
                err1 = (float)((float)act1 - T1);
                UpdateActErr1(act1, err1);

                Thread.Sleep(halt1 * 1000);

                plc.SetDevice("M326", 1);
                plc.GetDevice("M326", out FB1);
                UpdateFB1(FB1);
                act1 = RawMatScale;
                err1 = (float)((float)act1 - T1);
                UpdateActErr1(act1, err1);

                Thread.Sleep(100);

                act1 = RawMatScale;
                err1 = (float)((float)act1 - T1);
                UpdateActErr1(act1, err1);
                plc.SetDevice("M326", 0);
                plc.GetDevice("M326", out FB1);
                UpdateFB1(FB1);

                Thread.Sleep(halt1 * 1000);

                act1 = RawMatScale;
                err1 = (float)((float)act1 - T1);
                UpdateActErr1(act1, err1);
            }
            while (RawMatScale <= target1_slowspeed && RawMatScale >= target1_fastspeed);
            plc.SetDevice("M326", 0);
            plc.GetDevice("M326", out FB1);
            UpdateFB1(FB1);
            act1 = RawMatScale;
            err1 = (float)((float)act1 - T1);
            UpdateActErr1(act1, err1);

            }

        private delegate void UpdateActErr1Delegate(float act1, float err1 );
        public  void UpdateActErr1(float a, float b)
        {
            if (txtAct1.InvokeRequired || txtErr1.InvokeRequired)
            {
                UpdateActErr1Delegate updateActErr1Ui = new UpdateActErr1Delegate(UpdateActErr1);
                Invoke(updateActErr1Ui, act1,err1);
            }
            else
            {
                txtAct1.Text = a.ToString();
                txtErr1.Text = b.ToString();
            }
        }

        private delegate void UpdateFB1Delegate(int fb1);
        public  void UpdateFB1(int ffb1)
        {
            if (Y2_On.InvokeRequired || Y2_Off.InvokeRequired)
            {
                UpdateFB1Delegate updateFB1 = new UpdateFB1Delegate(UpdateFB1);
                Invoke(updateFB1, FB1);
            }
            else
            {
                if (FB1 == 1)
                {
                    Y2_On.Show();
                    Y2_Off.Hide();
                }
                else
                {
                    Y2_On.Hide();
                    Y2_Off.Show();
                }

            }

        }

        #endregion bin1
            #region bin Oil

            public void WeighingOil()
            {
                if (T10 != 0.00)
                {
                try
                {
                    for(Currbatch=1;Currbatch<=TolBatch;Currbatch++)
                    {

                    txtOilState.Text = "وزن الزيت";
                    Oilscale = float.Parse(OilScale.Text);
                    target10_fastspeed = (float)((float)T10 - (fs9));
                    target10_slowspeed = (float)((float)T10);

                    //Fast speed
                    do
                    {

                    plc.SetDevice("M336", 1);

                                //FB from PLC
                    plc.GetDevice("M336", out FB10);
                                UpdateFB10(FB10);
                                act10 = Oilscale;
                        err10 = (float)((float)act10 - T10);
                        UpdateActErr10(act10, err10);

                    }
                  while (Oilscale <= target10_fastspeed);

                // Slow speed
                do
                {
                        act10 = Oilscale;
                        err10 = (float)((float)act10 - T10);
                        UpdateActErr10(act10, err10);

                        plc.SetDevice("M336", 0);
                        plc.GetDevice("M336", out FB10);
                                UpdateFB10(FB10);

                        Thread.Sleep(halt10 * 1000);

                        act10 = Oilscale;
                        err10 = (float)((float)act10 - T10);
                        UpdateActErr10(act10, err10);

                        plc.SetDevice("M336", 1);
                        plc.GetDevice("M336", out FB10);
                        UpdateFB10(FB10);

                        Thread.Sleep(100);

                        act10 = Oilscale;
                        err10 = (float)((float)act10 - T10);
                        UpdateActErr10(act10, err10);
                        plc.SetDevice("M336", 0);
                                plc.GetDevice("M336", out FB10);
                                UpdateFB10(FB10);

                                Thread.Sleep(halt10 * 1000);

                        act10 = Oilscale;
                        err10 = (float)((float)act10 - T10);
                        UpdateActErr10(act10, err10);
                    }
                    while (Oilscale <= target10_slowspeed && Oilscale >= target10_fastspeed);

                plc.SetDevice("M336", 0);

                            //FB from PLC
                            plc.GetDevice("M336", out FB10);
                            UpdateFB10(FB10);
                            act10 = Oilscale;
                            err10 = (float)((float)act10 - T10);
                            UpdateActErr10(act10, err10);
                        }

                    }

                catch (Exception ex)
                {
                        MessageBox.Show(ex.Message + "Oil"); }
                }
                txtOilState.Text = "تم وزن الزيت";
            }

            private delegate void UpdateActErr10Delegate(float act10, float err10 );
            public  void UpdateActErr10(float s, float t)
            {
                if (txtAct10.InvokeRequired || txtErr10.InvokeRequired)
                {
                    UpdateActErr10Delegate updateActErr10Ui = new UpdateActErr10Delegate(UpdateActErr10);
                    Invoke(updateActErr10Ui, act10, err10);
                }
                else
                {
                    txtAct10.Text = s.ToString();
                    txtErr10.Text = t.ToString();

                }
            }

            private delegate void UpdateFB10Delegate(int fb10);
            public  void UpdateFB10(int ffb10)
            {
                if (Oil_FB_On.InvokeRequired || Oil_FB_Off.InvokeRequired)
                {
                    UpdateFB10Delegate updateFB10 = new UpdateFB10Delegate(UpdateFB10);
                    Invoke(updateFB10, FB10);
                }
                else
                {
                    if (FB10 == 1)
                    {
                        Oil_FB_On.Show();
                        Oil_FB_Off.Hide();
                    }
                    else
                    {
                        Oil_FB_On.Hide();
                        Oil_FB_Off.Show();
                    }

                }

            }

            #endregion bin Oil

            #region bin Surf

            public void WeighingSurf()
                {
                    if (T11 != 0.00)
                    {

                        try
                        {
                            for (Currbatch = 1; Currbatch <= TolBatch; Currbatch++)
                                txtSurfState.Text = "وزن السرف";
                            Surfscale = float.Parse(SurfScale.Text);
                            target11_fastspeed = (float)((float)T11 - (fs11));
                            target11_slowspeed = (float)((float)T11);

                            //Fast speed
                            do
                            {

                                plc.SetDevice("M400", 1);

                                //FB from PLC
                                plc.GetDevice("M400", out FB11);
                                if (FB11 == 1)
                                {
                                    Surf_FB_On.Show();
                                    Surf_FB_Off.Hide();
                                }
                                else
                                {
                                    Surf_FB_On.Hide();
                                    Surf_FB_Off.Show();
                                }

                                act11 = Surfscale;
                                err11 = (float)((float)act11 - T11);
                                UpdateActErr11(act11, err11);
                            }
                            while (Surfscale <= target11_fastspeed);

                            // Slow speed
                            do
                            {
                                act11 = Surfscale;
                                err11 = (float)((float)act11 - T11);

                                plc.SetDevice("M400", 0);
                                plc.GetDevice("M400", out FB11);
                            UpdateFB11(FB11);

                            Thread.Sleep(halt11 * 1000);

                                act11 = Surfscale;
                                err11 = (float)((float)act11 - T11);
                                UpdateActErr11(act11, err11);

                                plc.SetDevice("M400", 1);
                                plc.GetDevice("M400", out FB11);
                            UpdateFB11(FB11);

                            Thread.Sleep(100);

                                act11 = Surfscale;
                                err11 = (float)((float)act11 - T11);
                                UpdateActErr11(act11, err11);

                                plc.SetDevice("M400", 0);
                                plc.GetDevice("M400", out FB11);
                            UpdateFB11(FB11);

                            Thread.Sleep(halt11 * 1000);

                                act11 = Surfscale;
                                err11 = (float)((float)act11 - T11);
                                UpdateActErr11(act11, err11);
                            }
                            while (Surfscale <= target11_slowspeed && Surfscale >= target11_fastspeed);

                            plc.SetDevice("M400", 0);

                            //FB from PLC
                            plc.GetDevice("M400", out FB11);
                        UpdateFB11(FB11);
                        act11 = Surfscale;
                        err11 = (float)((float)act11 - T11);
                        UpdateActErr11(act11, err11);

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + "Surf");
                        }
                    }

                    txtSurfState.Text = "تم وزن السرف";
                }

            private delegate void UpdateActErr11Delegate(float act11, float err11);

            public  void UpdateActErr11(float u, float v)
            {
                if (txtAct11.InvokeRequired || txtErr11.InvokeRequired )
                {
                    UpdateActErr11Delegate updateActErr11Ui = new UpdateActErr11Delegate(UpdateActErr11);
                    Invoke(updateActErr11Ui, act11, err11 );
                }
                else
                {
                    txtAct11.Text = u.ToString();
                    txtErr11.Text = v.ToString();

                }

            }

            private delegate void UpdateFB11Delegate(int fb11);
            public  void UpdateFB11(int ffb11)
            {
                if (Surf_FB_On.InvokeRequired || Surf_FB_Off.InvokeRequired)
                {
                    UpdateFB11Delegate updateFB11 = new UpdateFB11Delegate(UpdateFB11);
                    Invoke(updateFB11, FB11);
                }
                else
                {
                    if (FB11 == 1)
                    {
                        Surf_FB_On.Show();
                        Surf_FB_Off.Hide();
                    }
                    else
                    {
                        Surf_FB_On.Hide();
                        Surf_FB_Off.Show();
                    }

                }

            }

            #endregion bin Surf

            #endregion bin 1-11

            public void Mixing()
            {
                txtControlState.Text = "Mixing";
                txtAct1.Text = "0.00";
               //txtAct.Text is repeated 11 times

            }

            private void Raw_mat_Scale_TextChanged(object sender, EventArgs e)
            {
                try
                {
                RawMatScale = float.Parse(Raw_mat_Scale.Text);
                }
                catch
                {

                }
            }

            private void OilScale_TextChanged(object sender, EventArgs e)
            {
                try
                {
                    Oilscale = float.Parse(OilScale.Text);
                }
                catch
                {

                }
            }

            private void SurfScale_TextChanged(object sender, EventArgs e)
            {
                try
                {
                    Surfscale = float.Parse(SurfScale.Text);
                }
                catch
                {

                }

            }
            public string Comm_Data_Scale1
            {
                get { return Raw_mat_Scale.Text; }
                set { Raw_mat_Scale.Text = value; }
            }

            public void BtnQuit_Click(object sender, EventArgs e)
            {
                Form1 form1 = new Form1();
                serialPort1.Close();
                serialPort2.Close();
                this.Hide();
                form1.Show();
            }

            private void btnPause_Click(object sender, EventArgs e)
            {
                // pause the process in its current state

            }

            private void btnStop_Click(object sender, EventArgs e)
            {
                //finish the current batch
                plc.SetDevice("M326", 0);
                plc.SetDevice("M328", 0);
                plc.SetDevice("M329", 0);
                plc.SetDevice("M330", 0);
                plc.SetDevice("M331", 0);
                plc.SetDevice("M332", 0);
                plc.SetDevice("M333", 0);
                plc.SetDevice("M334", 0);
                plc.SetDevice("M335", 0);
                plc.SetDevice("M336", 0);
                plc.SetDevice("M400", 0);

            }

            private void btnUrgent_Click(object sender, EventArgs e)
            {
                // stop the process in its current state , no start

            }
        }
    }

I just want to know how to optimize my app so it run smoothly and any advice or tips on how to make my code better and how to upgrade my self in programming I all new to this.


text:
Q: How to access struct values inside of another struct in Swift 4? I currently have
struct cellData {
    var opened = Bool()
    var title = String()
    var iconName = String()
    var sectionData = [Any]()
}

struct SectionData {
    var subTitle: String
    var iconName: String
}

And in another function I call:
let test = tableViewData[indexPath.section].sectionData[dataIndex]

print(test)

Which outputs:
SectionData(subTitle: "Terms", iconName: "")

How do I access the subTitle value because doing test.subTitle throws the following error:
Value of type 'Any' has no member 'subTitle'

A: This is because, in your line var sectionData = [Any](), you have defined the type as Any. So when you access it via tableViewData[indexPath.section], you get back the value as Any.
You should change var sectionData = [Any]() to var sectionData = [SectionData]()
Otherwise, once you get the value from tableViewData[indexPath.section], you can convert to SectionData and then access the value.

A: Change your sectionData array to an array of SectionData like so: var sectionData = [SectionData](). Once you do this, you'll able to access it by calling: tableViewData[indexPath.section].sectionData[dataIndex].subTitle


text:
Q: How to resolve unreviewed code warnings We are using Jira 6.4.1 connected to Bit bucket 4.3.2. When i look at the releases for my project i see a number of warnings for some specific Jiras. The warning is:

Unreviewed Code These issues have been marked complete but the commits
  are not part of a pull request or review.

Usually as my workflow i may push commits direct to the repo without code review; but the issues listed seem a bit random and i can workout whats been done with them.
What causes this state and warning, and how can i resolve it?

A: This issue can happen regardless of using pull requests, for example if someone refers to the issue only in a merge commit message.
To resolve this and get rid of the warning, you can create an empty commit (git commit --allow-empty -m "Review ISSUE-13") in a new branch that references all the issues affected using the commit message. Then open a pull request for it and merge it as usual. Jira will see the pull request as being merged and the warning is cleared.

A: This warning is caused by having a jira issue key used in commits, but that issue key not appearing in a pull request or review. The assumption is made that all code included in that release should be reviewed.
There are two ways to remove that warning. The first is to change your development process and start using pull requests instead of committing straight to master.
The second is to turn that warning off. On the warnings tab there should be a button Manage Warnings that opens a dialogue where you can select what will trigger a warning. You want to unselect the Unreviewed Code checkbox.


text:
Q: iMac fan going on and off We have an iMac at our house which hasn't been turned on for about two month. I've turned it on and I'm getting some updates done, but the iMac fan is behaving weirdly. It goes full speed, and then stops, and then goes at full speed again, at random intervals. It's almost like the CPU thinks the machine is overheating but is hesitant to put the fans on full power.
The fans would go on full power for about 3 seconds, and then keep quite, and then go at it again. I have absolutely no idea what's going on. I have my Macbook in the same room, and it's running as smooth as ever. Is a security compromise a possibility here?


text:
Q: Possible to modify settings for which display windows open in? I have a two monitor setup. Often the window opening behavior seems to be quite the opposite of what I'd like.
For example: I can have a web-browser in one monitor, and I open up a terminal in the other display and xdg-open something, then the new window will open on top of my browser, instead of it being on top of the terminal.
Similarly, I have the launcher on both monitors, but if I open a new window from the launcher, it seems like it typically opens in whichever monitor has focus at the time that it loads. This is problematic if it takes time to load, because again, I could have my web-browser open already and want to open something else. If I click on the launcher in the other monitor and then go back to my browser, it will open in the browser's monitor.
I'm pretty sure I'm using unity, although I'm a bit confused because this is my output when I follow the instructions for finding out given here:
$ cat /etc/X11/default-display-manager
/usr/sbin/lightdm


text:
Q: Cannot find TData or TValue in the tanstack typescript library I am using react-table version 8 aka Tanstack table. Why are the types TData and TValue not found? And what is the best way to handle this?
I have a function that takes an argument of type Cell.
If I just write the fn like this,
 const getCellValue = (cell: Cell<TData, TValue>): void => {
    // .. function body
  }

I get the error...

So I added the 2 type arguments like so...
 const getCellValue = (cell: Cell<TData, TValue>): void => {
    // .. function body
  }

These type arguments TData and TValue are not found in the tanstack library.

What is the solution?
New to typescript and new to tanstack.
Perhaps I'm importing TData and TValue improperly?
Perhaps the Tanstack type files are not complete?
Perhaps I need to use a different type rather than Cell in my file.
Cheers

A: From here we found that:
data: TData[]

So, TData is our table data type, you can use your data interface here. For example, Order[], Todo[], etc.
A generic type table can be implemented as follows:
import {
  ColumnDef,
  useReactTable,
  ...
} from "@tanstack/react-table";

interface ReactTableProps<TData> {
  data: TData[];
  columns: ColumnDef<TData>[];
}

const ReactTable = <TData extends object>({
  data,
  columns,
}: ReactTableProps<TData>) => {
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    ...
  )
}

and TValue is the value type (string, number, etc.).
Here is the example:


text:
Q: Как использовать Rest API отдельно от сайта Laravel? Всем привет! Хотел создать сайт парсер объявлений и нужно написать к нему как сервис rest api, в который будет хранить, изменять, удалять и добавлять информацию об объявлениях. Будет ли уместно сделать это в одном проекте? Просто сделать роутинг api и web. Или создать отдельные два проекта, где будет сайт и rest, как bulletin и bulletin-service?

A: Отделять API от монолита стоит при одном из 3 условий:

*

*Вы планируете, что над проектом будет работать несколько программистов, и каждый будет ответственен за свою часть. Так будет проще шарить и мержить проект кусками.

*Вы планируете высоконагруженный проект с контейнеризацией в кубер кластер или бессерверную архитектуру.

*Вы предполагаете, что логика парсера (сервиса) будет прожорливой и будет сжирать ресурсы, необходимые для сайта.
В ином случае, я думаю, что отделение избыточно и приведёт к потере скорости разработки.


text:
Q: Syntax highlighting for .tpl file in Aptana Studio 3 I am trying to edit a smarty php template file in Aptana studio 3, and unfortunately it is very very plain, black text on a white background.
I would like to activate syntax highlighting for .tpl files.
I have already tried going to Preferences > General > Content types and have added ****.tpl*** to the HTML and PHP sections under text, but to no avail.
I am running Mac OSX 10.8 Mountain Lion, any idea how I can get the syntax highlighting to work on the .tpl file?
Thanks.

A: Try  Preferences > General > Content types  add *.tpl to php source in the text dropdown.

A: First check whether *.tpl is included in your associated files.
Go to Preferences >  General > Editors > File Associations
Check in the list whether **.tpl* exists, if not add it.
Select *.tpl and if Associated editors is empty click Add and add PHP Source Editor and press OK
Then - as Gabriel Catillo said - go to Preferences > General > Content Types and add .tplto PHP Source in the Text dropdown.
You might need to close and reopen your .tpl files for this to take effect.


text:
Q: .:Duplicated:..formatting - text cells and math cells I'm writing a formulary in Mathematica and I'm experiencing issues while formatting the text. I create a new notebook and a text cell (Alt+9) with text style. Let's say I'm writing the following

The solutions are x, x2,x3

A math cell is automatically created when I do the superscript Ctrl+6, and it contains only "x2,x3". More general, a math cell is created whenever I try to insert things from Palettes > Writing Assistant (or "Basic Math")
Since I don't want this to happen, how can I write math formulas outside a math cell.
I know it is possible because I have a notebook where this doesn't happen,that is I can write any maths formulas in the same text cell.
Perhaps the image might clarify

Is there a way to do this?


text:
Q: Regex to extract number from "ISBN: 9783295359" I've got data formatted like this:
ISBN: 9783295359
How can I use a regex to isolate only the number 9783295359?
I only need the number, so I need to exclude the "ISBN: ".

A: Normal Version
Try this RegEx:
ISBN:\s*(\d+)

The data is stored in the first capture group. To make it slightly safer, add a $ to the end
Live Demo on RegExr
How it works:
ISBN:    # (ISBN:)
\s*      # Optional Whitespace
(\d+)    # Capture Digits

Simplest Version
Note that you could get it as short as (\d+) (since the only set of digits is the number you want to extract), or slightly safer, (\d+)$ (to make sure the number appears at the end of the string)
Live Demo on RegExr

Safest Version
The safest version would be this:
ISBN:\s*(\d{10})$

The {10} specifies 10 digits, i.e it is equivalent to \d\d\d\d\d\d\d\d\d\d
Live Demo on RegExr

If you cannot get data from one capture group for whatever reason, or just want shorter code, you can use a Positive Lookbehind to not select the ISBN: part. You could need to change the ISBN:\s* part to:
(?<=ISBN:\s)

Note that this will only allow one whitespace between the : and ISBN Number. Also, this method only works if you are using PCRE (Pearl Compatible Regular Expressions). You can also remove the () around \d+
Live Demo on Regex101

A: You an extract this using simple regex. See PCRE example below.
(?<=ISBN:\s)(\d+)

This regex will exclude ISBN: and just capture numeric part.
See demo at https://regex101.com/r/zK1uM9/1


text:
Q: nonvanishing higher cohomology of a very ample divisor I am looking for smooth projective varieties $X$, with $h^i(X, \mathcal{O}_X) = 0$ for $i > 0$, with a very ample line bundle $L$ with some nonvanishing higher cohomology.
What is clear:
(1) Curves will not work (because $\mathbf{P}^1$ is the only such curve)
(2) Fano varieties will not work, by Kodaira vanishing (in char. 0)
(3) Hypersurfaces and complete intersections will not work, because the only ones with $h^i(X, \mathcal{O}_X) = 0$ for $i > 0$ will be Fano
Maybe $X$ can be a surface of non-negative Kodaira dimension with $p_g = q = 0$, e.g. general type or Enriques?
(Note that the question is easy if I just wanted ample $L$, not very ample, as $L = \mathcal{O}(K_X)$ on a Godeaux surface or a fake projective plane would be such an example.)


text:
Q: Binding Errors in DataTemplated ListBoxItems Currently i have a user control which contains a listbox of other visual element user controls; which (for this special case) have been data templated.
<Grid>
    <ListBox ItemSource="{Binding Path=UserControlCollection}">
        <ListBox.ItemTemplate>
             <DataTemplate>
                  <StackPanel Orientation="Horizontal">
                      <ContentPresenter Content="{Binding}"/>
                      <Button/>
                  </StackPanel>
             </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

The issue is that i have This Issue. And because of the data template, i can't seem to find a way to correct the styling issue.
Any help would be greatly appreciated.

A: I found by overriding the ListBoxItem's horizontalcontentalignment and verticalcontentalignment i was able to correct the issue.
 <ListBox.ItemContainerStyle>
     <Style TargetType="ListBoxItem">
         <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
         <Setter Property="VerticalContentAlignment" Value="Stretch"/>
     </Style>
 </ListBox.ItemContainerStyle>

I also found changing to a listview helpful but did have issues of its own.


text:
Q: Prevent variable value from resetting on refresh in Firebase I made a simple click event in javascript, when button clicked variabel i adds value with 150. Then I send it to firebase. But when I refresh my index page and click button again the value restart at 0 again in Firebase.
What code do I need to change?
var myDataRef = new Firebase('https://***.firebaseIO.com');
var i = 0;

$('.btn').click(function() {
   i = i + 150;
   myDataRef.set({value: i});
});

$('.progress-bar').css({ 'width' : i});

$(document).ready(main);

A: You currently initialize i to 0 when the page loads.
You should also get the value from Firebase, which you can do with:
myDataRef.child('value').once('value', function(snapshot) {
    i = snapshot.val();
});

If you combine that with the existing code and clean it up a bit, it becomes:
var myDataRef = new Firebase('https://***.firebaseIO.com');

var i = 0;
$('.progress-bar').css({ 'width' : i});

myDataRef.child('value').on('value', function(snapshot) {
    i = snapshot.val();
    $('.progress-bar').css({ 'width' : i});
});

$('.btn').click(function() {
   myDataRef.set({value: i + 150});
});

$(document).ready(main);

Note that the initial snippet I gave uses once('value', while here we use on('value'. This means the latest code will actually keep listening for updated values from Firebase, which is normally what you want.
So the initial flow here is:

*

*You initialize i to 0 and draw the progress bar

*You start listening for values from Firebase

*You start listening for click events

*At some point a new value arrives from Firebase, which

*Updates i and the progress bar

Then when the user clicks the button:

*

*You update the value in Firebase, which triggers steps 4 and 5 from above

A: The variable restarts from 0 because you reload your page code so the initialization of i = 0 executes again.
To avoid this you can:

*

*Extract i to another file that don't get reloaded, using it like a variable external to this file scope.

*Read the value from your current Firebase value


text:
Q: About viewController's "viewDidLoad" and "viewWillAppear" methods I've got a question regarding the two mentioned methods, since in my tests I don´t make clear the order they are called. I thought that, firstly, viewDidLoad is called when the viewController is loaded for first time (as the name indicates), and inmediately after the init method. Then, I thought that once viewDidLoad returns, viewWillAppear is called. If you display another viewController, and then you return to this one, then it should be already loaded and only viewWillAppear will be called.
However, while developing I make the impression that there is no order when calling viewDidLoad and viewWillAppear... I couldn´t find a clear description of this lifecycle in Apple's documentation, how does this actually work?
Thanks!

A: -viewDidLoad is called when the controller loads its view, which is not necessarily right after initialization. View controllers don't load their views until they need them, either to display or for any other reason.
-viewWillAppear is called just before the view is displayed. This will be after -viewDidLoad, but you don't know exactly how long after. -viewWillAppear is called every time the view is displayed; -viewDidLoad will only be called a second time if the view is unloaded at some point (such as didReceiveMemoryWarning). These days that's unusual, but it can happen.
Or if the viewController is set to nil, which can usually happen if a view controller is kicked off the navigation stack, and therefore next time it is brought to the navigation stack it needs to call -viewDidLoad again.

A:
I thought that, firstly, viewDidLoad is called when the viewController
  is loaded for first time (as the name indicates), and inmediately after the init method

No. The name indicates that the controller's view has been loaded (not the controller itself). Actually the docs state that this method will get called after the view hierarchy has been loaded into memory (either via loadView or through a nib for example).

Then, I thought that once viewDidLoad returns, viewWillAppear is
  called

Again, no. loadView (and as a consequence viewDidLoad) method will get called the first time that view property is to be accessed and is nil (which is the case when you're initializing a controller). Think of this simple scenario:
MyViewController *vc = [[MyViewController alloc] init];
UIView *view = vc.view; // <= loadView & viewDidLoad will fire but it certainly didn't appear...

However, while developing I make the impression that there is no order
  when calling viewDidLoad and viewWillAppear...

Well there is an order. We know for sure that viewWillAppear will always be called after viewDidLoad (if both of them are to be called of course).

A: I would like to add to Caleb's answer: Don't confuse the view controller and the view! The name viewDidLoad clearly indicates that the method is invoked after the view has been loaded. It is the view controller that does the loading.
Some pointers regarding the lifecycle of views and the order in which messages are sent:

*

*Not an official Apple document, but I find this diagram really useful because it includes pretty much all of UIViewController's lifecycle overrides.

*In the section Resource Management in View Controllers from Apple's "View Controller Programming Guide" there is a flowchart that depicts how views are initially loaded. It explains loadView and viewDidLoad, also in conjunction with storyboards.

*The section Responding to Display-Related Notifications from Apple's "View Controller Programming Guide" explains how to respond to views appearing and disappearing (viewWillAppear: et al)

*If you are planning on implementing a container view controller: The UIViewController class reference has a good overview of how messages need to be sent by your subclass.

I'm stopping here. You can find more stuff yourself by googling for "uiviewcontroller life cycle".

A: As you said, ViewDidLoad is only calling once after loading the view. So we can initialize the instances in the viewDidLoad. It is mainly meant for the initialization.
viewWillAppear will invoke whenever we reach to this view. So if there is any changes in UI, we can done it in viewWillAppear.

A: I ran a trace on when all these calls are made: http://thecodist.com/article/ios_arc_storyboards_and_uiviewcontroller_trace