text:
Q: Feynman-diagram with tikz - vertically I have a Feynman diagram. Is it possible to make the time arrow (right in the image) some centimeters from the Feynman-diagram? And is it possible to make the \draw[fermion] longer and the node above smaller?
Code is based on an answer from Harish Kumar.
\documentclass{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}

\usepackage{pgfplots}
\usepackage{xparse}
\usepackage[left=1cm,right=1cm,top=2cm,bottom=2cm]{geometry}

\usetikzlibrary{positioning,arrows,patterns}
\usetikzlibrary{decorations.markings}
\usetikzlibrary{calc}

\tikzset{
  photon/.style={decorate, decoration={snake}, draw=black},
  fermion/.style={draw=black, postaction={decorate},decoration={markings,mark=at position .55 with {\arrow{>}}}},
}

\begin{document}
\pagestyle{empty}

\iffalse
\begin{equation*}
\left ( 2 \pi \right )^4 \int \left [ \bar{v}^{(s_2)} \left ( p _3 \right ) \left (i \sqrt{4 \pi \alpha}\gamma^\mu \right ) v^{(s_1)} \left ( p _1 \right ) \right ] \frac{i g_{\mu\nu}}{q^2} \left [ \bar{v}^{(s_4)} \left ( p _4 \right ) \left ( i \sqrt{4 \pi \alpha}\gamma^\mu \right ) v^{(s_2)} \left ( p _2 \right ) \right ] \times \delta ^{(4)} \left (p _1 - p _3 - q \right ) \delta ^{(4)} \left ( p _2 + q - p _4 \right ) d^4 q
\end{equation*}
\fi

\begin{figure}
\centering
\begin{tikzpicture}[node distance=1cm and 1cm]
\coordinate[] (v1);
\coordinate[right=of v1] (v2);
\coordinate[right=of v2] (v3);
\coordinate[right=of v3] (v4);
\coordinate[above right=of v4,label=right:$\mu$] (f1);
\coordinate[below right=of v4,label=right:$\mu$] (f2);
\coordinate[above left =of v1,label=left :$e$] (e1);
\coordinate[below left =of v1,label=left :$e$] (e2);
%The fermion
\draw[fermion] (v1) -- (e1) node[midway, sloped, above=0.1cm] {$p_3, s_3$};
\draw[fermion] (e2) -- (v1) node[midway, sloped, below=0.1cm] {$p_1, s_1$};
\draw[fermion] (v4) -- (f1) node[midway, sloped, above=0.1cm] {$p_4, s_4$};
\draw[fermion] (f2) -- (v4) node[midway, sloped, below=0.1cm] {$p_2, s_2$};
%The proton
\draw[photon] (v1) -- (v4) node[midway,below=0.1cm] {$\gamma$} node[midway, above=0.1cm]{$q$};
%the timeline
\draw[arrows=->,line width=1.2pt] (f2) -- (f1) node[midway, sloped, above=-0.05cm, rotate=180] {time};
\end{tikzpicture}
\end{figure}

\end{document}

Kind regards!
And thank you in advance!

A: You have to adjust the dimensions in
\coordinate[above right= 3cm and 3cm of v4,label=right:$\mu$] (f1);
\coordinate[below right= 3cm and 3cm of v4,label=right:$\mu$] (f2);
\coordinate[above left = 3cm and 3cm of v1,label=left :$e$] (e1);
\coordinate[below left = 3cm and 3cm of v1,label=left :$e$] (e2);

to make \draw[fermion] longer. To make node text smaller, use font=\footnotesize (or any size). Further to shift the time arrow use xshift as in
\draw[arrows=->,line width=1.2pt,] ([xshift=1cm]f2) -- ([xshift=1cm]f1) node[midway, sloped, above=-0.05cm, rotate=180] {time};

Code:
\documentclass[a4paper]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}

\usepackage{pgfplots}
\usepackage{xparse}
\usepackage[left=1cm,right=1cm,top=2cm,bottom=2cm]{geometry}

\usetikzlibrary{positioning,arrows,patterns}
\usetikzlibrary{decorations.markings}
\usetikzlibrary{calc}

\tikzset{
  photon/.style={decorate, decoration={snake}, draw=black},
  fermion/.style={draw=black, postaction={decorate},decoration={markings,mark=at position .55 with {\arrow{>}}}},
}

\begin{document}

\begin{figure}
\centering
\begin{equation*}
\left ( 2 \pi \right )^4 \int \left [ \bar{v}^{(s_2)} \left ( p _3 \right ) \left (i \sqrt{4 \pi \alpha}\gamma^\mu \right ) v^{(s_1)} \left ( p _1 \right ) \right ] \frac{i g_{\mu\nu}}{q^2} \left [ \bar{v}^{(s_4)} \left ( p _4 \right ) \left ( i \sqrt{4 \pi \alpha}\gamma^\mu \right ) v^{(s_2)} \left ( p _2 \right ) \right ] \times \delta ^{(4)} \left (p _1 - p _3 - q \right ) \delta ^{(4)} \left ( p _2 + q - p _4 \right ) d^4 q
\end{equation*}

\begin{tikzpicture}[node distance=1cm and 1cm]
\coordinate[] (v1);
\coordinate[right=of v1] (v2);
\coordinate[right=of v2] (v3);
\coordinate[right= of v3] (v4);
\coordinate[above right= 3cm and 3cm of v4,label=right:$\mu$] (f1);
\coordinate[below right= 3cm and 3cm of v4,label=right:$\mu$] (f2);
\coordinate[above left = 3cm and 3cm of v1,label=left :$e$] (e1);
\coordinate[below left = 3cm and 3cm of v1,label=left :$e$] (e2);
\draw[fermion] (v1) -- (e1) node[midway, sloped, above=0.1cm,font=\footnotesize] {$p_3, s_3$};
\draw[fermion] (e2) -- (v1) node[midway, sloped, below=0.1cm,font=\footnotesize] {$p_1, s_1$};
\draw[photon] (v1) -- (v4) node[midway,below=0.1cm] {$\gamma$} node[midway, above=0.1cm]{$q$};
\draw[fermion] (v4) -- (f1) node[midway, sloped, above=0.1cm,font=\footnotesize] {$p_4, s_4$};
\draw[fermion] (f2) -- (v4) node[midway, sloped, below=0.1cm,font=\footnotesize] {$p_2, s_2$};
\draw[arrows=->,line width=1.2pt,] ([xshift=1cm]f2) -- ([xshift=1cm]f1) node[midway, sloped, above=-0.05cm, rotate=180] {time};
\end{tikzpicture}
\end{figure}

\end{document}


text:
Q: Prove principal ideal with no unit $\neq$ non-zero ring A.
Let A be a non-zero commutative ring.  Let a ∈ A be an element which is not a unit. Prove that the principal ideal (a) is different from A .

Proof
$(a) = \left\{ a\cdot q  \ | \ q \in A\right\}$ and $\forall q \in A, \ a\cdot q \neq 1$. Thus $1
\notin (a)$ , since A is a non-zero ring 1 $\in$ A.
$\therefore(a) \neq A$
Is it correct? Did I miss some assumptions? The proof seems a bit too simple. This is a 3rd semester Math undergrad exercise.
Thanks

A: The only nitpick is that it could be more formal, by assuming that (a) = A and reaching a contradiction with a not being a unit, following the same chain of logic. But overall, it is correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to specify which NetworkInterface .net will use? I would like to run a series of tests on a device using its Wifi and LAN connections.  I have two network interface cards, one is WiFi, the other is wired.  The device has a single IP address that is accessible through both Network Interfaces.  Is there a way to guarantee that my machine is using a particular Network Interface so that I can run all tests through the wired connection, and then run all tests through the Wifi connection?
Keep in mind, both connections share the same subnet, so either will successfully connect to the device.  I just want to be able to switch back and forth and specify which connection I'm using at any given time.
I'm using HttpClient on .net with C#.  Is there a way to force HttpClient to use a particular Network Interface?  It seems to automatically choose one based on IP Address, but in this case, there are 2 Network Interfaces that can work.  I need to be able to programatically switch back and forth to run my automated tests.
I have noticed something called an 'Interface Metric' that can be changed manually via IP4 Properties Advanced TCP/IP Settings.  Will the smaller numbered interface be used every time?  Is there a way to change this value programatically?
MORE CLARIFICATION:  The reason I didn't directly jump to Disabling the WiFi NIC or the Wired NIC back and forth was when you disable the WiFi NIC, you disconnect the device it was connected to and it doesn't automatically reconnect when you enable it.  (even when you say 'connect automatically' it doesn't connect when re-enabled).  However, I found a quick solution.  Set the Interface Metric on the Wired NIC to be lower than the Interface Metric on the WiFi NIC.  Then, just enable and disable the Wired NIC.  When disabled, the WiFi NIC will be used by the system.  When enabled, the Wired NIC will be used by the system because its Interface Metric is set lower.  Now, I just need to figure out how to programatically enable/disable the Wired NIC...

A: One way would be to update your route table to force traffic for a particular IP onto a particular NIC. The route table is what is used to decide which NIC to send traffic out on.
You could do this in a couple of ways:
1) Use P/Invoke to update the route table with C# code (see here for a good example, but basically you are calling CreateIpForwardEntry).
2) Use Process.Start to call route.exe, e.g.
route.exe ADD destination_network MASK subnet_mask  gateway_ip metric_cost

and
route.exe CHANGE destination_network MASK subnet_mask  gateway_ip metric_cost

A: You can use the library WlanAPI.cs
static public void Connect_to_wifi(string ssid)
            {
                WlanClient client = new WlanClient();
                foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
                {
                    // Lists all networks with WEP security
                    //Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
                    //foreach (Wlan.WlanAvailableNetwork network in networks)
                    //{
                    //    if (network.dot11DefaultCipherAlgorithm == Wlan.Dot11CipherAlgorithm.WEP)
                    //    {
                    //        Console.WriteLine("Found WEP network with SSID {0}.", network.profileName);
                    //    }
                    //}

                    // Retrieves XML configurations of existing profiles.
                    // This can assist you in constructing your own XML configuration
                    // (that is, it will give you an example to follow).
                    foreach (Wlan.WlanProfileInfo profileInfo in wlanIface.GetProfiles())
                    {
                        if (profileInfo.profileName == ssid)
                        {
                            wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, wlanIface.GetProfileXml(profileInfo.profileName), true);
                            wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileInfo.profileName);
                            break;
                        }
                    }
                }
            }

A: Best way is to use WinSock bind: TCP/IP connection on a specific interface
But once you have single IP for bith NICs then:
Disable NIC from PowerShell: https://learn.microsoft.com/en-us/powershell/module/netadapter/disable-netadapter?view=win10-ps
Calling PowerShell from c#: https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

A: I ended up solving this by setting the Interface Metric on the wired NIC to be lower than the Interface Metric on the Wifi NIC.  In this way, I was able to simply disable and enable the Wired NIC which would effectively change which NIC was being used at any time during the test.  To Disable the NIC, I use the netsh.exe command with the following code.  The 'command' was either 'enable' or 'disable' depending if I was turning it on or off:
        System.Diagnostics.Process p = new System.Diagnostics.Process
        {
            StartInfo =
            {
                FileName = "netsh.exe",
                Arguments = $"interface set interface \"{nicName}\" {command}",
                UseShellExecute = false,
                RedirectStandardOutput = true
            }
        };

        bool started = p.Start();


text:
Q: How Stuff and 'For Xml Path' work in SQL Server? Table is:

Id
Name

1
aaa

1
bbb

1
ccc

1
ddd

1
eee

Required output:

Id
abc

1
aaa,bbb,ccc,ddd,eee

Query:
SELECT ID,
    abc = STUFF(
                 (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
               )
FROM temp1 GROUP BY id

This query is working properly. But I just need the explanation how it works or is there any other or short way to do this.
I am getting very confused to understand this.

A: Here is how it works:
1. Get XML element string with FOR XML
Adding FOR XML PATH to the end of a query allows you to output the results of the query as XML elements, with the element name contained in the PATH argument. For example, if we were to run the following statement:
SELECT ',' + name
              FROM temp1
              FOR XML PATH ('')

By passing in a blank string (FOR XML PATH('')), we get the following instead:
,aaa,bbb,ccc,ddd,eee

2.  Remove leading comma with STUFF
The STUFF statement literally "stuffs" one string into another, replacing characters within the first string. We, however, are using it simply to remove the first character of the resultant list of values.
SELECT abc = STUFF((
            SELECT ',' + NAME
            FROM temp1
            FOR XML PATH('')
            ), 1, 1, '')
FROM temp1

The parameters of STUFF are:

*

*The string to be "stuffed" (in our case the full list of name with a
leading comma)

*The location to start deleting and inserting characters (1, we're stuffing into a blank string)

*The number of characters to delete (1, being the leading comma)

So we end up with:
aaa,bbb,ccc,ddd,eee

3. Join on id to get full list
Next we just join this on the list of id in the temp table, to get a list of IDs with name:
SELECT ID,  abc = STUFF(
             (SELECT ',' + name
              FROM temp1 t1
              WHERE t1.id = t2.id
              FOR XML PATH (''))
             , 1, 1, '') from temp1 t2
group by id;

And we have our result:

Id
Name

1
aaa,bbb,ccc,ddd,eee

A: In for xml path, if we define any value like [ for xml path('ENVLOPE') ] then these tags will be added with each row:
<ENVLOPE>
</ENVLOPE>

A: PATH mode is used in generating XML from a SELECT query
1. SELECT
       ID,
       Name
FROM temp1
FOR XML PATH;

Ouput:
<row>
<ID>1</ID>
<Name>aaa</Name>
</row>

<row>
<ID>1</ID>
<Name>bbb</Name>
</row>

<row>
<ID>1</ID>
<Name>ccc</Name>
</row>

<row>
<ID>1</ID>
<Name>ddd</Name>
</row>

<row>
<ID>1</ID>
<Name>eee</Name>
</row>

The Output is element-centric XML where each column value in the resulting rowset is wrapped in an row element. Because the SELECT clause does not specify any aliases for the column names, the child element names generated are the same as the corresponding column names in the SELECT clause.
For each row in the rowset a  tag is added.
2.
SELECT
       ID,
       Name
FROM temp1
FOR XML PATH('');

Ouput:
<ID>1</ID>
<Name>aaa</Name>
<ID>1</ID>
<Name>bbb</Name>
<ID>1</ID>
<Name>ccc</Name>
<ID>1</ID>
<Name>ddd</Name>
<ID>1</ID>
<Name>eee</Name>

For Step 2: If you specify a zero-length string, the wrapping element is not produced.
3.

    SELECT

           Name
    FROM temp1
    FOR XML PATH('');

    Ouput:
    <Name>aaa</Name>
    <Name>bbb</Name>
    <Name>ccc</Name>
    <Name>ddd</Name>
    <Name>eee</Name>

4. SELECT
        ',' +Name
FROM temp1
FOR XML PATH('')

Ouput:
,aaa,bbb,ccc,ddd,eee

In Step 4 we are concatenating the values.
5. SELECT ID,
    abc = (SELECT
            ',' +Name
    FROM temp1
    FOR XML PATH('') )
FROM temp1

Ouput:
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee

6. SELECT ID,
    abc = (SELECT
            ',' +Name
    FROM temp1
    FOR XML PATH('') )
FROM temp1 GROUP by iD

Ouput:
ID  abc
1   ,aaa,bbb,ccc,ddd,eee

In Step 6 we are grouping the date by ID.
STUFF( source_string, start, length, add_string )
Parameters or Arguments
source_string
The source string to modify.
start
The position in the source_string to delete length characters and then insert add_string.
length
The number of characters to delete from source_string.
add_string
The sequence of characters to insert into the source_string at the start position.
SELECT ID,
    abc =
    STUFF (
        (SELECT
                ',' +Name
        FROM temp1
        FOR XML PATH('')), 1, 1, ''
    )
FROM temp1 GROUP by iD

Output:
-----------------------------------
| Id        | Name                |
|---------------------------------|
| 1         | aaa,bbb,ccc,ddd,eee |
-----------------------------------

A: SELECT ID,
    abc = STUFF(
                 (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
               )
FROM temp1 GROUP BY id

Here in the above query STUFF function is used to just remove the first comma (,) from the generated xml string (,aaa,bbb,ccc,ddd,eee) then it will become (aaa,bbb,ccc,ddd,eee).
And FOR XML PATH('') simply converts column data into (,aaa,bbb,ccc,ddd,eee) string but in PATH we are passing '' so it will not create a XML tag.
And at the end we have grouped records using ID column.

A: There is very new functionality in Azure SQL Database and SQL Server (starting with 2017) to handle this exact scenario. I believe this would serve as a native official method for what you are trying to accomplish with the XML/STUFF method. Example:
select id, STRING_AGG(name, ',') as abc
from temp1
group by id

STRING_AGG - https://msdn.microsoft.com/en-us/library/mt790580.aspx
EDIT: When I originally posted this I made mention of SQL Server 2016 as I thought I saw that on a potential feature that was to be included. Either I remembered that incorrectly or something changed, thanks for the suggested edit fixing the version. Also, pretty impressed and wasn't fully aware of the multi-step review process that just pulled me in for a final option.

A: I did debugging and finally returned my 'stuffed' query to it it's normal way.
Simply
select * from myTable for xml path('myTable')

gives me contents of the table to write to a log table from a trigger I debug.

A: Declare @Temp As Table (Id Int,Name Varchar(100))
Insert Into @Temp values(1,'A'),(1,'B'),(1,'C'),(2,'D'),(2,'E'),(3,'F'),(3,'G'),(3,'H'),(4,'I'),(5,'J'),(5,'K')
Select X.ID,
stuff((Select ','+ Z.Name from @Temp Z Where X.Id =Z.Id For XML Path('')),1,1,'')
from @Temp X
Group by X.ID

A: This article covers various ways of concatenating strings in SQL, including an improved version of your code which doesn't XML-encode the concatenated values.
SELECT ID, abc = STUFF
(
    (
        SELECT ',' + name
        FROM temp1 As T2
        -- You only want to combine rows for a single ID here:
        WHERE T2.ID = T1.ID
        ORDER BY name
        FOR XML PATH (''), TYPE
    ).value('.', 'varchar(max)')
, 1, 1, '')
FROM temp1 As T1
GROUP BY id

To understand what's happening, start with the inner query:
SELECT ',' + name
FROM temp1 As T2
WHERE T2.ID = 42 -- Pick a random ID from the table
ORDER BY name
FOR XML PATH (''), TYPE

Because you're specifying FOR XML, you'll get a single row containing an XML fragment representing all of the rows.
Because you haven't specified a column alias for the first column, each row would be wrapped in an XML element with the name specified in brackets after the FOR XML PATH. For example, if you had FOR XML PATH ('X'), you'd get an XML document that looked like:
<X>,aaa</X>
<X>,bbb</X>
...

But, since you haven't specified an element name, you just get a list of values:
,aaa,bbb,...

The .value('.', 'varchar(max)') simply retrieves the value from the resulting XML fragment, without XML-encoding any "special" characters. You now have a string that looks like:
',aaa,bbb,...'

The STUFF function then removes the leading comma, giving you a final result that looks like:
'aaa,bbb,...'

It looks quite confusing at first glance, but it does tend to perform quite well compared to some of the other options.


text:
Q: Popular error - org.sqlite.JDBC in apache netbeans 11.2 I know that this is a very common question, but I search a lot about it but cannot resolve my issue.
public static Connection connectDB(){
    try{
        Class.forName("org.sqlite.JDBC");
        Connection conn;
        conn = (Connection) DriverManager.getConnection("jdbc:sqlite:E:\\JAVA GUI\\Library\\library.sqlite");
        return conn;
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null,e);
        return null;
    }
}

it shows error

ClassNotFoundException org.sqlite.JDBC

I also installed and set a JDBC connector driver in Apache Netbeans, but still in vain. I am trying this from the last 2 days, but .
How can I fix this issue?
Thanks in advance...

A: For this issue i recommend to use this class and test, if you have a output data your connections is OK but it doesn't show anything verify your driver
For Sqlite
package net.sqlitetutorial;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author sqlitetutorial.net
 */
public class Connect {
     /**
     * Connect to a sample database
     */
    public static void connect() {
        Connection conn = null;
        try {
            // db parameters
            String url = "jdbc:sqlite:C:/sqlite/db/chinook.db";
            // create a connection to the database
            conn = DriverManager.getConnection(url);

            System.out.println("Connection to SQLite has been established.");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        connect();
    }
}

Article: https://www.sqlitetutorial.net/sqlite-java/sqlite-jdbc-driver/
For Oracle
importjava.sql.*;
importjava.util.*;
class Main
{
    public static void main(String a[])
    {
        //Creating the connection
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "system";
        String pass = "12345";

        //Entering the data
        Scanner k = new Scanner(System.in);
        System.out.println("enter name");
        String name = k.next();
        System.out.println("enter roll no");
        int roll = k.nextInt();
        System.out.println("enter class");
        String cls =  k.next();

        //Inserting data using SQL query
        String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
        Connection con=null;
        try
        {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

            //Reference to connection interface
            con = DriverManager.getConnection(url,user,pass);

            Statement st = con.createStatement();
            int m = st.executeUpdate(sql);
            if (m == 1)
                System.out.println("inserted successfully : "+sql);
            else
                System.out.println("insertion failed");
            con.close();
        }
        catch(Exception ex)
        {
            System.err.println(ex);
        }
    }
}

Check this tutorial: https://www.geeksforgeeks.org/establishing-jdbc-connection-in-java/


text:
Q: What am I doing wrong with this MERGE / INSERT query? I have a database table that I want to update with SQL. Basically, it carries a set of description information for parts of a timetable booklet, but that isn't important. Some of the data is entered already via an application, but it is time consuming and blocks of it are "boiler plate" that want to be updated each week. In some cases, I may have missed entering the data via the application, and so also want to create data automatically if it doesn't exist.
That leads me to use a MERGE query, as follows:
MERGE INTO TTP_LINE_DESCRIPTION o
USING
  (SELECT DISTINCT lv.lv_nv_id TLDE_NV_ID,
                   lv.lv_id TLDE_LV_ID,
                   dir.dir_id TLDE_DIR_ID,
                   8 TLDE_MED_FLAG,
                   1 TLDE_TYPE,
                   0 TLDE_SORT_NO,
                   'Timetable valid from ' || to_char(lv.lv_valid_from,'DD/MM/YYYY') || ' until ' || nvl2(lv.lv_valid_until,to_char(lv.lv_valid_until,'DD/MM/YYYY'),'further notice') TLDE_TEXT,
                   0 TLDE_ALIGNMENT,
                   null TLDE_FONT_SIZE,
                   null TLDE_FONT_STYLE
   FROM LINE_VERSION lv
   JOIN line_point_sequence lps ON (lv.lv_id = lps.lps_lv_id)
   JOIN direction dir ON (dir.dir_id = lps.lps_dir_id)
   where lv.lv_nv_id=3799 and lv.lv_id=10455244) n

ON (o.TLDE_NV_ID=n.TLDE_NV_ID
   and o.TLDE_LV_ID=n.TLDE_LV_ID
   and o.TLDE_DIR_ID=n.TLDE_DIR_ID
   and o.TLDE_TYPE=n.TLDE_TYPE
   and o.TLDE_SORT_NO=n.TLDE_SORT_NO)

WHEN MATCHED THEN
   UPDATE SET o.TLDE_TEXT=n.TLDE_TEXT,
      o.TLDE_ALIGNMENT=n.TLDE_ALIGNMENT,
      o.TLDE_FONT_SIZE=n.TLDE_FONT_SIZE,
      o.TLDE_FONT_STYLE=n.TLDE_FONT_STYLE

WHEN NOT MATCHED THEN
   INSERT (o.tlde_id, o.tlde_nv_id, o.tlde_lv_id, o.tlde_dir_id,
           o.tlde_med_flag, o.tlde_type, o.tlde_sort_no, o.tlde_text,
           o.tlde_alignment, o.tlde_font_size, o.tlde_font_style,
           o.updated_by, o.updated_on, o.updated_prog)
   VALUES ((select max(tld.tlde_id)+1 from TTP_LINE_DESCRIPTION tld),
           n.tlde_nv_id, n.tlde_lv_id, n.tlde_dir_id, n.tlde_med_flag,
           n.tlde_type, n.tlde_sort_no, n.tlde_text, n.tlde_alignment,
           n.tlde_font_size, n.tlde_font_style, 'STUARTR',
           SYSDATE, 'PL/SQL Developer');

There is one thing to note here, which is the WHERE clause in the SELECT DISTINCT. The lv.lv_id=10455244 is a reference that I know will force the select to return only a single pair of rows in that SELECT, so that I can limit my testing. For this purpose, 10455244 is a valid value that is NOT currently in the TTP_LINE_DESCRIPTION table.
When I use a value that is in the table, the WHEN MATCHED code executes correctly, and updates a pair of rows in 0.016s.
Running the SELECT statement on its own using the value I have shown above returns the two rows that need adding in 0.109s.
Getting the max id and adding one to it (this is the primary key) as per the first item in the VALUES line at the end takes 0s.
Finally, if I write an INSERT INTO and explicitly write all of the values that I want to write for one of the rows, I can do the INSERT of one row in 0.016s.
But put it all together and ... nothing. The execution just sits there, executing, and doesn't appear to end. Or I get nervous waiting to see if it will end. I've left it a reasonable time, and nothing seems to go in.
So what's going on, and why won't it do what I think that it should?

A: You are doing this:
create table t (id, nv_id, val) as (select 1, 101, 'A' from dual);

merge into t o
using (
  select 102 nv_id, 'P' val from dual union all
  select 103 nv_id, 'Q' val from dual ) n
on (o.nv_id = n.nv_id)
when matched then update set val = n.val
when not matched then
  insert (o.id, o.nv_id, o.val)
  values ((select max(id) + 1 from t), n.nv_id, n.val);

In my case it worked, but id for inserted rows was the same: 2. When I did rollback and added primary key constraint:
alter table t add constraint t_pk primary key(id);

merge caused error - unique constraint violated. I suspect that this is something connected to your tlde_id, maybe not constraint but something else. Generating values this way is a big no-no. If your Oracle version is 12c or higher you can change this column to auto generated
generated by default on null as identity

or in older versions use sequence and trigger (find max id, add 1 and set it as starting value for sequence)
create sequence seq_t_id start with 2;

create or replace trigger t_on_insert
  before insert on t for each row
begin
  select seq_t_id.nextval into :new.id from dual;
end;

Then modify your merge, either by removing id from insert clause or just insert null and trigger will set proper values:
merge into t o
using (
  select 102 nv_id, 'P' val from dual union all
  select 103 nv_id, 'Q' val from dual ) n
on (o.nv_id = n.nv_id)
when matched then update set val = n.val
when not matched then
  insert (o.nv_id, o.val)
  values (n.nv_id, n.val);

Even if this does not solve your problem you should not generate ids as max() + 1, this causes problems with concurent sessions, commits, multi inserts etc.


text:
Q: How do I create an Event Listener for Cursor.lockstate? I'd like to add an event listener for changes to Cursor.lockState in my unity WebGL game.
If the cursor is locked, I would like to unpause the game. If I detect the cursor has been unlocked I'd then like to pause.
Here is what I have so far
using UnityEngine;
using System.Collections;

public class Pause : MonoBehaviour {

public RotateCamera rotateCamera;
public GameObject pauseMenu;
private bool paused;

void Update()
{
    if (paused)
    {
        if (Input.GetMouseButtonDown(0))
        {
            UnpauseGame();
            return;
        }
    }
    if (Cursor.lockState == CursorLockMode.Locked)
    {
        Debug.Log("CursorLockMode = Locked");
        UnpauseGame();
        return;
    }
    if (Cursor.lockState == CursorLockMode.Confined)
    {
        Debug.Log("CursorLockMode = Confined");
        UnpauseGame();
        return;
    }

    if (Cursor.lockState == CursorLockMode.None && paused == false)
    {
        Debug.Log("CursorLockMode = None");
        PauseGame();
    }
}

public void PauseGame()
{
    Cursor.lockState = CursorLockMode.None;
    Cursor.visible = true;
    paused = true;
    pauseMenu.SetActive(true);
}

public void UnpauseGame()
{
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
    paused = false;
    pauseMenu.SetActive(false);
}
}

The problem is

*

*When trying to unpause the game with mouse button down the game instantly pauses itself. I believe the script detects that the cursor.lockstate is unlocked and instantly re-pauses the game.

To fix this, I think I need to create an event that listens to changes in the lock state and calls the method. Rather than the method being called every frame.

A:
I think I need to create an event that listens to changes in the lock
  state and calls the method. Rather than the method being called every
  frame.

This is simple. Don't use the Cursor API directly. Wrap another class around it then use property getter and setter to implement a simple event system. Check out Unity's Events and Delegates tutorial here.
The wrapper AdvanceCursor.cs:
public class AdvanceCursor
{
    //Not needed but included just because Cursor has a pulbic constructor
    private Cursor cursor;

    public AdvanceCursor()
    {
        cursor = new Cursor();
    }

    public static CursorLockMode lockState
    {
        set
        {
            Cursor.lockState = value;

            //Notify Event
            if (OnLockStateChanged != null)
            {
                OnLockStateChanged(value);
            }
        }

        get { return Cursor.lockState; }
    }

    public static bool visible
    {
        set
        {
            Cursor.visible = value;

            //Notify Event
            if (OnVisibleChanged != null)
            {
                OnVisibleChanged(value);
            }
        }

        get { return Cursor.visible; }
    }

    public static void SetCursor(Texture2D texture, Vector2 hotspot, CursorMode cursorMode)
    {
        Cursor.SetCursor(texture, hotspot, cursorMode);

        //Notify Event
        if (OnTextureChanged != null)
        {
            OnTextureChanged(texture, hotspot, cursorMode);
        }
    }

    /////////////////////////////////////////////EVENTS//////////////////////////////////

    //Event For LockState
    public delegate void cursorLockStateAction(CursorLockMode lockMode);
    public static event cursorLockStateAction OnLockStateChanged;

    //Event For visible
    public delegate void cursorVisibleAction(bool visible);
    public static event cursorVisibleAction OnVisibleChanged;

    //Event For Texture Change
    public delegate void cursorTextureAction(Texture2D texture, Vector2 hotspot, CursorMode cursorMode);
    public static event cursorTextureAction OnTextureChanged;
}

USAGE:
Simply subscribe to the events.
public class CursorTest: MonoBehaviour
{
    void Start()
    {
        AdvanceCursor.lockState = CursorLockMode.Locked;
        AdvanceCursor.visible = true;
        //AdvanceCursor.SetCursor(...);
    }

    //Subscribe to Events
    void OnEnable()
    {
        AdvanceCursor.OnLockStateChanged += OnCursorLockStateChanged;
        AdvanceCursor.OnVisibleChanged += OnCursorVisibleChanged;
        AdvanceCursor.OnTextureChanged += OnCursorTextureChange;
    }

    //Un-Subscribe to Events
    void OnDisable()
    {
        AdvanceCursor.OnLockStateChanged -= OnCursorLockStateChanged;
        AdvanceCursor.OnVisibleChanged -= OnCursorVisibleChanged;
        AdvanceCursor.OnTextureChanged -= OnCursorTextureChange;
    }

    void OnCursorLockStateChanged(CursorLockMode lockMode)
    {
        Debug.Log("Cursor State changed to: " + lockMode.ToString());
    }

    void OnCursorVisibleChanged(bool visible)
    {
        Debug.Log("Cursor Visibility is now: " + visible);
    }

    void OnCursorTextureChange(Texture2D texture, Vector2 hotspot, CursorMode cursorMode)
    {
        Debug.Log("Cursor Texture Changed!");
    }
}


text: Q: Not able to access file in Google Cloud Storage using Cloud Vision API I am currently trying to read a pdf file that I have stored in my Google Cloud Storage bucket. I have finished writing my code using the Google Cloud Vision API to read pdf files, but for some reason when I try to access the file that I have stored, I receive an error in my code saying that permission was denied to the file. How can I fix this, and if needed what code should I include to fix this?


text:
Q: How can I define default imports for Stylus in nuxt.js I import various helpers (mixins, vars, functions) into my component automatically to ensure they're always available to me and my team.
Currently I use the vue-cli webpack template and to import these helpers I set the stylus import option within the webpack.base.js config as shown below;
stylus: { import: ['~stylus/common.styl'] }

I've not been able to figure out how to do this with nuxt.js, I raised an issue about this and was told to use the build extend method.
This didn't work as I then received errors from webpack itself;
WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.

So with the changes brought in with v2.2.0 of webpack, how can I apply my stylus options?

A: Webpack 2 changed the syntax slightly. Instead of having a stylus key in the top level Webpack config, you have an options key under your stylus-loader configuration. So you should use something like:
...
{
  loader: 'stylus-loader',
  options: {
    import: ['~stylus/common.styl']
  }
}
...

Here's a solution for an identical issue with a different loader.


text:
Q: extract text from string data using SQL (with handing null values) I have issue with extracting text from string data using T-SQL. I have following data and text that I would like to extract (value between second and third underscore:
sss_ss_d_a -> d
aaa_dd_b -> b
aaa_aa -> NULL

I know that there is a lot of similar topics, but I have problem especially with handling NULLs and situation when there are no delimiter after desired value
Thank you very much for your help, regards

A: Try it like this:
Some sample data in a declared table
DECLARE @tbl TABLE(YourString VARCHAR(100));
INSERT INTO @tbl VALUES('sss_ss_d_a'),('aaa_dd_b'),('aaa_aa');

--The query
SELECT t.YourString
      ,CAST(CONCAT('<x>',REPLACE(t.YourString,'_','</x><x>'),'</x>') AS XML).value('/x[3]/text()[1]','nvarchar(max)')
FROM @tbl t;

The idea in short:

*

*We replace the underscores with XML tags thus transforming the string to castable XML.

*We use XQuery within .value to pick the third element.

Starting with v2016 the recommended approach uses JSON instead
(hint: we use "2" instead of "3" as JSON is zero-based).
      ,JSON_VALUE(CONCAT('["',REPLACE(t.YourString,'_','","'),'"]'),'$[2]')

The idea is roughly the same.
General hint: Both approaches might need escaping forbidden characters, such as < or & in XML or " in JSON. But this is easy...


text:
Q: Cutting Recipes exercise on CodeChef The following is my solution to a problem on codechef.
I am getting the correct output on my computer but not on codechef.
I couldn't find the mistake in my code.
The problem is to divide an array by the GCD of its elements and print it.
I wrote the following code :
#include<stdio.h>

int main(void)
{
  int t,n;
  scanf("%d",&t);

  while(t--)
  {
    scanf("%d",&n);
    int a[n],i,divisor,curr,r;

    for(i=0;i<n;i++)
    {
      scanf("%d",&a[i]);
    }

    divisor = a[0];
    for(i=1;i<n;i++)
    {
      curr = a[i];
      if(curr<divisor)
      {
        divisor = curr;
      }
    }

    for(i=0;i<n;i++)
    {
      r = a[i]%divisor;
      if(r != 0){
        divisor = 1;
        break;
      }
    }

    for(i=0;i<n-1;i++)
    {
      printf("%d ",a[i]/divisor);
    }

    printf("%d\n",a[n-1]/divisor);

  }

  return 0;
}

*

*t is the number of test cases.

*n is the length of the array.

*a[n] is the array.

*divisor is the GCD of all the elements in the array.

*curr is the current number tested.

*r is the remainder.

Sample Input
3
2 4 4
3 2 3 4
4 3 15 9 6

Sample Output
1 1
2 3 4
1 5 3 2

A: You were on the right track thinking it was an exercise involving CGD ( greatest common divisor ).
However you misunderstand on how to calculate the GCD.
it is rarely the smallest element of an array .
For example:
15, 6, 9

The smallest element is 6 and is not a common divisor of the other element ( and would have chosen 1 as a divisor in your case ), but the gcd in this case is 3
You could start by reading some information about calculating the CGD of a pair of element. And one example implementation.
Then try to figure out how to calculate the GCD of all the element of an array.
These hints could help


text:
Q: ngx-translate/multi-http-loader version 9 works in app module but not in others I use the new release 9.0, it works perfectly in my app module
export function HttpLoaderFactory(httpBackend: HttpBackend) { return new MultiTranslateHttpLoader(httpBackend, ['/assets/i18n/core/']); }
and
TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpBackend] } })
but when declare in another module
`
export function HttpLoaderFactory(httpBackend: HttpBackend) {
  return new MultiTranslateHttpLoader(httpBackend,
    ['/assets/i18n/core/', 'assets/i18n/home/']);
}

and
TranslateModule.forChild({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpBackend]
      }
    })

It doesn't work.


text:
Q: I found strange data reshaping method in MATLAB doc... Help me My goal is to build forecasting model with RNN.
I'm stuck at reshaping time series data.

There were some methods I could not figure out.
Time series forecasting using MATLAB
Time series forecasting using python
If you take a look at this example in MATLAB documentation, the target is 1-step shifted value.
for n = 1:numel(dataTrain)
    X = dataTrain{n};
    XTrain{n} = X(:,1:end-1);
    TTrain{n} = X(:,2:end);
end

Also, in the second code, target is just shifted values.
Yt = data[None,initLen+1:trainLen+1]

What is this method called? I would be glad to know any documentations about these reshaping methods.
Thanks.
After reading a lot of papers and internet blogs, I figured out that most of them uses sliding window approach.

*

*Sliding window (Tumbling window/Hopping window)
Sliding window


text:
Q: Font awesome translation or transform when click by user Good day! I'm trying to make a fixed floating action button with Font Awesome 5 that when a user clicks on the large button it will transform or translate the Font Awesome into another Font Awesome logo.
Here's the fiddle of https://jsfiddle.net/4eLq3dj0/ that has what I've tried so far. I also wanted it to spin around the bottom so I used this other thread.
HTML
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Document</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet">
        <link rel="stylesheet" href="">

            <button href="#" class="floating-btn">

            </button>

CSS
.floating-btn{
            width: 80px;
            height: 80px;
            background: #f5af09;
            display: flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            border-radius: 50%;
            color: #ffffff;
            font-size: 40px;
            box-shadow: 2px 2px 5px (0,0,0,0.25);
            position: fixed;
            right: 20px;
            bottom: 20px;
            transition: background 0.25s;
            outline: blue;
            border: none;
            cursor: pointer;

        }
         .button .icons {
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 2.3rem 0 0;
            width: 1.25rem;
            height: 2.6rem;
        }

        .button .icons i {
            position: absolute;
            top: 5;
            left: 5;
            display: block;
        }

        .floating-btn:active{
            background:#007D63;
        }

         .button .icons .icon-hover {
            transition: opacity 0.3s, transform 0.3s;
            transform: rotate(-180deg) scale(0.5);
            opacity: 0;
        }

        .button:active {
            transform: scale(1.2);
            box-shadow: 20px 15px rgba(0, 0, 0, 0.15);
        }

        .button:active .icon-hover {
            transform: rotate(0deg) scale(1);
            opacity: 1;
        }

        .button:active .icon-default {
            transform: rotate(180deg) scale(0.5);
            opacity: 0;
        }

A: Is this what you're trying to achieve? Hover:

.floating-btn {
  width: 80px;
  height: 80px;
  background: #f5af09;
  text-decoration: none;
  border-radius: 50%;
  color: #ffffff;
  font-size: 40px;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.25);
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  right: 20px;
  bottom: 20px;
  transition: background-color 0.25s ease-out;
  border: none;
  cursor: pointer;
}

.floating-btn:hover {
  background-color: red;
}

.floating-btn i {
  transition: transform 0.25s cubic-bezier(.4, 0, .2, 1);
}

.floating-btn:hover i {
  transform: rotate(45deg);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet" />

    <button href="#" class="floating-btn">

    </button>

Click:

document.querySelector('.floating-btn').addEventListener('click', function(e) {
  e.target.closest('button').classList.toggle('clicked');
})
.floating-btn {
  width: 80px;
  height: 80px;
  background: #f5af09;
  text-decoration: none;
  border-radius: 50%;
  color: #ffffff;
  font-size: 40px;
  box-shadow: 0 1px 3px 0 rgba(0,0,0,.2), 0 1px 1px 0 rgba(0,0,0,.14), 0 2px 1px -1px rgba(0,0,0,.12);
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  right: 20px;
  bottom: 20px;
  transition: background-color 0.25s ease-out, box-shadow 0.25s ease-out;
  border: none;
  cursor: pointer;
  outline: none;
}
.floating-btn:hover {
  box-shadow: 0 4px 5px -2px rgba(0,0,0,.2), 0 7px 10px 1px rgba(0,0,0,.14), 0 2px 16px 1px rgba(0,0,0,.12);
}

.floating-btn.clicked {
  background-color: red;
}

.floating-btn i {
  transition: transform 0.25s cubic-bezier(.4, 0, .2, 1);
}

.floating-btn.clicked i {
  transform: rotate(315deg);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet" />

    <button href="#" class="floating-btn">

    </button>

A:

.floating-btn {
  width: 80px;
  height: 80px;
  background: #f5af09;
  display: flex;
  align-items: center;
  justify-content: center;
  text-decoration: none;
  border-radius: 50%;
  color: #ffffff;
  font-size: 40px;
  box-shadow: 2px 2px 5px (0, 0, 0, 0.25);
  position: fixed;
  right: 20px;
  bottom: 20px;
  transition: background 0.25s;
  outline: blue;
  border: none;
  cursor: pointer;
}

.floating-btn i {
  position: absolute;
  top: 5;
  left: 5;
  display: block;
}

.floating-btn:active {
  background: #007D63;
}

.floating-btn .icon-hover {
  transition: opacity 0.3s, transform 0.3s;
  transform: rotate(-180deg) scale(0.5);
  opacity: 0;
}

.floating-btn:active {
  transform: scale(1.2);
  box-shadow: 20px 15px rgba(0, 0, 0, 0.15);
}

.floating-btn:active .icon-hover {
  transform: rotate(0deg) scale(1);
  opacity: 1;
}

.floating-btn:active .icon-default {
  transform: rotate(180deg) scale(0.5);
  opacity: 0;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet">
  <link rel="stylesheet" href="">

      <button href="#" class="floating-btn">

      </button>


text:
Q: Compiler error when using thrust placeholders with the ternary operator ?: I am using Thrust 1.8 and I get two compiler errors when I try to compile the below code :
#include <thrust/device_vector.h>
#include <thrust/functional.h>

int main(int argc, char* argv[])
{
    thrust::device_vector<bool> condition(100);
    thrust::device_vector<int> input(100);
    thrust::device_vector<float> result(100);
    float mean = 10.4f;

    thrust::transform(condition.begin(),condition.end(),input.begin(),result.begin(), ( (thrust::placeholders::_1 ) ? ( thrust::placeholders::_2) : (mean) ) );
}

When I try to compile, I get the following compiler time errors :
(for placeholders::_1)

Error : Expression must be of  bool type (or convertible to bool)

(for placeholders::_2)

Error : operand types are incompatible ("const thrust::detail::functional::actor < thrust::detail::functional::argument<1U>>" and "float")

How to correct this?

A: You cannot use the placeholders like you tried to, i.e. in combination with a ternary operator.
Instead, you could create your own functor:
struct my_fun : public thrust::binary_function<bool,float,float>
{
   float mean;
   my_fun(float mean) : mean(mean) {}
   __host__ __device__
   float operator()(bool condition, float input) const
   {
        float result = mean;
        if (condition)
        {
             result = input;
        }
        return result;
    }
};

...

thrust::transform(condition.begin(),
                  condition.end(),
                  input.begin(),
                  result.begin(),
                  my_fun(mean));


text:
Q: How to make a contour/error surface plot of 3d array? My script calculates the location error using a set of the equation for different values of x and y and stores the output into an empty array t_error. However, there are two issues that need to be resolved:
1: How to store the output in a 20_by_20 matrix instead of a 400_by_1 dimension.
2: How to make a contour plot (error surface) using x, y, and out_put parameter that is t_error in our case.
The sample script is as below:
**import pandas as pd
import numpy as np
import math
ev_loc= pd.read_csv("test_grid.txt", sep='\t',header=None)
x=np.array(ev_loc[1])
y=np.array(ev_loc[0])
v=3.5
t_error=[]
for s in x:
    for t in y:
        for i, j, k in [[73.9,33.1, 1.268571], [73.5,33.1, 1.268571], [73.4,33.1, 2.854286], [73.7,33.2, 0.317143],[73.7,33.0, 0.317143]]:
            u=((np.sqrt((t-j)**2 + (s-i)**2)/v)*111 - k)
            v=u*u
            t_error.append(float(v))
df_hr = pd.DataFrame(t_error)
numbers = np.array(df_hr)
window_size = 5
i = 0
moving_averages = []
while i < len(numbers) - window_size + 1:
    this_window = numbers[i : i + window_size]

    window_average = sum(this_window)
    moving_averages.append(window_average)
    i += 5
Error = pd.DataFrame(moving_averages)
Error.to_csv('test_total_error.csv')
print(Error)**

The data of test_grid.txt is as below

A: x1=np.linspace(73,75,num=41)
y1=np.linspace(33,35,num=41)
v=3.5
t_error=[]

for i, j, k in [[71.91500,33.82850, 57.2], [72.32200,33.16267, 38.28], [72.57900, 33.61317, 37.48], [73.44883, 33.83300, 27.8], [71.52967,33.15267, 58.8],
         [73.27017,33.65167, 18.44], [73.14017, 33.75200, 29.97], [72.46550,32.63183, 39.98], [73.22900, 32.99867, 14.77], [72.67167, 31.92100, 48.71],
         [71.91817, 32.53983, 54.73],[71.92333,33.04400, 49.67],[71.74417,32.79617, 57.39]]:
     u=((np.sqrt((y1-j)**2 + (x1-i)**2)/v)*111 - k)
     c=np.sum(u)
     t_error.append(c)
plt.plot(t_error)
plt.show()

What is the error suppose to show?


text:
Q: Charts.js polar area scales When Charts.js (Version: 2.1.3) renders my polar area charts for low data values the scale is drawn with fractional values:
Example polar area chart
The fractions do not make sense in the context of my data (student numbers). I would rather display a scale of whole numbers, or no scale. I have tried to change the chart options, looked at and tested various examples, searched for answers on this site and elsewhere, but no success yet. Any advice please?
Example of my code:
    var ML_Chart_obj = new Chart(ctx,
{
    type: "polarArea",
    data: {
      datasets: [{
          data: [0,1,0],
          backgroundColor: [
              "rgba(060,186,084,0.6)"
              ,"rgba(244,194,013,0.6)"
              ,"rgba(219,050,054,0.6)"
          ],
          label: ""
      }],
      labels: [
          "Active, on target"
          ,"Unspecified start or end date"
          ,"Active, at risk"
      ]
    },
    options: {
      scales: {
         xAxes: [{
         display:false
         }]
      },
      legend: {
        display: false
      }
    }
});

A: A little too late, but this is how you do it.
options{
    scale: {
        ticks: {
            stepSize: 1
        }
    }
}


text:
Q: Show all subcategories of current parent caregory in sidebar navigation in MAGENTO Trying to build sidebar category structure in Magento so that all children for an active category show when clicked. Using below as sample, when you go into main catalog only Main Cats appear.  Then when clicking any Sub Cat the children for that respective category appear and so on.
For example
Main Cat 1
    Sub Cat 1
        Sub/Sub 1
        Sub/Sub 1
        Sub/Sub 1
    Sub Cat 1
    Sub Cat 1
Main Cat 2
Main Cat 3

Here's the current code I have, but once you get to the last category, only the Main Cats show (in other words, if you click on Sub/Sub, the menu closes and shows only the Main Cats).

<?php echo $this->__('Products') ?>

<?php foreach ($store_cats as $cat) {
    if ($cat->getName() == $current_cat) {
        echo '
getCategoryUrl($cat).'">'.$cat->getName()."
";
        foreach ($obj->getCurrentChildCategories() as $subcat) {
            echo '
getCategoryUrl($subcat).'">'.$subcat->getName()."
";
        }
        echo "

";
    } else {
        echo '
getCategoryUrl($cat).'">'.$cat->getName()."
";
    }
} ?>

             <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('holiday-nav-links')->toHtml() ?>

             <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('about-us-nav-links')->toHtml() ?>

Any help is much appreciated.  Thank you in advance for the help!

A: <?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
<?php if (count($_categories) > 0): ?>

        <?php foreach($_categories as $_category): ?>

                <a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
                    <?php echo $_category->getName() ?>

                <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
                <?php $_subcategories = $_category->getChildrenCategories() ?>
                <?php if (count($_subcategories) > 0): ?>

                        <?php foreach($_subcategories as $_subcategory): ?>

                                <a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
                                    <?php echo $_subcategory->getName() ?>

                        <?php endforeach; ?>

                <?php endif; ?>

        <?php endforeach; ?>

<?php endif; ?>

Please check this link http://fishpig.co.uk/magento/tutorials/display-categories-and-subcategories-in-magento/
hope this help you

A: Had to do this very thing a few days back . get my whole function, may include some unnecessary html parts though. Shows 2nd level categories level onwards (for 3rd level category view as well)
public function getCatTree()
 {
        $treeHtml = '';
        $_helper = Mage::helper('catalog/category');
        $_categories = $_helper->getStoreCategories();
        $category = Mage::registry('current_category');

        $level = $category->getLevel();
        switch($level)
        {
            case 4 :
                    $level3Cat = $category->getParentCategory();
                    $level2Cat = $level3Cat->getParentCategory();
                    break;

            case 3 :
                    $level2Cat = $category->getParentCategory();
                    break;

            case 2 :
                    $level2Cat = $category;
                    break;

            default :
                    $level2Cat = null;
                    break;
        }

        //get the level 2 category ID
        $categoryId = $level2Cat->getId();

        if (count($_categories) > 0)
        {
            foreach ($_categories as $_category)
            {
                //match with the level 2 category, then list all its children
                if ($_category->getId() == $categoryId)
                {
                    $_category = Mage::getModel('catalog/category')->load($_category->getId());
                    $_catChildrens = $_category->getAllChildren();

                    foreach(explode(',',$_catChildrens) as $index=>$child)
                    {
                            $cat = Mage::getModel('catalog/category')->load($child);
if($cat->getLevel() == 3 && $cat->getIsActive())
                            {
                                $isParent = ($cat->hasChildren()) ? 'parent' : '';
                                $treeHtml .= '
getLevel().' '.$isParent.'">'.
                                            'getUrl().'">'.
                                              $cat->getName().
                                                '';

                                if($cat->hasChildren())
                                {
                                    $treeHtml .= '

';
                                    foreach($cat->getChildrenCategories() as $indx=>$_subcategory)
                                    {
                                        if($_subcategory->getIsActive())
                                        {
                                            $cat4 = Mage::getModel('catalog/category')->load($indx);
                                            $treeHtml .= '
getLevel().'">'.
                                            'getUrl().'">'.
                                              $cat4->getName().
                                                '
';

                                        }
                                    }
                                    $treeHtml .= '

';
                                }
                                $treeHtml .= '
';
                            }

                    }
                    return $treeHtml;
 }
            }
        }

    }


text:
Q: use activerecord to retrieve virtual attributes when using select() with includes() and where() I'm having trouble retrieving virtual attributes when making database queries.  The following works as expected:
s = Story.includes(:scenes).select("stories.*, 3 as testval")
s.first.title
=> "My Story"
s.first.testval
=> 3

But when I put in a where clause, it stops working:
s = Story.includes(:scenes).select("stories.*, 3 as testval").where("scenes.id < ?",1000).references(:scenes)
s.first.title
=> "My Story"
s.first.testval
NoMethodError: undefined method `testval' for #<Story:0x007fcd6b93eb68>

I'm guessing the issue is that ActiveRecord doesn't know that 'testval' should belong to 'stories' instead of 'scenes', but I'm not sure.  Does anyone know how to resolve this?

A: Sorry to be the bearer of bad news but you can't do a custom select and eager load as references/eager_load overrides the select with a bunch of t%d_r%d.
You'll need to do approach with a different ActiveRecord strategy if you need virtual attributes.


text:
Q: Windows 10 add custom fonts to command line I'm trying to add fonts to the windows command line so the Ubuntu terminal can use the pre-patched Meslo LG installed from the powerline fonts github page (see below) (so vim-airline won't have any missing special characters).
https://github.com/powerline/fonts
I've followed the tutorial here:
https://www.techrepublic.com/blog/windows-and-office/quick-tip-add-fonts-to-the-command-prompt/
I've installed the fonts successfully, so I can use the font in word.
I've tried different names for the string value and restarted several times but nothing seems to work.
I've look around online, every source offers the same advice for going through the registry editor.
I'm not sure what to do from here and I'd really appreciate some advice.
I'd also really appreciate some insight into how the registry uses the string value to match with the ttf.
EDIT 1:
Windows has a linux subsystem which you can run bash or any other terminal emulator on. In Linux you could add whatever type of font you wanted either through the CLI or GUI install.
I wanted to install Meslo LG S for powerline (the vim plugin that gives you a status bar) since patched fonts are needed that support the special characters.
As it turns out, when it comes to fonts, Windows doesn't care what you've specified. Since the terminal emulator is built on top of the cmd executable, it has the same limitations for fonts.
Rather than just moving to some other terminal emulator, I wanted to solve the problem so other people who're having the same issue with ubuntu terminal for windows 10 could get some help.
As it turns out, Meslo is not a monospace font, so it can't be used in cmd.
Knowing this, I simply chose another patched monospace font and everything works fine.
I haven't answered my question yet because I thought maybe someone with a bit more experience with MS-DOS could show an alternative.


text:
Q: Generating permutations of a 10-element vector with 8 zeros and 2 ones in R I'm generating 10-element vectors of 0s and 1s and varying the possible number of 1s from 2 to 9.
For example
2 values = 1
1000000010

3 values = 1
1010100000

EDIT: I want to efficiently generate all possible combinations.
I have a crude way of doing this but I'm guessing there is a simpler way to achieve this using some sort of permutation function.
My way:
Using the sample function in R:  I start with a vector of all zeros and draw 2 random numbers from 1 to 10 without replacement and uses those as indices of elements in the vector to change to 1.  I do this a lot of times then toss our the duplicates.
mat <- matrix(data = 0,nrow = 1000,ncol = 10) #matrix to hold output
vect <- rep(NA, 1000)
v0 <- rep(0,10)                              #initial vector of all 0s
for(i in 1:dim(mat)[1]){
  mat[i, sample(1:10, 2)] <- 1

  vect[i] <- paste(mat[i,], collapse = "")   #collapse vector to a string
}

mat[duplicated(vect) !=T,]                       #remove duplicates

This is a round about way to do it but gets the job done.

A: To generate all permutations with 2 ones in a 10 element vector, use combn(10,2) to enumerate all possible position:
t(apply(combn(10,2),2,function(x){ tmp<-rep(0,10); tmp[x]<-1; return(tmp) }))

This returns 45 different permutations same result as the OP's code using sampling but more efficient.


text:
Q: Topological proof on discrete topology where $X$ is infinite How must I prove this problem?
Let $X$ be an infinite set and let $T$ a topology in $X$ in which all infinite subsets of $X$ are open.
Prove: $T$ is a discrete topology in $X$.

A: HINT: Since $X$ is infinite, there is an infinite $A\subseteq X$ such that $X\setminus A$ is also infinite. For convenience let $B=X\setminus A$. For each $x\in A$ consider the open sets $A$ and $\{x\}\cup B$. Do something very similar to handle the points of $B$.


text:
Q: Magento 1.9: Newsletter subscribe checkbox not working I have installed magento 1.9 and have newsletter subscribe checkbox,
whenever i check it and submit success message shows but again checkbox is unchecked similarly for the unsubscribe case.
I there any solution to this problem.
Enabled the Mail chimp extension, which is working fine, but only checkbox is not working as expected.


text:
Q: Replace values in array using mask of different dimension I read this answer and wondered if this can be used to replace nested arrays.
So I tried:
import numpy as np

frm = [[[1,2], [2,3]], [[3,4], [4,5]], [[5,6], [6,7]]]
mask = [[False, True], [False, True], [True, False]]
repl = [0,0]
# convert frm to a numpy array:
frm = np.array(frm)
# create a copy of frm so you don't modify original array:
to = frm.copy()

# mask to, and insert your replacement values:
to[mask] = repl

print(to)

However I get the error IndexError: boolean index did not match indexed array along dimension 0; dimension is 3 but corresponding boolean dimension is 2
My goal here is to replace a nested array with another array. E.g. I want this value [2,3] in the first column to be replaced by this [0,0]

A: Try this:
to[np.newaxis, mask] = repl

or you convert the mask and the values to be replaced to an array. Then it is also working.
frm = [[[1,2], [2,3]], [[3,4], [4,5]], [[5,6], [6,7]]]
mask = np.array([[False, True], [False, True], [True, False]])
repl = np.array([0,0])
# convert frm to a numpy array:
frm = np.array(frm)
# create a copy of frm so you don't modify original array:
to = frm.copy()

# mask to, and insert your replacement values:
to[mask] = repl

print(to)

Output:
[[[1 2]
  [0 0]]

 [[3 4]
  [0 0]]

 [[0 0]
  [6 7]]]


text:
Q: Возвращение простого значения в функциях Python Есть ли разница в выводе простого значения функции между этими первой и второй реализациями? Для чего создавать переменную как в первом случае, если можно это все сократить?
def get_formatted_name(first_name, last_name):
    full_name = f"{first_name} {last_name}"
    return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

def get_formatted_name(first_name, last_name):
    full_name = (f"{first_name} {last_name}")
    print(full_name.title())

get_formatted_name('jimi', 'hendrix')

A: Если вы ничего не планируете больше делать с результатом, который считает и возвращает функция, то разницы нет. Но вообще возвращать результат из функции, а не печатать его внутри - лучше сразу по нескольким параметрам:

*

*функцию, возвращающую значение, проще покрыть тестами

*если вы захотите потом значение не печатать, а выводить в файл, или передавать в другую функцию - у вас есть почти готовое решение, берёте результат функции и делаете с ним что хотите; а вот функцию, которая результат печатает, вам придётся переделывать

*в развитие предыдущего пункта - такие функции можно объединять в библиотеки, составлять их них как из кубиков программы, вы можете написать модуль с нужными функциями и далее подключать его в свои программы и вызывать нужные функции из него

Ну, всё это помимо того, что функция вообще-то у вас называется get_formatted_name, что предполагает, что она возвращает некое formatted_name, а если вы хотите что-то печатать в этой функции, то и называть её надо было соответственно.


text:
Q: Sqlite3 Python: How to do an efficient bulk update? I can do very efficient bulk inserts in Sqlite3 on Python (2.7) with this code:
cur.executemany("INSERT INTO " + tableName + " VALUES (?, ?, ?, ?);", data)

But I can't get updates to work efficiently. I thought it might be a problem of the database structure/indexing, but even on a test database with only one table of 100 rows, the update still takes about 2-3 seconds.
I've tried different code variations. The latest code I have is from this answer to a previous question about update and executemany, but it's just as slow for me as any other attempt I've made:
data = []
for s in sources:
    source_id = s['source_id']
    val = get_value(s['source_attr'])
    x=[val, source_id]
    data.append(x)
cur.executemany("UPDATE sources SET source_attr = ? WHERE source_id = ?", data)
con.commit()

How could I improve this code to do a big bulk update efficiently?

A: When inserting a record, the database just needs to write a row at the end of the table (unless you have something like UNIQUE constraints).
When updating a record, the database needs to find the row. This requires scanning through the entire table (for each command), unless you have an index on the search column:
CREATE INDEX whatever ON sources(source_id);

But if source_id is the primary key, you should just declare it as such (which creates an implicit index):
CREATE TABLE sources(
    source_id INTEGER PRIMARY KEY,
    source_attr TEXT,
    [...]
);


text:
Q: How to control pipeline failure based on severity of snyk vulnerabilities found? I'm developing a CI/CD pipeline with Gitlab, and am currently using snyk to run dependency security analysis.  It's working great, but I would like to now implement some logic to allow the pipeline to continue without failure through this step if the vulnerabilities found are under a given threshold.  For example, if there are a few medium severity vulnerabilities found and nothing else, allow this and don't fail the pipeline.  However if there are some medium severity vulnerabilities found and a few high severity vulnerabilities found as well, fail the pipeline due to these high severity vulnerabilities.
I'm using shared Gitlab runners so I'm watching everything run through the online UI.  I've looked into exit codes for the command I'm using (snyk test), but all I've seen is that if any vulnerability is found, the process exits with a "non-zero" exit code.  When I ran snyk test and it found 6 vulnerabilities, three high and three medium severity, the exit code returned with echo $? was 1 (shown below).
Here's a demonstration of the snyk test command and the exit code:
$ snyk test

...some vulnerabilities...

Tested 126 dependencies for known vulnerabilities, found 6 vulnerabilities, 32 vulnerable paths.

$ echo $?
1

And here's the snyk job defined in my .gitlab-ci.yml in case that's helpful:
# TODO Make stage success/failure based on vulnerability severity
snyk-dependency-analysis:
  image: awesomeaiden/custom_snyk
  stage: static_analysis
  only:
    changes:
      - boot-kotlin-svc/**/*
  before_script:
    - cd boot-kotlin-svc
    - export GRADLE_USER_HOME=`pwd`/.gradle
    - export SNYK_TOKEN=$secret_snyk_token
  after_script:
    - cd ..
  variables:
    SNYK_TOKEN: $secret_snyk_token
  script:
    - snyk test
  cache:
    key: "$CI_COMMIT_REF_NAME"
    policy: pull
    paths:
      - build
      - .gradle
  allow_failure: true

I would love to be able to get highest detected severity level and use it to fail or not fail the pipeline, but I don't see any examples of this online and don't really know if its even possible.

A: Answer solved, snyk support said you can use the severity threshold option when running the snyk command to ignore vulnerabilities below a certain threshold.
Snyk Support Answer:
We do indeed have exit codes, we use exit code 1 for when vulnerabilities are found, 2 for any other failure. You can also use it in conjunction with the --severity-threshold, if for example you only wanted to fail on high severity vulnerabilities.

A: You can add flag --severity-threshold=low|medium|high

With this flag, only vulnerabilities of provided level or higher will
  be reported

snyk test --all-sub-projects --severity-threshold=high

Also by default Snyk scans all possible configurations including those used by tests only. To exclude those dependencies you can use --configuration-matching flag. Here is example for Gradle projects:
snyk test --all-sub-projects --configuration-matching=^(?!test).*

this will exclude configurations like: testCompile, testCompileClasspath, testRuntimeClasspath, testImplementation, etc


text:
Q: What is the CidrIp in Security groups I am creating a self ingress rule in a security group. I have created a CloudFormation template for the security groups, but I couldn't understand what is the CidrIp that I need to give here:
"SelfIngress1": [
          {
            "IpProtocol" : "tcp",
            "FromPort"   : "7600",
            "ToPort"     : "7600",
            "CidrIp"     : "10.0.0.0/1"
          },

What is the CidrIp that I have to provide here? Do I have to get it from the subnet where the VPC associates?

A: From AWS::EC2::SecurityGroupIngress - AWS CloudFormation:

CidrIp
An IPv4 CIDR range.
For an overview of CIDR ranges, go to the Wikipedia Tutorial.

That field defines the IP address range (in CIDR notation) that is permitted to send inbound traffic through the security group.
Your security group is permitting inbound traffic on port 7200, but it also needs an IP address range, such as:

*

*0.0.0.0/0 means from the whole Internet

*11.22.33.44/32 means only from 11.22.33.44

*10.5.2.0/24 means only from 10.5.2.x (with anything as the last number)


text:
Q: Preloading has_many association with a subset of records I have a system that allows users to auction and bid on items. I have these models
Item (id, description)
User (id, name)
Bid (id, item_id, user_id, price)
Sale (id, item_id, seller_id, buyer_id)
class Item < ApplicationRecord
  has_many :bids
end

class User < ApplicationRecord
  has_many :bids
end

class Bid < ApplicationRecord
  belongs_to :user
  belongs_to :item
end

class Sale < ApplicationRecord
  belongs_to :seller, foreign_key: seller_id, class_name: 'User'
  belongs_to :buyer, foreign_key: :buyer_id, class_name: 'User
  belongs_to :item
  has_many :bids, through :item
end

I am trying to make a page that lists out all the recent sales, and for each sale, lists out the bidding history of the eventual buyer.
So for example:
class SalesController < ApplicationRecord
  def index
    @sales = Sale.all.includes(:item, :bids)
  end
end

index.html.erb:
<% @sales.each do |sale| %>
  <%= sale.item.description %>

previous bids

   <% sale.bids.select { |bid| bid.user_id == sale.buyer_id }.each do |bid| %>
     <%= bid.price %>
   <% end %>
<% end %>

This works fine, but I'm having to preload all of the bids in the controller. Is there a way to only include the required subset? I feel like It should be possible to add an association to Sale such as has_many :buyer_previous_bids, -> (??), class_name: 'Bid' that can be preloaded Sale.includes(:buyer_previous_bids)

A: I think due the relations you have between your models, and without adding anything else you can get access to both bids and items, INNER JOINing bids with sales through their user_id and buyer_id respectively, and to items through their primary/foreign keys:
Sale.joins("
  INNER JOIN bids b ON b.user_id = sales.buyer_id
  INNER JOIN items i ON i.id = b.item_id
")


text:
Q: Error installing packages using conda command I have Python 3.10 and I installed Anaconda 3 today. I would like to install packages by Anaconda prompt, and I do the following for example:
conda install fiona

However, the following error appears:
conda is not recognized as an internal command
How to adjust this?
If I do pip install fiona, then it works.
What could be this error of not working the command conda. My system is Windows.

A: You have to add conda to your environment path. Otherwise your terminal/commmand prompt won't recognize the conda command straight away. You can check how to set environment variables and save them in your operating system here.

A: You need to add Anaconda to PATH.
In my case,  anaconda installed into C:\Anaconda3. I added  C:\Anaconda3 and  C:\Anaconda3\Scripts\ to my path variable.
Set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\


text:
Q: How to link a bank account to user profile in my website and show his transaction history In our website  website  a user will be able to link his bank account via logging in  to his bank account .and then our website will show him his all bank details and transaction history like how much he debit/credit and when he done these transactions.
so my problem is that I don't know how can I do this. I know there will be some third party resources so want to know some of these.


text:
Q: Why do we declare string, number, boolean, void and etc in angular2? I am confuse why do programmers declaring class in individual scope or something.
Example
result: boolean = false
public generateRand(x): void { }

This is also similar to
result = false
public generateRand(x) { }

** Same with the other declarations.
What's the reason behind those declaration? Is it the proper practice for programming or OOP(not sure of this since I don't have good grasp with it)?

A: The main reason is Static Typing
Javascript is a dynamically typed language. That is, the type of a variable is inferred at runtime. This can cause trouble to developers if they put a wrong type in a variable (Example: Putting a String where a Number should be)
TypeScript avoids these mistakes by defining the type of a variable in the code. So any attempts to put a different kind of value (Example, String in a Number) will result in an error. It also helps code completion because it knows what kind of value is being returned.
But these types exist only in the source. In the compiled JS, there is no trace of them.
Cheers!

A: You are right. You should not declare type in that particular example, as the type is already acknowledged via Type Inference
However, you will need to consider declaring type to variables with no initial value AND you explicitly want those variables to store a certain type of value:
isActive: boolean;
errorMessage: string;

It helps when:
1 .You want to detect type-related error sooner in the development cycle. For example, this code may yield unexpected error if you omit the type:
isActive: any;
...
this.isActive = "false";
...
if (!this.isActive) {
  // this will not happen
}

*You want to have better intellisense.

A: TypeScript is a superset of JavaScript - which means that TypeScript is JavaScript + more, where the more part is type annotations.
TypeScript has a .ts extension. You can compile TypeScript by running the following command:
tsc greeter.ts

Type annotations give you type safety. That is, when typescript is compiled the compiler looks at the static types, and ensures that the function or variable contract is valid at the time that the script is compiled.   Otherwise, the compiler complains when the types or contracts are incompatible.
Example
function greeter(person: string) {
    return "Hello, " + person;
}

var user = "Jane User";

document.body.innerHTML = greeter(user);

The function greeter expects a string as a parameter.  This code is synatically valid, and will happily compile with no compile-time errors.
On the other hand, if an incorrect type (such as an array) is passed:
function greeter(person: string) {
    return "Hello, " + person;
}

var user = [0, 1, 2];

document.body.innerHTML = greeter(user);

An error would be displayed when the script is compiled:
greeter.ts(7,26): Supplied parameters do not match any signature of call target


text:
Q: Find duplicate JARs in OSGi fat jar bundle I am currently working on a project that results in a fat JAR that runs in an OSGi context (Apache Felix). Is there a way/command to check if some of the jars that I have embedded into my fat jar are also available from other bundles and services, so that I can remove them (and thus make the fat jar smaller)?
The reason why I am building a fat jar is because I am using a different build system to build my jar. (I am using Scala & SBT, everything else is is built with Java & Gradle)

A: I do not know of any automated tools doing this, but Apache Felix has two tools that might help you find your duplicates:

*

*/system/console/depfinder

*/system/console/status-duplicate_exports
Especially, the second one should help you. It lists packages that are exported more than once and then it lists the bundles that export the those packages. If your bundle appears in this list, you know that another bundle exports packages, that are in your fat bundle.
But as with the depfinder, you will have to go through the list manually or write a little script to help you.

A: Another option: just have a look whether the JAR's you are currently including into your fat JAR are OSGi bundles (many IDE's tell that already in some project dependency view) and note down the header Bundle-SymbolicName.
Then you extract the same information from all bundles installed at the Felix runtime, e.g. using the Gogo shell:
lb -s

...or if you have a directory with bundles for the runtime and the bnd command (and you're on a Unix):
find <bundles-directory> -type f -iname "*.[jw]ar" -exec bnd --failok print --manifest {} \; 2>/dev/null | grep -F 'Bundle-SymbolicName'

Now you can compare those lists against the SymbolicName's that you have found in your fat JAR. Once you found a match, you should also verify that the version is OK.


text:
Q: Repository Pattern and Azure Table Storage(???) While doing the following simple example, I found the following difficulties
As the title says, I am intending to use the Repository pattern while I am storing data in the Azure table storage.now I have couple of classes, Repository.cs, IRepository.cs, DataContext.cs and the Controller.
During my reading I found  some info and been doing as follows.
IRepository.cs
public interface IRepository<T> where T: TableServiceEntity
{

    T GetById(int Id);

    IQueryable<T> GetAll();

}

and the DataContext.cs
public class DataContext<T>:TableServiceContext where T:TableServiceEntity
{

   public DataContext(CloudStorageAccount storageaccount, StorageCredentials credentials)
        : base(storageaccount.TableEndpoint.AbsoluteUri, credentials)
    {
       // _storageAccount = storageaccount;

       var  storageAccount =        CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(KEY_STORAGE));
        storageAccount.CreateCloudTableClient().CreateTableIfNotExist(tableName);

    }

   public IQueryable<T> DeviceTable
   {
       get { return CreateQuery<T>(tableName); }
   }

}

plus some part of the controller(I have already data in the table which I created before)
public class DeviceMeController : Controller
{

    private IRepository<Entity>_repository;

    public Controller() : this(new Repository<Entity>())
    {
    }
    public Controller(IRepository<Entity> repository)
    {
        _repository = repository;
    }
    public ActionResult Index()
    {
        var List = _repository.GetAll();

        return View(deviceList);
    }

and the the Implementation of the interface Reposistory.cs, here is where I have an error and got lost somewhere
 public class Repository<T>:IRepository<T> where T:TableServiceEntity
   {
  private  DataContext<T> _serviceContext;
    // here get tablename as pararameter;
    // so the Enities call this function
    public Repository()
    {

        // the same context for multiple tables ?
    }
    // perhaps it should take the table Name
    public void Add(T item)
    {

        _serviceContext.AddObject(TableName,item);
        _serviceContext.SaveChangesWithRetries();
    }
  public IQueryable<T> GetAll()
    {
       var results = from c in _serviceContext.Table
                      select c;

        return results;

Error is about the null reference, the debugger shows the variable results is null?
In the end I need to know few things.
what should I do in the Repository.cs   constructor? I believe the Datacontext.cs class has to be in a separate class ...
any Hint here

A: Hy,
first of all I presume you left out some code, because I don't see how you get your context in your repository. But supposing you do set it correctly, (injection?) taking into account the way you desinged your datacontext the repository doesn't need to know the table name because it is set in the following lines of code:
 public IQueryable<T> DeviceTable
 {
     get { return CreateQuery<T>(Constants.DeviceTableName); }
 }

So when you create a query based on the IQueryable DeviceTable, the table name is already set.
The thing is I don't see the need for your context class, especially as it can only bring over a single entity type (it is generic and based on an entity).
A basic layout of my Repository for Azure Table Storage is:
public abstract class CloudRepository<TEntity> : ICloudRepository<TEntity>
{
    private TableServiceContext _tableServiceContext;
    private string _tableName;

    public string TableName
    {
        get { return _tableName ?? ( _tableName = typeof(TEntity).Name.Replace("Entity", string.Empty).ToLower()); }
    }

    public CloudStorageAccount StorageAccount
    {
        get
        {
            return CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
        }
    }

    public CloudTableClient TableClient
    {
        get
        {
            CloudTableClient cloudTableClient = StorageAccount.CreateCloudTableClient();
            cloudTableClient.CreateTableIfNotExist(TableName);
            return cloudTableClient;
        }
    }

    public TableServiceContext ServiceContext
    {
        get
        {
            return _tableServiceContext ?? (_tableServiceContext = TableClient.GetDataServiceContext());
        }
    }

    public IEnumerable<TEntity> FindAll()
    {
        return ServiceContext.CreateQuery<TEntity>(TableName).ToList();
    }

}

Hope this helps you.


text:
Q: Implement WPF multilanguage interface I want to make my WPF window multilanguage.
I have already read this post. Instead of using resx file, I want that the translations are performed by an instance of my class that is the translation responsable because I use it also in other points of the application.
I thought to implement the Binding with a converter which receives the key value that has to be translated. I don't know if this is the best approach or if there are any better solution.
Any help is really appreciate! Thanks.

A: That is a good approach.
You can write a MarkupExtension to handle the translations.
use it like so:
<TextBlock Text="{MyNameSpace:Translate 'good night'}"/>

The MarkupExtension will be responsible to go to your class/service to translate
that string and return it.
That way you dont need to have unnecesary Bindings and Converters.

A: This is the solution I found:
public class TranslateMarkupExtension : MarkupExtension
{
    [ConstructorArgument("value1")]
    public string Value1 { get; set; }

    public TranslateMarkupExtension() { }

    public TranslateMarkupExtension(string value1)
    {
        Value1 = value1;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var rootObjectProvider = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
        var root = rootObjectProvider.RootObject;

        var translation = GetLangTranslator(root);

        return string.IsNullOrEmpty(translation) ? Value1 :translation;
    }

    private string GetLangTranslator(object root)
    {
        var properties = root.GetType().GetProperties();

        foreach (var property in properties)
        {
            if (typeof(MultiLanguage) == property.PropertyType)
            {
                var m = property.PropertyType.GetMethod("Translate");

                var propValue = property.GetValue(root);
                return m.Invoke(propValue, new object[] {Value1}) as string;
            }
        }

        return null;
    }
}

Now I have just to find how to update the UI when the language change runtime.


text:
Q: How to set the brand logo in Bootstrap 4 navbar to the left edge? I have a logo as shown below.

START

      ...

Bootstrap adds a piece of padding on the left resulting in the following offset from the edge.

Since our logo is a cut off circle, we want it to be placed precisely at the edge to create illusion of a real circle but sticking outside of the browser. I've tried to set a negative margin on the left side but it only moved the image, still retaining the weird edge as shown below.

What can I do about it?

A: You can use row instead of container-fluid. these two have opposite margins.
https://jsfiddle.net/gsb3ohd2/

START

      ...

A: Remove the left padding of .navbar-brand and .container-fluid.navbar-container(you don't want to override the styles of .container-fluid, so add a new class to it).
HTML

CSS
.container-fluid.navbar-container, .navbar-brand {
  padding-left: 0;
}

Working fiddle: https://jsfiddle.net/9t20dmLk/1/


text:
Q: Space remove from String #include<stdio.h>
#include<string.h>

int main(){
    char array[]="Arijit Saha Student";
    spaceremover(array);
    getch();
    return 1;
}

int spaceremover(char a[]){
    int i;
   // printf("L=%d",strlen(a));
    char final[strlen(a)+1];
    int count=0;
    for(i=0;i<strlen(a);i++)
    {
        if(a[i]!=' ')
            final[count]=a[i];
        count++;
    }
    final[count]='\0';
    int j=0;
    for(j=0;j<strlen(final);j++)
    printf("%c",final[j]);
    // printf("\n%s",final);
    return 1;
}

With this example code the output is Arijit.Saha, but my desired output is ArijitSahaStudent.
Why am I getting the wrong output?
Where the . is coming from?

A: The error is here:
if(a[i]!=' ')
    final[count]=a[i];
count++;

The count++ should be included in the if, so:
if(a[i]!=' ') {
    final[count]=a[i];
    count++;
}

Note: It is considered good programming practice to always use curly braces after if statements.

A: In the for loop you increase count even if a[i] == ' ' .
So when a[i] == ' ' you only increase count but doesn't set final[count] to anything.
I assume you ment to write:
if (a[i] != ' ')
{
    final[count] = a[i];
    count++;
}

A: You are not incrementing count correctly.  It needs to be in the if loop. This might be easier for you to see if things are indented correctly.
#include<stdio.h>
#include<string.h>

int main(){
  char array[]="Arijit Saha Student";
  spaceremover(array);
  return 1;
}

int spaceremover(char a[]){
  int i;
  // printf("L=%d",strlen(a));
  char final[strlen(a)+1];
  int count=0;
  for(i=0;i<strlen(a);i++)
  {
    if(a[i]!=' ')
      final[count++]=a[i];
  }
  final[count++]='\0';
  int j=0;
  for(j=0;j<strlen(final);j++)
    printf("%c",final[j]);
  // printf("\n%s",final);
  return 1;
}

A: In the loop, the count should increase if a[i] not equal to space
if(a[i]!=' ')
      final[count]=a[i];
count++;
if(a[i]!=' ')
final[count++]=a[i];
//count++;


text:
Q: How to Pass parameter to an unix shell script to run a job in an unix environment I am trying to run a .sh script which will basically trigger a  job , i am trying to pass parameter to the .sh file but i am getting error repeteadly .This sh will run a script and execute a batch that will produce some output and will keep in a file.
Below is the folder structure
JAVA=$APPSERVER/java/bin
BATCHPROGRAM=com.i21.framework.SystemBootstrap
APPNAME=BATCH_${REGION}
APPDIR=/apps/$APPNAME
#FRAMEWORKDIR=$APPDIR/Framework
BATCHDIR=$APPDIR/DNQLETTER
FRAMEWORKJARLOC=$APPDIR/lib
BATCHJARLOC=$BATCHDIR/lib

FRAMEWORKCONFIG=$APPDIR/config/
BATCHCONFIG=$BATCHDIR/config/

LOG=/logs21C/$APPNAME/DNQLETTER/
DATE_TIME_STAMP=`$DATE +%Y%m%d.log`;
LOGFILE="${LOG}/batch"_"$DATE_TIME_STAMP"

#--------------------------------------------------------------------
# Create the error file and the log file if they do not exist
#--------------------------------------------------------------------
$TOUCH $LOGFILE
$CHMOD 666 $LOGFILE  2>> /dev/null

This is the error i am getting
./ProcessBatch.sh DEV1 This i am trying using to pass the BATCH Region

I am getting below error
/bin/touch: cannot touch `/logs21C/BATCH_/DNQLETTER//batch_20170627.log': No such file or directory
./ProcessBatch.sh[80]: /logs21C/BATCH_/DNQLETTER//batch_20170627.log: cannot
create [No such file or directory]
/bin/ls: /apps/BATCH_/lib/*.jar: No such file or directory
/bin/ls: /apps/BATCH_/DNQLETTER/lib/*.jar: No such file or directory
/bin/ls: /apps/BATCH_/DNQLETTER/config//*.*: No such file or directory
/bin/ls: /apps/BATCH_/config//*.*: No such file or directory

A: I would remove the final slash from the definition of LOG, but this is not the reason of the error you are experiencing (it just might cause troubles later on). The reason for the error is:

*

*Your error message implies, that the directory /logs21C/BATCH_/DNQLETTER does not exist.

*We can also see that the variable REGION is empty.


text:
Q: Is it possible to move Steamwork Common Redistributables to external library? I have 2 computers that both of have Steam installed.
I am using an external HDD for a game library to make it easier.
Can I move Steamwork Common Redistributables like other games, so I don't need to update it twice every time there is new update?


text:
Q: Authorize Web Service Requests We have built numerous web services and hosted them on our internal servers and these will be used by our iPhone application. End users of the iPhone app need not sign into the application, they can just use the app without any credentials.
Whenever web services receive a request; I want to authorize that these requests are coming from iPhone app. How can i do this?
Thanks!

A: How safe do you want it to be ?
The dead simple and widely used technique is to require all webservice request include an ApiKey header. The server must then validate the ApiKey against a known list of allowed ApiKeys. If communication is done over SSL this is fairly safe (would require disassembly of the client code to find the key), on the other hand if communication is plain http, the ApiKey can be easily sniffed.


text:
Q: Checklist layout with a fixed part I'm trying to make the layout of a checklist, which has this type of row:

Where:

*

*A is a CheckBox (it's fixed size)

*B is a TextView (it should stretch all available space)

*C is a TextView (it should stretch all available space)

*D is a TextView (it's fixed size)

*E is the parent, the row of the list

This is my layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_vertical">
    <CheckBox android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <LinearLayout android:orientation="vertical"
    android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_weight="1"
        android:paddingRight="6dp"
        android:gravity="center_vertical">
        <TextView android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginLeft="6dp"
            android:gravity="center_vertical"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:singleLine="true" />
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6dp"
            android:gravity="center_vertical"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:singleLine="true" />
    </LinearLayout>
    <TextView android:layout_width="wrap_content"
    android:layout_height="60dp"
        android:layout_weight="2"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:gravity="center_vertical|right"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#2B78E4" />
</LinearLayout>

And I'm getting this result:

The first row has very long content on B and C, and so D is not appearing at all.
The second row has long content, but shorter than first's, and so D is shrinked.
The third row has short content, and D is displayed correctly.
How could I modify my layout so D is always displayed correctly, and B&C will be filling only the available space?

A: You should use RelativeLayout, as main container,
first put A, then put D, after them put B and C.
So your new layout would look like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:gravity="center_vertical">
    <CheckBox android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView android:id="@+id/textView" android:layout_alignParentRight="true"
        android:layout_width="wrap_content" android:layout_height="60dp"
        android:layout_marginLeft="6dp" android:layout_marginRight="6dp"
        android:gravity="center_vertical|right" android:layout_weight="2"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#2B78E4" />
    <TextView android:id="@+id/txt1"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_marginLeft="6dp" android:layout_marginTop="6dp"
        android:layout_toRightOf="@id/checkbox" android:layout_toLeftOf="@id/textView"
        android:gravity="center_vertical" android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView android:id="@+id/txt2" android:layout_below="@id/txt1"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_marginLeft="6dp" android:layout_marginTop="3dp"
        android:layout_toRightOf="@id/checkbox" android:layout_toLeftOf="@id/textView"
        android:gravity="center_vertical" android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>

You should of course change the ids of the checkbox and textview for your preference.
This way your output will look consistent in both landscape and portrait mode:
 and
Updated layout and screenshots (to match the provided output).

A: I have changes to your XML
Here it is
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
  <CheckBox
    android:id="@+id/ckb"
    android:gravity="center_vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true" />
  <RelativeLayout
    android:layout_centerInParent="true"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/ckb"
    android:layout_toLeftOf="@+id/txt">

    <LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="60dp"
      android:layout_weight="1"
      android:paddingRight="6dp"
      android:gravity="center_vertical"
      android:orientation="vertical">
      <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6dp"
        android:gravity="center_vertical"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:singleLine="true" />
      <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6dp"
        android:gravity="center_vertical"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:singleLine="true" />
    </LinearLayout>
  </RelativeLayout>
  <TextView
    android:id="@+id/txt"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_weight="2"
    android:layout_marginLeft="6dp"
    android:layout_marginRight="6dp"
    android:gravity="center_vertical"
    android:layout_alignParentRight="true"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="#2B78E4" />
</RelativeLayout>

A: Even though the above answer works I'd suggest to replace the LinearLayout and change the alignment of the 2 TextViews in the middle, since you are already in a RelativeLayout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="60dp">
    <CheckBox android:layout_alignParentLeft="true"
        android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:id="@+id/checkBox1" android:layout_centerVertical="true" />
    <TextView android:lines="1" android:id="@+id/textView1"
        android:text="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed  diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. "
        android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_toRightOf="@+id/checkBox1"
        android:layout_alignTop="@+id/checkBox1"
        android:layout_toLeftOf="@+id/textView3"
        android:layout_marginLeft="6dp" />
    <TextView android:id="@+id/textView2"
        android:text="Lorem ipsum dolor sit amet, consetetur sadip"
        android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:layout_below="@+id/textView1" android:layout_alignLeft="@+id/textView1"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:lines="1" android:layout_toLeftOf="@+id/textView3" />
    <TextView android:id="@+id/textView3" android:text="TextView"
        android:layout_height="match_parent" android:layout_width="wrap_content"
        android:layout_alignParentRight="true" android:gravity="center_vertical|right"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#2B78E4" android:layout_marginLeft="6dp" />

In general it's good practice to save the amount of Layouts, especiallay as this is a layout for your list items, but I think Romain Guy is better in explaining this here ;)


text:
Q: Restore Data From a Huge mysqldump File I have written a script to restore a huge mysqldump file in parallel
https://gist.github.com/arunp0/4c34caee2432a6f11b91b99dfd2c5ef3
Is it okay split the dump file in parts and restore in parallel?
Or If there is any suggestions for improvements to reduce time in restoring
Just to Explain How the script works
sed -n -e '/DROP TABLE/,/--/p'  "${restoreFile}" > "${tableMetaFile}"

Creates new sql file with DROP TABLE , CREATE TABLE Commands
then this file is restored (Not in parallel) - All the tables are created before restoring the data
  # Creates new file with data only for one table (TableName)
  grep -E "^INSERT INTO \`${TableName}\`" "${restoreFile}"  > "tmp/${TableName}.sql"

  # that file is split into as many chunks as the number of cpus
  split -n l/$(nproc) --additional-suffix=.sql "tmp/${TableName}.sql"  tmp/"${TableName}"/output.

 # This comamnd is used to restore the file
 pv -f tmp/meta/pre.sql "${item}" tmp/meta/post.sql | mysql --protocol=TCP --port "$PORT" --host "$HOST" -u "${USER}" -p"${PASSWORD}" -f "${DATABASE}"  &