text:
Q: A little help to achieve the desired pgfplot diagram I almost finished a diagram on pgfplot, but a few details are still missing. I hope some of you are willing to help me.
This is the almost completed diagram:
\documentclass{standalone}
\usepackage{pgfplots}
\usetikzlibrary{arrows.meta}
\pgfplotsset{compat=1.13}
\begin{document}
\centering
\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
title style={yshift=6ex},
grid=both,
xlabel=$Time~(T_n)$, ylabel=$States~(X_n)$,
xmin=0,xmax=20,
ymin=0,ymax=4,
axis line style={-Latex[round]},
ticklabel style={font=\footnotesize,fill=white},
extra x ticks={0},
extra x tick labels ={$t_0$},
xtick={1.2, 2.4, 3.6, 4.8, 6, 7.2, 8.4, 9.6, 10.8, 12, 13.2, 14.4, 15.6, 16.8, 18, 19.2},
xticklabels={$t_1$, $t_2$, $t_3$, $t_4$, $t_5$, $t_6$, $t_7$, $t_8$, $t_9$, $t_{10}$, $t_{11}$, $t_{12}$, $t_{13}$, $t_{14}$, $t_{15}$, $t_{16}$},
ytick={0.5, 1, 1.5, 2, 2.5, 3, 3.5},
yticklabels={$CCC$, $B$, $BB$, $BBB$, $A$, $AA$, $AAA$},
extra y ticks={0},
extra y tick labels={$D$},
yticklabel style={anchor=east},
xlabel style={at={(ticklabel* cs:1)},anchor=north west},
ylabel style={at={(ticklabel* cs:1)},anchor=south west},
width=11cm,
]
\end{axis}
\begin{axis}[
at={(0,-0.7cm)},
axis x line*=left, axis y line=none,
xticklabels={$T_0$, $T_1$, $T_2$, \scriptsize{$s$}, $T_3$, $T_4$, $T_5$, $T_6$, \scriptsize{$s$}\tiny{+}\scriptsize{$t$}, $T_7$},
xtick={0, 2.4, 4.8, 6, 8.4,  12, 13.2, 15.6, 16.8, 18},
axis line style={-Latex[round]},
ticklabel style={font=\footnotesize,fill=white},
xmin=0,xmax=20,
ymin=0,ymax=4,
ytick={0.5, 1, 1.5, 2, 2.5, 3, 3.5},
width=11cm,
]
\addplot[->,>={}] coordinates{
(0,2.855)
(2.4,2.855)

(2.4,1.855)
(4.8,1.855)

(4.8,1.355)
(8.4,1.355)

(8.4,0.855)
(12,0.855)

(12,2.355)
(13.2,2.355)

(13.2,2.355)
(15.6,2.355)

(15.6,3.355)
(18,3.355)

(18.1,1.355)
(20,1.355)

};
\draw [fill,black] (0.05,2.855) circle [radius=1.5pt];
\draw [fill,black] (2.4,1.855) circle [radius=1.5pt];
\draw [fill,black] (4.8,1.355) circle [radius=1.5pt];
\draw [fill,black] (8.4,0.855) circle [radius=1.5pt];
\draw [fill,black] (12,2.355) circle [radius=1.5pt];
\draw [fill,black] (13.2,2.355) circle [radius=1.5pt];
\draw [fill,black] (15.6,3.355) circle [radius=1.5pt];
\draw [fill,black] (18,1.355) circle [radius=1.5pt];
\end{axis}
\end{tikzpicture}
\end{document}

In this picture I added the few details I'm still missing:

It shouldn't be hard for someone used to pgfplots. Note that even something similar to the one suggested would be of great help.
Thanks!

A: As a starting point, a part of solution is as follows.
1- Add overbrace style to your tikzpicture environment:
\begin{tikzpicture}[
brc/.style args = {#1/#2}{decorate,
              decoration={brace, amplitude=5pt,
              raise=#1,#2},% for mirroring of brace
              thick}]

\begin{axis}[
axis lines=middle,
title style={yshift=6ex},
.
.
.

2- Drawing:
\draw [fill,black] (0.05,2.855)coordinate (X0) circle [radius=1.5pt] node[above right=0.2cm]{\tiny $X_0=A$};
\draw [-latex] (X0)--++(20:0.5);
\draw [fill,black] (2.4,1.855)coordinate (X1) circle [radius=1.5pt] node[above right=0.2cm]{\tiny $X_1=BB$};
\draw [-latex] (X1)--++(20:0.5);
\draw [fill,black] (4.8,1.355) circle [radius=1.5pt];
\draw [fill,black] (8.4,0.855) circle [radius=1.5pt];
\draw [fill,black] (12,2.355) circle [radius=1.5pt];
\draw [fill,black] (13.2,2.355) circle [radius=1.5pt];
\draw [fill,black] (15.6,3.355) circle [radius=1.5pt];
\draw [fill,black] (18,1.355) circle [radius=1.5pt];
\draw [dashed] (6,0)--(6,1.5);
\draw [red] (4.8,0.5)--(6,0.5);
\draw [brc=1mm/] (4.8,0.5)--node[above=3mm]{\tiny $=l$}(6,0.5);
%\draw[decorate,decoration={overbrace,amplitude=3pt,mirror}] (4.8,0.5) -- (6,0.5 );
\draw [blue] (6,0.5)--(8.4,0.5);
\draw [brc=1mm/] (6,0.5)--node[above=3mm]{\tiny $=u$}(8.4,0.5);

will produce:


text:
Q: Can one Observable() handle the Subscribe for two situations? I'm applying reactive programming to the Unity3D project.
Entering a character in InputField enables the button and disables it if there are no characters.
Can this logic be processed in one stream using UniRx.Observable?
inputID.OnValueChangedAsObservable()
            .Where(x => string.IsNullOrEmpty(x) == false)
            .Subscribe(_ => buttonLogin.gameObject.SetActive(true));

inputID.OnValueChangedAsObservable()
            .Where(x => string.IsNullOrEmpty(x) == true)
            .Subscribe(_ => buttonLogin.gameObject.SetActive(false));

Can combine these two logics into one logic?
Please reply. Thank you.

A: Yes, you can use the Map operator.
http://reactivex.io/documentation/operators/map.html
"transform the items emitted by an Observable by applying a function to each item"
Replace Where with Map, and inside the map operator, you'll be passed your x variable, and return the boolean from your IsNullOrEmpty check. That boolean will be passed in as a variable in your subscription which you can use directly in setActive.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XMLHttpRequest contains non-empty response but XMLHttpRequest.response is  I'm sending HTTP requests and receiving responses with the following code:
var xhr = new XMLHttpRequest()
var waiting = true
var sup = this
var userId = userInfo.userId
var userType = 'student'
if (userInfo.type == 2) {
    userType = 'professor'
}
xhr.onreadystatechange = function() {
    try {
        if (this.status == 200 && waiting) {
            waiting = false;
            var courses
            try {
                courses = JSON.parse(xhr.response)
            } catch (jerr) {
                courses = []
            }
            sup.courseArray = courses;
            console.log(sup.courseArray)
            sup.render()
        }
    } catch (err) {}
}
xhr.open('GET', 'http://localhost:8080/course/read/' + userType + 'Id/' + userId)
xhr.send()

As you can see, I'm only accessing response in the callback, so the server has responded and xhr has been initialized at that point. If I simply call console.log(xhr), I can clearly see response is a non-empty string:
response: "[{\"id\":1,\"professorId\":1,\"name\":\"java\",\"code\":\"CS1017\"}]"
However, if I call console.log(xhr.response), I get
<empty string>
Does anyone know why I'm seeing this discrepancy?

A: this.status == 200 will be true as soon as xhr.readyState == 2, but the request will not be completely fulfilled until xhr.readyState == 4; at readyState == 2 response will still be empty.
console.log(xhr) will eventually show the status at readyState == 4, but that's 2 readyStates later than when your code tries to access xhr.response.
You have to check that both status == 200 and readyState == 4 are true to be sure a complete response has arrived.

A: why not try using using JS native fetch instead
var waiting = true
var sup = this
var userId = userInfo.userId
var userType = 'student'
if(userInfo.type == 2) {
   userType = 'professor'
}

fetch('http://localhost:8080/course/read/' + userType + 'Id/' + userId)
.then(r => r.json())
.then((response) => {
    waiting = false;
   sup.courseArray = response;
   console.log(sup.courseArray);
   sup.render();
})
.catch((e) => {
     waiting = false;
     console.log(e);
});


text:
Q: python: unicode data is not equal to unicode data i has some json works like this.
>>> j = '{"a":5}'
>>> js = json.loads(j)
>>> for key in js:
...     key
...     type(key)
...     key is unicode('a')
...
u'a'
<type 'unicode'>
False

In my opinion last value of output should be true. Plese helpme to find my mistake.

A: Why are you using is here? You just want to compare:
key == unicode('a')

or even better:
key == u'a'


text:
Q: How to covert file byte code to file form data I have two folders from one folder i get the file and upload to another server
So when i get file from 1st folder i get a byte code of that file now i want same file to upload in second folder but the rest api of uploading is taking FormData as argument.
I tried this.
I am getting response type blob when downloading file
this.testservice.getfile().subscribe((res)=>{
     /*res is byte of file that i download*/
    let formData = new FromData();
    formData.append("name","abc.png")
    formData.append("files",res as any)
    this.testservice.uploadfile(formData).subscribe((res)=>{
        console.log("uploaded successfully)
    })
})

But why i get is file not found exception so please help me what i can do to convert this byte code to form-data image type

A: there appears to be a typo FormData() and not FromData() ?
Can you try again and see if the issue persists.


text:
Q: Java resultset displayed in reverse order I'm testing a very simple Java webapp doGet() method with the following code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
{
    try
    {
        Class.forName("oracle.jdbc.OracleDriver");
    }
    catch(ClassNotFoundException ex)
    {
            System.out.println(ex);
    }

    String sql_qrp="select * from HR.EMP_MGMT";

    try
    {
        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/XE","HR","HR");

        try(Statement stm=con.createStatement())
        {
            ResultSet rs=stm.executeQuery(sql_qrp);

            while(rs.next())
            {
                int emp_ID=rs.getInt("EMP_ID");
                String name=rs.getString("NAME");
                String address=rs.getString("ADDRESS");
                int tel=rs.getInt("TEL");
                String email=rs.getString("EMAIL");

                System.out.println(emp_ID+", "+name+", "+address+", "+tel+", "+email);
            }
        }
    }
    catch (SQLException ex) {
        Logger.getLogger(Add_Employee.class.getName()).log(Level.SEVERE, null, ex);
    }
}

It connects well to Oracle db and fetches all 3 rows from the table specified in the code, BUT IN REVERSE ORDER. I already tried to force FETCH_FORWARD with no success. So it fetched records like:
ID 3.,2.,1. and not ID 1., 2., 3.

A: Add
ORDER BY id ASC

to sql_qrp.


text:
Q: asp.net MVC Ajax call, suddenly get 404 (Not Found) My website is running unchanged for a few weeks now (running on Azure cloud),
suddenly, when calling a function on the server side from the view, i'm getting 404 (Not Found).
tried from 3 different PCs,
it looks like call is correct, i can't find what might be the issue.
View calling the function :
<script type="text/javascript">
    function Submit() {
        $("#divLoader").show();
        var pdata = new FormData();
        var files = $("#CSVFile").get(0).files;
        pdata.append('CSVFile', files[0]);
        $.ajax({
            url: "OrderWarehouse/Submit",
            type: "POST",
            data: pdata,
            processData: false,
            contentType: false,
            success: function (data) {
                // var input = $("#CSVFile");
                //input.replaceWith(input.val('').clone(true));
                $("#divLoader").hide();
                if (data.success == 0) {
                    swal("Error!", data.excep, "error").then((value) => { location.reload(); })

                }
                else {

                    swal("Success!", data.excep, "success").then((value) => { location.reload(); })
                }
            },
            error: function (data) {
                $("#divLoader").hide();
                swal("Error!", "Unknown error", "error").then((value) => { location.reload(); })
            }
        });
    }
</script>

Here is the exception i'm getting:

A: I Published my website to Azure again , Now it's working again


text:
Q: Using a PHP loop to fetch MySQL data and repeat until get certain amount I have a database table that stores image details. From this I want to get a exactly 6 images (as strings only) and display the images as background images on figure tags.
Where I am struggling is to get 6 image paths even if there are only 4 in the DB. In this instance I would like to go back around at fetch the first two rows again. Additionally if there are 10 rows from the query, I would like to randomly select only 6.
So far I have...
Functions file
// Slideshow images (Homepage)
function get_slideshow() {
    global $conn;
    $sql =  "SELECT id, caption, image, page_id
                FROM slideshow
                ORDER BY id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->free_result();
    $stmt->close();
    return $result;
}

Index.php
$slideshow = get_slideshow();

<?php
    if ($slideshow->num_rows > 0) {
        while($row = $slideshow->fetch_assoc()) {
?>
        <figure style="background-image:url(<?php echo '/photos/'.$row['image']; ?>)"></figure>
<?php
        }
    }
?>

Any help would be great. Thanks in advance :)

A: Drop the ORDER BY clause from the query. Once you've got the result set in an array, use PHP's shuffle function. Once they've been shuffled, use a loop to generate the image from the 1st 6 images from the shuffled array.
Depending on how many images are in the db table, the use of ORDER BY RAND can potentially have quite a bad performance penalty


text:
Q: Python:Count occurrences of letters in a string I'm looking for a way to count the number of occurrences of a given letter in a string, if a letter appears more than once, use the first formula, if it does not repeat it use the second formula.
def Entropy(n):
    probability= [n_x / len(n) for x, n_x in collections.Counter(n).items()]
    from collections import Counter
    a = Counter(n)
    if a > 1:
        entropy = [-p_x * math.log2(p_x) for p_x in probability]
        return sum(entropy)
    else:
        entropy2 = [-math.log2(r_x) for r_x in probability]
        return sum(entropy2)

A: Maybe this will do.
from collections import Counter
import math
def Entropy(n):
    a = Counter(n)
    probability= [n_x / len(n) for x, n_x in a.items()]
    flag = 0
    for items in a:
        if a[items] > 1:
            flag = 1

    if flag == 1:
        entropy = [-p_x * math.log2(p_x) for p_x in probability]
        return sum(entropy)
    else:
        entropy2 = [-math.log2(r_x) for r_x in probability]
        return sum(entropy2)
print(Entropy("Hello World"))

A: You can use the most_common function.
The example below will print
{'method': 0, 'most_common': 2, 'entropy_sum': 1.584962500721156, 'string': 'coucou'}
{'method': 1, 'most_common': 1, 'entropy_sum': 8.0, 'string': 'abcd'}

import math
import collections as cl

def Entropy(_s):
    probability = [n_x / len(_s) for x, n_x in cl.Counter(_s).items()]
    most_common = cl.Counter(_s).most_common(1)[0][1]
    if most_common > 1:
        method = 0
        entropy = [-p_x * math.log2(p_x) for p_x in probability]
    else:
        method = 1
        entropy = [-math.log2(r_x) for r_x in probability]
    return {"method": method,
            "most_common": most_common,
            "entropy_sum": sum(entropy),
            "string": _s
            }

if __name__ == "__main__":
    strings = [
        "coucou",
        "abcd"
    ]
    for _s in strings:
        ans = Entropy(_s)
        print(ans)


text:
Q: ws jaxb custom external mapping I have to do custom JAXB external mapping file.
Already red tutorial about this and can not find any suitable example of JAXB customization. My scenario is that I have two WSDL files main WSDL and secondary WSDL which is included in main one. And in secondary WSDL file is one complexType definition which has a name that I want to customize. BTW name of that complexType is objectFactory. So now you know what I really really need that external customization.
I have came so far that when I run  wsimport path-to-my-main-wsdl -b customBindings.jaxb
output is like
[ERROR] XPath evaluation of "//xs:complexType[@name='objectFactory']" results in empty target node
line 2 of file:/customBindings.jaxb

File customBindings.jaxb looks like
<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <jxb:bindings schemaLocation="path-to-my-secondary-wsdl#types?schema1" node="//xs:complexType[@name='objectFactory']">
        <jxb:class name="MyObjectFactory" />
    </jxb:bindings>
</jxb:bindings>

At second line of my customBindings.jaxb file are two properties schemaLocation and node. Does property schemaLocation need to point at main WSDL or secondary WSDl? And does property node be exact path (XPath) to wanted complexType or is like this ok? And what is with namespaces within XPath (node property), it has to be xs or what? And what actually this types and schema1 stands for in schemaLocation?
thx

A: I came across your question while researching the same problem.
A few vague hints are found on this page: http://jaxb.java.net/guide/Dealing_with_errors.html
Causes for the "empty target node" message are suggested at the bottom of that page.


text:
Q: Commenting and uncommenting using sed -e I am using sed -e in a python script to comment and uncomment lines in my /etc/network/interfaces file for my RPi2. It works in such a way that when I run my python script, the specific lines in my /etc/network/interfaces will be commented and uncommented respectively. However, I am facing an error where I  cannot comment out some of the lines, in other words, it does not add a '#' in front of the line I want commented out. I am also facing problems uncommenting the wpa-conf /etc/wpa_supplicant.conf
This is the code that I used for commenting in my python script:
stream = os.popen("sudo sed -e '/iface wlan0 inet static/ s/^#*/#/' -i /etc/network/interfaces

I have about 4 other almost identical lines, just the part where 'iface....static' changes.
The code that I used for uncommenting the wpa-conf /etc/wpa_supplicant.conf is this:
stream = os.popen("sudo sed -e '/wpa-conf /etc/wpa_supplicant.conf/ s/^#*//' -i /etc/network/interfaces

Error that came out when I ran the python was:
sh :1 tc/wpa_supplicant.conf/: not found

The python script managed to comment out all but 1 line, and uncomment out all but just the wpa-conf /etc/wpa_supplicant.conf line.
Would appreciate any assistance.

A: You need to escape the forward slashes in this match /wpa-conf /etc/wpa_supplicant.conf/ to /wpa-conf \/etc\/wpa_supplicant.conf/
What is happening is that sed sees /wpa-conf /e which tells it to execute the subsequent command on lines matching /wpa-conf /.   The "subsequent command" is tc/wpa_supplicant.conf/, which is not a valid sed command.


text:
Q: JS reading a varaible name as a string rather than the value Good day,
I have a form where a user can select a product, the "value" stored to it is then parsed to determine the datalist name for the next drop down and the array I need to use (the array has been declared at the top of the JS)
The problem I get is when I pass the value arrayName to the function, it receives it as a string rather than the array.
in the console it shows:
console.log("array:", array) --> array: washArray
console.log("length:", array.length) --> length: 9
It should be:
console.log("array", array) --> array: (2) [Array(3),[Array(3)]
console.log("length", array.length) --> length: 2
If I change
var avgPrice = traverseArray(dlName, arrayName);
to be
var avgPrice = traverseArray(dlName, washArray);
It works correctly and reads the array
however arrayName shows its equal to washArray ... however its the string not the array,
How do I make it read the array with name washArray instead of a string.

    <form id="AvgCalc" class="table-bordered mod-data-default-template jobsdata generaltable boxaligncenter">

            Product:

            <select name="dlproduct" id="dlproduct" onchange="myFunction()">
                <option id="0" value="" selected="" disabled="">« Please Select a Product »</option>
                <option id="1" value='["refModels", "refArray"]'>Refrigerator</option>
                <option id="2" value='["washModels", "washArray"]'>Washing Machine</option>
            </select>

   </form>

 const washArray = [
    ["F3S1CWK2EV","101","2726.76"],
    ["F3S1CWK2EV","107","1919.23"]
  ]

function avgCalc() {
        var values = document.getElementById("dlproduct");
        var val = values.options[values.selectedIndex].value;
        var array = JSON.parse(val);
        var dlName = array[0];
        var arrayName = array[1];              <--- *Issue here*
        console.log("dlname", dlname);
        console.log("arrayName", arrayName);

        var avgPrice = traverseArray(dlName, arrayName);}

function traverseArray(dl, array){
    console.log("Array:", array);          <--- *Issue here*
    console.log("length", array.length)}   <--- *Issue here*


text:
Q: background image on a java gui
Possible Duplicate:
How to set background image in Java?

I am trying to put a background image on my java gui, and I can't figure out how to do it.  I've looked around and tried some code but I can't get it to work. I have the imageicon setup but I don't understand where I'm suppose to put this at.  Please help!

A: Read the section from the Swing tutorial on How to Use Icons for an example of displaying an icon.
Then, depending on your requirement, Background Panel explains how you can then use the JLabel with the icon as a background image.

A: Could this solve your problem? It's an explanation code which shows how you can put a background-image to a panel :) http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.htm


text:
Q: HotChocolate GraphQL filtering on GUID I have very limited knowledge on GraphQL as I am still in the learning process. Now I stumbled upon an issue that I cannot resolve by myself without some help.
I'm using HotChocolate in my service.
I have a class ConsumerProductCategory with a Guid as Id which has a parent that is also a ConsumerProductCategory (think category > sub-category > ...)
Now I want to get the sub categories for a specific category, in linq you would write:
.Where(cat => cat.Parent.Id == id)

First of all lets start with our classes:
public class BaseViewModel : INode
{
    public virtual Guid Id { get; set; }
}

public class ConsumerProductCategory : BaseViewModel
{
    public ConsumerProductCategory()
    {
    }

    public string Name { get; set; }

    [UsePaging]
    [UseFiltering]
    [UseSorting]
    public List<ConsumerProduct> Products { get; set; } = new List<ConsumerProduct>();

    public ConsumerProductCategoryImage Image { get; set; }

    public ConsumerProductCategory Parent { get; set; } = null;

    public bool HasParent => this.Parent != null;
}

The object type definition is like this:
public class ConsumerProductCategoryType : ObjectType<ConsumerProductCategory>
{
    protected override void Configure(IObjectTypeDescriptor<ConsumerProductCategory> descriptor)
    {
        descriptor
            .Name(nameof(ConsumerProductCategory));

        descriptor
            .Description("Categories.");

        descriptor
            .Field(x => x.Id)
            //.Type<UuidType>()
            .Type<IdType>()
            .Description($"{nameof(ConsumerProductCategory)} Id.");

        descriptor
            .Field(x => x.Name)
            .Type<StringType>()
            .Description($"{nameof(ConsumerProductCategory)} name.");

        descriptor
            .Field(x => x.Parent)
            .Description($"{nameof(ConsumerProductCategory)} parent category.");

        descriptor
            .Field(x => x.Products)
            .Description($"{nameof(ConsumerProductCategory)} products.");

        descriptor
           .ImplementsNode()
           .IdField(t => t.Id)
           .ResolveNode((context, id) => context.Service<IConsumerProductCategoryService>().GetByIdAsync(id));
    }
}

The query to get the "main" categories would be like this:
query GetAllCategories {
  consumerProductCategories(
    #request: { searchTerm: "2"}
    first: 10
    after: null
    where: { hasParent: { eq: false } }
    order: {
      name: ASC
    }
  ) {
    nodes {
      id
      name
      image {
        url
        alt
      }
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}

This returns this result:
{
  "data": {
    "consumerProductCategories": {
      "nodes": [
        {
          "id": "Q29uc3VtZXJQcm9kdWN0Q2F0ZWdvcnkKZ2EyOTYxNmRlMWMzMjQ4ZTU4YTU2YzRjYjdhMGQ5NmY5",
          "name": "Category 1",
          "image": {
            "url": "https://picsum.photos/200",
            "alt": "Category 1 Image"
          }
        },
        {
          "id": "Q29uc3VtZXJQcm9kdWN0Q2F0ZWdvcnkKZ2NmZWI0YzNiMGQyNjQyOWI4MGU0MmQ1NGNjYWE1N2Q4",
          "name": "Category 2",
          "image": {
            "url": "https://picsum.photos/200",
            "alt": "Category 2 Image"
          }
        },
        {
          "id": "Q29uc3VtZXJQcm9kdWN0Q2F0ZWdvcnkKZ2I0MjhjYWE2NGMxNTQ4MTdiMjM1ZWFhZWU3OGRhYWYz",
          "name": "Category 3",
          "image": {
            "url": "https://picsum.photos/200",
            "alt": "Category 3 Image"
          }
        }
      ],
      "pageInfo": {
        "endCursor": "Mg==",
        "hasNextPage": false
      }
    }
  }
}

The first thing I noticed was that the Id's (Guid's) are changed to some base64 encoded strings.
Weird, but if I would do this:
query {
      node(
        id: "Q29uc3VtZXJQcm9kdWN0Q2F0ZWdvcnkKZ2EyOTYxNmRlMWMzMjQ4ZTU4YTU2YzRjYjdhMGQ5NmY5"
      ) {
        ... on ConsumerProductCategory {
          id
          name
        }

      }
    }

this perfectly works, result:
{
  "data": {
    "node": {
      "id": "Q29uc3VtZXJQcm9kdWN0Q2F0ZWdvcnkKZ2EyOTYxNmRlMWMzMjQ4ZTU4YTU2YzRjYjdhMGQ5NmY5",
      "name": "Category 1"
    }
  }
}

However, now I want to filter on the Parent.Id,
query GetSubcategories {
  consumerProductCategories(
    first: 10
    after: null
    where: { parent: { id: { eq: "Q29uc3VtZXJQcm9kdWN0Q2F0ZWdvcnkKZ2NmZWI0YzNiMGQyNjQyOWI4MGU0MmQ1NGNjYWE1N2Q4"}} }
    order: {
      name: ASC
    }
  ) {
    nodes {
      id
      name
      image {
        url
        alt
      }
      parent {
        id
      }
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}

This gives an error that the fieldtype where I do the "eq" is not correct, makes sense because in the data it's actually a Guid.
The result:
{
  "errors": [
    {
      "message": "The specified value type of field `eq` does not match the field type.",
      "locations": [
        {
          "line": 5,
          "column": 31
        }
      ],
      "path": [
        "consumerProductCategories"
      ],
      "extensions": {
        "fieldName": "eq",
        "fieldType": "UUID",
        "locationType": "UUID",
        "specifiedBy": "http://spec.graphql.org/June2018/#sec-Values-of-Correct-Type"
      }
    }
  ]
}

I understand why it gives me this error, but I have no clue how to resolve this.
I looked everywhere on Google but have not found a similar question and in the official docs of HotChocolate I cannot really find a solution for this issue.
Can anyone point me in the right direction?
By the way, is it a good practice to use these "autogenerated" base64 strings as Id's, or is there some way to specify that this generation should not happen and actually return the Guid's instead?
Thanks in advance!

A: Ok, I can answer my own question, basically it isn't supported yet: github
What I've done for now is just add a second Guid in the base class:

This results in:


text:
Q: MAX aggregate function in sql server I wrote the following query to return the the records with the latest date.
select fs.company_id, max(fs.create_dt) as latestcreatedate
from field_sale fs
group by fs.company_id
order by fs.company_id

The query all works fine. But I need to retrieve the record with all related columns attached to it. Such as, id, title, desc and etc.
How can I retrieve the records with its corresponding columns?

A: Couple ways of doing so :
-- 1.
SELECT a.*
FROM field_sale a
INNER JOIN
(
select fs.company_id, max(fs.create_dt) as latestcreatedate
from field_sale fs
group by fs.company_id
)b
ON b.company_id = a.company_id AND b.latestcreatedate = a.create_dt
order by a.company_id;

--  2.
SELECT b.* FROM
(
   SELECT a.* , ROW_NUMBER()
    OVER (PARTITION BY a.company_id ORDER BY a.create_dt DESC)
    AS rn
   FROM field_sale a
)b WHERE b.rn  = 1
ORDER BY company_id

A: WITH    t AS (
           SELECT   fs.company_id,
                    fs.create_dt AS latestcreatedate,
                    id,
                    title,
                    etc,
                    ROW_NUMBER() OVER ( PARTITION BY fs.company_id ORDER BY fs.create_dt DESC ) AS rowNum
           FROM     field_sale fs
         )
SELECT  t.company_id,
        t.latestcreatedate,
        t.id,
        t.title,
        t.etc
FROM    t
WHERE   t.rowNum = 1
ORDER BY t.company_id


text:
Q: is there any way of simulating an autocommit in functions in postgres I know you can't control transactions in functions or procedures, but I'm wondering if there's something like that or some alternative.
The problem:  I have a function that's very expensive that turns things like a customer id into a nice html report.  Trouble is - it takes seconds... so I've put into the function something that basically looks at a cache to see if a pre-rendered one exists, returning it if it does - and if it doesn't - it adds to the cache afterwards - so it will only ever render things once.
Now - given most things will never change - I sort of want to do it across everything - but given the time - it will probably take about 1 year to run - which is ok actually - this system has to run for ten.  Trouble is - I don't want it to lock anything on the database, so I sort of want it trickle along, doing 1 at a time and committing immediately.
I investigated pg_cron, because that seemed an option, but the version of aurora I am using doesn't support it.   Any ideas how I'd do this inside the database?

A: Add a text column to the customer table to hold the html report.
Put trigger(s) on table(s) whose content influences the html report that refreshes the report column.
This gives you instant retrieval and only (re)calculates it when needed.

Or if data is stable:
create table customer_report (
  customer_id int not null primary key,
  report text not null
);

insert into customer_report
select id, my_report_proc(id)
from customer;

A: By all means, don't code that as a function running inside the database. It is fine to do the calculations in the database, but generating a report and iterating over customers belong into client code. That way, committing each report is not a problem.


text:
Q: Multiple Groupings within a Content Query Web Part Does anyone know of a way to do multiple groupings on a content query web part. I have been able to customeize everything else, but the sub groupings issue has me.
What I need to do is, first group the list by column1, then within that grouping group on column2.
Any help would be great. Thanks

A: In the ContentQueryMain.xsl you need to modify the <xsl:template name="OuterTemplate.Body"> but that would end up having you to hardcode which group you want to add. The Extended CQWP and the Enhanced CQWP might give you more options (I could not find a feature list to confirm if you can do multiple groups)


text:
Q: specific solution to pde $u_x + yu_y =0, u(0,y)=y^3$ I have
$$\left\{\begin{matrix}
4u_{x}-3u_{y}=0\\
u(0,y)=y^3
\end{matrix}\right.$$
with general solution
$$u(x, y) = f(ye^{−x})$$
so using the boundary condition I get
$ \ \ u(0,y)=y^3 \ $ so $\ \ y^3=f(ye^{0}) \quad$  therefore  $ \ \ f(y)=y^3$
which suppose give  the solution
$$u(x, y) = \mathbf{(y e^{−x})^3} = y^3 e^{−3x}$$
I don't understand the final substitution of  $\quad y \quad$  for $\quad ye^{−x}$. Could anybody explain please?

A: You obtain the general solution $u(x,y)=f(ye^{-x})$ which is correct.
Then , with the boundary condition, you obtained $f(y)=y^3$ which is correct.
This relationship defines the function $f$
This definition of function is valid for any symbol of the variable, for example : $f(t)=t^3$ or $f(z)=z^3$ or ...
For example let :
$$f(X)=X^3$$
Thus :
$$u(x,y)=f(ye^{-x})=f(X) \text{ where } X=ye^{-x}$$
$$u(x,y)=f(X)=X^3=\left(ye^{-x} \right)^3$$
$$u(x,y)=y^3e^{-3x}$$


text:
Q: Want to convert the list to a comma separated file in Python? I have a raw file as :
RollNo    Address1    City    State    ZipCode    Age    Branch    Subject    Marks1    Marks2
10000        6505 N MGM W   ROAD                                                                                MMUMBAI CITY                   IN      46360                          77          0              0             -1          1
10002        1721 HAZAREER DR. DR. UNIT 8                                                                         BELAGHIA                       FL      33756                          86          0              0             -1          2

How can I convert this to a comma separated file in python as:
RollNo,Address1,City,State,ZipCode,Age,Branch,Subject,Marks1,Marks2
10000,6505 N MGM W   ROAD,MMUMBAI CITY,IN,46360,77,0,0,-1,1
10002,1721 HAZAREER DR. DR. UNIT 8,BELAGHIA,FL,33756,86,0,0,-1,2

I tried to convert it to a list, so later i can convert it to a comma separated string, using \t as the delimiter, but seems like it won't give me the desired output.
My code was:
files_list=[[i for i in line.strip().split('    ')] for line in open('C:/Users/Vinny/Desktop/Python/file2cnvrt.txt').readlines()]

The output I got:
[['RollNo', 'Address1', 'City', 'State', 'ZipCode', 'Age', 'Branch', 'Subject', 'Marks1', 'Marks2'],
['10000        6505 N MGM W   ROAD                                                                                MMUMBAI CITY                  IN      46360                          77          0              0             -1          1'],
['10002        1721 HAZAREER DR. DR. UNIT 8                                                                         BELAGHIA                      FL      33756                          86          0              0             -1          2']]

Can anyone suggest ?

A: Try this:
def read_file(filename):
    indices = [13, 113, 145, 153, 184, 196, 211, 225, 237, 0]
    columns = []
    data = []
    with open(filename) as f:
        lines = f.readlines()
    columns = lines[0].strip().split('    ')
    for line in lines[1:]:
        row = []
        line = line.strip()
        for i in range(len(indices) - 1):
            row.append(line[indices[i-1]:indices[i]].rstrip())
        data.append(row)
    return [columns] + data

The indices were gathered from the data you gave us. I assumed that everything was perfectly aligned.

A: This may not be the most optimised way, though it produces a comma separated file of the values. Where FILE_IN and FILE_OUT are the filenames of input and output files respectively.
# Read file lines to list as values
file_in = open(FILE_IN, 'r')
lines_of_values = []
for line in file_in:
    # Split line, remove whitespace and remove empty fields
    line_values = list(filter(None, line.strip().split('    ')))
    values = [value.strip() for value in line_values]
    lines_of_values.append(values)
file_in.close()

# Open file to save comma separated values
file_out = open(FILE_OUT, 'w')
for values in lines_of_values:
    print("{:s}".format(",".join(values)), file=file_out)
file_out.close()

A: Several things. First of all, don't use open() directly in your list comprehension.
If you want to use open(), always use a context manager, which guarantees that the file will be closed when you are done with it:
with open('filename..txt') as f:
    lines = f.readlines()

Second: you'll find your life a lot easier to not bother with open() at all and start using the amazing pathlib module.
import Path from pathlib
f_path = Path('C:/Users/Vinny/Desktop/Python/file2cnvrt.txt')
# get text as one big string:
file_str = f_path.read_text()
# get text as a tuple of lines (splits along new line characters):
lines_tuple = f_path.read_text().split('\n')
# get text as a list of lines (use a list if you intend to edit the lines):
lines = list(f_path.read_text().split('\n'))

Third: instead of copying and pasting the entire path to your desktop, you can automatically find its location using the Windows USERPROFILE environment variable:
from pathlib import Path
import os
# os.getenv just gives you a dictionary with all the Windows environment variables
# (such as USERPROFILE and APPDATA)
user_folder_str = os.getenv['%USERPROFILE%']
desktop_path = Path(user_folder_str)/'Desktop'
file_path = Path(user_folder_str)/'Desktop'/'my_file.txt'
lines = list(file_path.read_text().split('\n'))

Fourth: it appears that the sample raw file you pasted does not have any tab characters ('\t') in it. It has 4 spaces ('    ') instead. If this is actually the case, this should work:
[[i for i in line.strip().split('    ') if i] for line in lines]

Note the if i part. That makes sure any consecutive sets of 4 spaces don't put empty strings ('') in your list.
However, your pasted code- which is equivalent to the above- is producing the wrong result. I think it may be because your second and third line actually do have tab characters ('\t') in them rather than 4 spaces. So you'll need to split() using both 4 spaces and a tab character.
The easiest way to do this is to replace the tabs with 4 spaces. Use the same if i again to avoid empty strings.
[[i for i in line.strip().replace('\t', '    ').split('    ') if i] for line in lines]


text:
Q: sum the numbers in different model i have two models Vote and Option,each with column "total" and "quantity".
(Vote has_many:options)
I want to implement like this initially:

Option.quantities.each{ |quantity| total+=quantity}
Vote.total=total

how to implement that??

A: Are you asking for an alternate implementation? Or for something else? You can do the same thing with Enumerable::inject, for example:
class Vote < ActiveRecord::Base
  has_many :options
  def calculate_total
    total = self.options.inject(0) { |sum, vote| sum += vote.quantity }
    save!
  end
end

In this way, the Vote total is calculated and saved every time calculate_total is called.


text:
Q: ASP.NET Core 2.0 Identity update user roles only after re-authorization I`m using ASP.NET Core 2.0 with Identity authorization. When I change user roles through my data context, the changes take effect only when the user logout and login again. Can I somehow update them without re-authorization? Can there be a way to do this using managers?

A: I asked MS about this, and it does not seem to be possible to update/refresh another user, only current. Se GitHub Issue here.


text:
Q: To fill space between these two curves in Gnuplot Code
set xrange [2014:2050]; set yrange [80:110];
set terminal qt size 560,270; set grid;
set offset 1,1,0,0;
inc(x) = 0.439 * x - 800.65;
re(x) = 1.0025 * 83.3 * 1.005**(-2014 + x);
plot re(x) w filledcurves, inc(x) w filledcurves;

and I get

which is wrong.
The parameter selection must be wrong, although it seems to work here.
How can you cover the space between the two graphs?

A: Filling between two curves works only for data. To use it also for functions, you must use the special file name +:
set xrange [2014:2050]; set yrange [80:110];
set grid;
set offset 1,1,0,0;
inc(x) = 0.439 * x - 800.65;
re(x) = 1.0025 * 83.3 * 1.005**(-2014 + x);
plot '+' using 1:(re($1)):(inc($1)) w filledcurves


text:
Q: Can't install arcpy in Jupyter Notebook I have ArcGIS Pro installed, which includes the installed Python packages. I am trying to learn Python and would like to use the ArcPy functions. I have never used Jupyter Notebook before, but to get started, I created a new Python 3 file. I entered the code to install arcpy but received an error.
pip install arcpy
ERROR: Could not find a version that satisfies the requirement arcpy (from versions: none)
ERROR: No matching distribution found for arcpy

import arcpy
ModuleNotFoundError: No module named 'arcpy'

I know I am missing a link somewhere, and I am guessing it has to do with environments. How can I reference the arcpy packages that are installed in my ArcGIS Pro program files?

A: Using "Non-ArcGIS Pro" Conda Environment
I assume that you use an Anaconda or Miniconda installation not provided by ArcGIS Pro, otherwise arcpy should already be available and there is no need to install it.
Note: If you want to use ArcGIS Pro's conda environment, scroll down to Using ArcGIS Pro's Conda Enviroment or Using Jupyter Notebook from within ArcGIS Pro.
To install arcpy, you need to use conda instead of pip. As far as I know arcpy is not available in the Python Package Index (pip's repository).
Initial Setup
Open Anaconda Prompt (or any command prompt if conda can be found through the PATH variable).
First you need a conda environment. Use the following command to create an environment called esri-notebook (can be any name):
conda create -n esri-notebook

Then activate the environment using:
conda activate esri-notebook

Install Jupyter Lab (or Notebook) with:
conda install jupyterlab
conda update --all

Install arcpy with:
conda install arcpy -c esri

Run Jupyter Lab with:
jupyter lab

Or, run Jupyter Notebook with:
jupyter notebook

Your browser will open with Jupyter Lab or Notebook.
Using Jupyter Lab/Notebook
Open Anaconda Prompt (or any command prompt if conda can be found through the PATH variable). Activate the environment:
conda activate esri-notebook

Run Jupyter Lab with:
jupyter lab

Or, run Jupyter Notebook with:
jupyter notebook

Your browser will open with Jupyter Lab or Notebook.
Using ArcGIS Pro's Conda Enviroment
Open Python Command Prompt. arcpy is available (no setup needed).
Then start Jupyter Notebook using:
jupyter notebook

Using Jupyter Notebook from within ArcGIS Pro
You can also create a notebook from within ArcGIS Pro and arcpy should be available to use it without any further setup. Find the Python button within the Analysis ribbon:


text:
Q: Powershell: Export a custom object to a CSV file - extract a single property value with Select-Object I wrote a script that constructs a custom object and exports it to a CSV file:
$reg = Get-ItemProperty HKLM:\SOFTWARE\McAfee\DLP\Agent | Select-Object agentversion

$date = Get-ItemProperty 'C:\Program Files\McAfee' | Select-Object {$_.LastWriteTime}

$date86 = Get-ItemProperty 'C:\Program Files (x86)\McAfee'| Select-Object {$_.LastWriteTime}

New-Object -TypeName pscustomobject -Property @{
  "Number1"=$reg
  "Number2"=$date86
  "Number3"=$date } | export-csv -Path C:\****\desktop\stuff.csv -NoTypeInformation

and the data row in the resulting CSV file is:

"@{AgentVersion=9.4.112.22}","@{$.LastWriteTime=5/6/2016 6:02:32 AM}","@{$.LastWriteTime=7/5/2016 8:34:01 PM}"

Is it possible to get rid of the unwanted @{<name>=...} wrappers?

A: The expression:
Select-Object {$_.LastWriteTime}

outputs an object with a single property with name $_.LastWriteTime. The simplest way to fix it is to use the -ExpandProperty parameter which will only output the value that you are interested in. e.g.:
$date86 = Get-ItemProperty 'C:\Program Files (x86)\McAfee'|
            Select-Object -ExpandProperty LastWriteTime

Note that I've also removed the script block from the Select-Object command, as it wasn't necessary.

A: To complement zdan's helpful answer[1]
with alternatives:
If you just want the value of a given object's property, simply wrap the command in (...) and use .<propertyName>:
(Get-ItemProperty 'C:\Program Files\McAfee').LastWriteTime # returns a [datetime] instance

In PSv3+, the above also works with commands returning multiple items (arrays), in which case an array of the input items' individual property values is output - this feature is called member-access enumeration.

PSv3 introduced a shortcut syntax for % / ForEach-Object (and also ? / Where-Object) that can be leveraged here as well :
Get-ItemProperty 'C:\Program Files\McAfee' | % LastWriteTime # ditto

This is the equivalent of the more verbose (which also works in PSv2-):
Get-ItemProperty 'C:\Program Files\McAfee' | % { $_.LastWriteTime }

These two pipeline-based syntax forms are slower, but have two advantages:

*

*Large input collections are better processed in pipelines one by one in order to keep memory use constant (if feasible; if you need to collect the entire output in memory, there is no advantage).

*This syntax unambiguously references an individual item's property rather than a property of the collection as a whole.

*

*E.g., (Get-ChildItem -File C:\Windows).Length returns the count of files in C:\Windows, because Length is interpreted as the collection's (array's) property;
by contrast, Get-ChildItem -File C:\Windows | % Length returns an array of the individual files' .Length (file-size) property values.

Finally, in PSv4+, you may also use the .ForEach() collection method, which doesn't use the pipeline and is therefore faster (though slightly slower than member-access enumeration), but, like member-access enumeration, requires that the input collection be in memory in full:
(Get-ItemProperty 'C:\Program Files\McAfee').ForEach('LastWriteTime')

[1] A quick overview of Select-Object's behavior:

*

*Select-Object [-Property] <string[]> returns a custom object for each input object, containing only the specified properties; even with only a single property specified, the results are custom objects with that single property, not the property values themselves.

*By contrast, using -ExpandProperty <string> returns the given, single property's value from each input object (typed as-is) instead.
A simple example: extract the Year property value from a Get-Date call:
# WRONG: with (implied) -Property
PS> $val = Get-Date | Select-Object Year; "$val"
@{Year=2018}  # !!
# A custom object with a Year property was returned and the above is its
# string representation, the equivalent of:
#      "$([pscustomobject] @{ Year = 2018 })"

# CORRECT: with -ExpandProperty
PS> $val = Get-Date | Select-Object -ExpandProperty Year; "$val"
2018  # OK: -ExpandProperty extracted just the property's *value*


text:
Q: Ruby on Rails - Problems with DELETE and EDIT of an object Currently i am struggling with creating my first rails web app. It should be a blog (following the tutorial).
I can create new articles, see them but somehow my DELETE and EDIT buttons are not working (showing error messages). I searched hours for solutions (here & on other forums) but couldnt figure it out so i am kindly asking for help from you guys! (thanks in advance!).
Versions: Rails(4.0.0), Ruby(2.3.3p222)... LEt me know if you need anything more that is not stated here.
Controller file
class EventsController < ApplicationController
  include EventsHelper

def index
  @events = Event.all
end

def show
   @event = Event.find(params[:id])
end

def new
   @event = Event.new

end

def create
   @event = Event.new(event_params)
   @event.save

   redirect_to event_path(@event)
end

def destroy
   @event = Event.find(params[:id])
   @event.destroy
   redirect_to events_path
end

def edit
   @event = Event.find(params[:id])
end

def update
   @event = Event.find(params[:id])
   @event.update(event_params)

   redirect_to event_path(@event)
end

private
def event_params
   params.require(:event).permit(:title, :body)
end
end

show.html.erb (where i call EDIT & DELETE)

<%= @event.title %>

<%= @event.body %>

<%= link_to "<< Back to Event List", events_path %>

<%= link_to "edit", edit_event_path(@event) %>
<%= link_to "delete", event_path(@event), method: :delete, data: { confirm: "Are you sure?" } %>

edit.html.erb

Edit an Event

<%= form_for(@event) do |f| %>

<% @event.errors.full_messages.each do |error| %>

<%= error %>

<% end %>

<%= f.label :title %>

<%= f.text_field :title %>

<%= f.label :body %>

<%= f.text_area :body %>

<%= f.submit %>

<% end %>

routes.rb
Events::Application.routes.draw do
   root to: 'events#index'
   resources :events
end

Output of routes:
    Prefix Verb   URI Pattern                Controller#Action
      root GET    /                          events#index
    events GET    /events(.:format)          events#index
           POST   /events(.:format)          events#create
 new_event GET    /events/new(.:format)      events#new
edit_event GET    /events/:id/edit(.:format) events#edit
     event GET    /events/:id(.:format)      events#show
           PATCH  /events/:id(.:format)      events#update
           PUT    /events/:id(.:format)      events#update
           DELETE /events/:id(.:format)      events#destroy

Error Messages:

After EDIT ->  Couldn't find Event with id=edit
After DELETE -> No route matches [DELETE] "/events"

event.rb (in this location -> events/app/models)
class Event < ApplicationRecord
end

`20170513124425_create_events (migration file of event)
class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
       t.string :title
       t.text :body

       t.timestamps
    end
  end
end

A: I just recreated your app. There were a few things I had to do to get it to work. First, make sure you run rake db:migrate.

*

*In your index action, change @event to @events.

The reason for this is you are trying to show all events on the index page, not just a single event.

*In your destroy action, change your redirect_to call to redirect_to events_path.

Currently, when you delete an event, you are trying to redirect back to that event. Since the event no longer exists, you are getting an error.

*In your show.html.erb file, change both occurrences of @events to @event.

You are going to show only one event on this page, not all events.

*Change the first line of your routes.rb file to Rails.application.routes.draw do
If you make these changes, your app should work. You should also put your event_params method in a private section in your controller.


text:
Q: The type variable used as exception parameter Could you get an example for the following rule
JLS 14.20

It is a compile-time error if a type variable is used in the
  denotation of the type of an exception parameter.

A: It means something like this:
catch (MySpecialException<T> ex) {
    ...
}

T is a type variable here.


text:
Q: Spring integration not able to ignore case while mapping request headers into response In my spring integration application , one of the step flows creates an outbound request for which X-JWS-Signature header is added and as part of the response another X-Jws-Signature (see the case difference)header is received with a different value. Ideally, while preparing the response headers as spring integration adds the request headers by default it ignores the existing values for headers present in request and replaces them with the values in response headers if header names are same but it in my case it treats them as two different headers which is not what I expect.
I can not see any functionality within DefaultHttpHeaderMapper class that allows for this case sensitivity in the header mapping to be ignored . Can you please help me with this ?

A: No; header names are case-sensitive; you would need to write a custom header mapper for this use case.


text:
Q: Why does automating SFTP with Expect hang after sending the password? I am attempting to automate uploading some files from my Linux server to an FTP-enabled Windows server. I am successfully doing so manually using SFTP and then issuing the put command. However, when called from cron, my script keeps stopping for a password.
Below is the code I am attempting to use:
#!/usr/bin/expect
#!/bin/sh
clear
spawn sftp remoteuser@43.123.0.10
expect "password"
send "world"
expect eof

As it stands, it stops each time to request a password. Why doesn't send "world" complete the password dialog?
UPDATE:
#!/usr/bin/expect
#!/bin/sh
clear
spawn sftp remoteuser@43.123.0.10
expect "remoteuser@43.123.0.10's password:"
send "world"
expect eof

Now I get the following error:
xml_reports.sh: line 5: spawn: command not found
couldn't read file "remoteuser@43.123.0.10's password:": no such file or directory
xml_reports.sh: line 7: send: command not found
couldn't read file "eof": no such file or directory

A: Try like this:
#!/bin/bash
expect -c "
spawn sftp remoteuser@XX.XX.XX.XX
expect \"password\"
send \"PASSWORD\r\"
interact "

Example : http://www.techtrunch.com/scripting/lazy-admins-part-2

A: You need to use arguments when you run it. Read this article. It explains how to do this properly.

A: What is happening is Expect is still waiting for the pattern to arrive (until timeout), it could be that "password" is not in the prompt of sftp  and that it could be "Password" or something else.


text:
Q: Problems with EmusicJ on Ubuntu 14.04 I am running Ubuntu 14.04 in my new machine and have a subscription to emusic (because I used it before in my Windows days because of the great selection of classical music). I have used it on my old machine (running older versions of Ubuntu) with some success but am having difficulties doing so now.
I am trying to use EmusicJ but do not/cannot remember how to do so. I have downloaded the program and unzipped it and ran the following command in a terminal:
./emusic

If I remember correctly, once I go to the emusic site and download my music, the EmucisJ program should open and begin downloading the music through that program but this time it is not and I have already wiped my old box in order to give it to a friend.
Any help is appreciated as I would like to continue with Emusic, but if I cannot get this resolved I will likely have to cancel my subscription and find a better alternative.
Thanks.


text:
Q: react-bootstrap-table2 column width change on cell click I have base react-bootstrap-table code:
import React from 'react'
import BootstrapTable from 'react-bootstrap-table-next';
import cellEditFactory from 'react-bootstrap-table2-editor';

const products = [
  {
    id: "0",
    name: "test",
    price: "2100"
  },
  {
    id: "1",
    name: "test",
    price: "2100"
  },
  {
    id: "2",
    name: "test",
    price: "2120"
  }
];

const columns = [
  {
    dataField: "id",
    text: "Product ID"
  },
  {
    dataField: "name",
    text: "Product Name",
  },
  {
    dataField: "price",
    text: "Product Price"
  }
];
export default class App extends React.Component {

    render() {
        return (
            <BootstrapTable
            keyField="id"
            data={ products }
            columns={ columns }
            cellEdit={ cellEditFactory({mode: 'click'})}
            />
        )
    }
}

My problem is that  column changes width, when I click editable cell. I see on live demo that is way to block this effect. live demo

I try avoid this effect by adding css with max width, but it's not problem cell, but whole column:
editorStyle: {
    backgroundColor: '#20B2AA',
    maxWidth: '30%',
},

A: You need add .table {table-layout: 'fixed'}.

A: I was able to resolve this issue by using style props for each column in my table. Specifically, I added the following props:
editorStyle: {width:'100%', overflow:'scroll', padding:'inherit', height:'inherit'},
style: {width:'20%'}

To come up with the width of 20% I had to play around a bit. My table has more than 5 columns, and I found that having my total width across all columns sum to more than 100% gave me good looking columns that didn't expand when editing.


text:
Q: Android: Find a value inside an Array with a "a like" value I'm having problem with this part
My Code:
String[] sample = {'name=NAME', 'add=ADD', 'age=AGE', 'gender=GENDER'};

for(int a = 0; a < sample.length; a++) {
    if(Arrays.asList(sample).contains("name")) {
        Log.d(tag, "successful");
    } else {
        Log.d(tag, "failed");
    }
}

When I'm using this code, it doesn't return true, but when I use .contains("name=NAME")
it returns true.
Is there any possibility to compare a string value using not too specific string?
BTW, those string values came from a file.txt.

A: If you use Arrays.asList(sample) you will have a list containing the String "name=NAME" hence it doesn't contain the String "name"
You should loop over the array (not needed to create the list)
boolean found = false;
for (String s: sample)
    if (s.contains("name"))
        found=true;

A: .contains method will check whether the object is present in the ArrayList or not.
Here in your case objects are : "name=NAME","add=ADD","age=AGE", "gender=GENDER" which are of String type. So it is obvious that it returns false.
For you, better practice is to create a class named Person which has attributes like name,add,age and gender. Then store the object of it in ArrayList and you can check whether object is in ArrayList of not using .contains() function. Like below :
class Person{
String name;
String add;
int age;
String gen;
    // All getters and setters methods will be here.
}

public static void main(String[] args){
    Person p = new Person();

    //Here you can set the properties of person using p.setXXX() methods
    //Now suppose you have ArrayList of Person object named "per" then you can check
    // whether Person exist in it or not using contains like below

    per.contains(p) //returns true if per contains object p

    //or you can check name by below code

    for(Person temp:per){
            if(temp.getName().equals(name)){ //returns true if name matchs with Persons name
                      //do something
            }
}

A: To get a value based on key:
1) You can use HashMap object
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
  public static void main(String args[]) {
    // create hash map
    HashMap newmap = new HashMap();

    // populate hash map
    newmap.put("name", "abcde");
    newmap.put("age", "XX");
    newmap.put("Gender", "Male");

    // get value of key Gender
    String val=(String)newmap.get("Gender");

    // check the value
    System.out.println("Value for key 3 is: " + val);
  }
}

2) You can also use Map object
  Map<String, String> map = new HashMap<String, String>();
  map.put("name", "abcde");
  map.put("age", "XX");
  String val=(String)map.get("name");

3) You can also use two dimentional array of string
  String data = "name=Name,age=Age";
  String[] rows = data.split(",");
  String[][] matrix = new String[rows.length][];
  int r = 0;
  for (String row : rows) {
     matrix[r++] = row.split("\\=");
  }
  System.out.println(matrix[1][1]);


text:
Q: How to disable automatic retries in GCD? In Google Cloud Dataflow, when a task runs into a problem it is automatically re-run a few times. The following message appears in the log:
Failed task is going to be retried.

However, while developing, the cause of the failure is almost always a bug of mine and so I would prefer for the job to be canceled instead of continuing needlessly.
Is there some setting I can use to control the retry behavior?
Ideally this would be something in the pipeline options but I couldn't find anything there.

A: It's not currently possible to change the number of retries when running on the Dataflow service.
However, you can use the DirectPipelineRunner to test your code locally, and that will fail immediately if your code throws an exception.


text:
Q: Speeding Up Ubuntu 19.04 in Dual Monitor with Virtualbox I'm using Ubuntu 19.04 (Lubuntu 19.04, in my case) with Virtualbox. If I don't have my second monitor connected to my laptop, the GUI transition animations (hover over menus, etc.) in GTK2, GTK3, Qt, and other widget libraries load very fast and my mouse doesn't jam. However, the moment I connect my second monitor and tell Virtualbox to load that as the primary monitor, the transition animations drag and the mouse occasionally jams until the transition animation caches, and even then, it caches only for so long and jams again while it rebuilds the transition animation cache. This is especially evident in Chromium browser and my Pluma editor, but not so much at all with the Q-based apps that come with the new Lubuntu 19.04.
Some articles have suggested that I could attempt xorg.conf tweaks. However, that file no longer exists and I only have /etc/X11/xorg.conf.d, and in that folder there's only a keyboard conf file, nothing more.
Why is it that when booting Virtualbox display into my laptop is fast, but booting Virtualbox display into my attached monitor is slow? Note that this problem didn't occur in Lubuntu 14.04 32 bit, occurred slightly but nowhere near as bad in Lubuntu 16.04 32 bit, and now occurs a lot in Lubuntu 19.04 64 bit. (They don't make a Lubuntu 19.04 32 bit.)
I'm running a Mac Air 13" (mid 2013) with an attached ASUS (Make:MX279/Model:MX279H) 27" display. My Mac tells me that my graphics chipset is Intel HD Graphics 5000 1536 MB graphics.
Note, I don't mean to imply here that I'm trying to boot Linux into a dual monitor setup. No, my Mac OS is, but my Linux I want to boot into my attached monitor, not in dual monitor config.

A: I was able to get a slight improvement on this problem by doing these two steps:

*

*Tweak Animation Settings

*Open Ubuntu Software Sources control panel, which might be listed as Additional Drivers control panel. You'll see a tab that says Additional Drivers. In there, I noticed two Innotek drivers. One was for Graphics Adapter, the other for Guest Service. Innotek is the maker of VirtualBox, owned by Oracle. I tried the 2 graphics adapter settings, but neither showed an improvement. The one that has "hwe" on it stands for hardware emulation. So, I set that setting to "Do not use the device" since it didn't improve it. Next, I went to the VirtualBox Guest Service driver, and set it on Using x86 virtualization service - guest addition module source for dkms from virtualbox-guest-dkms (proprietary). I also tried the one with "hwe" (hardware emulation). I found that the non-hardware emulation VirtualBox Guest Service version sped things up considerably. It still locks up slightly when the browser is downloading something slow, but the graphics processing is considerably faster on the second monitor now.


text:
Q: Jetty web server is automatically shutting down on EC2 I have Jetty 8.1.14.v20131031 is running on EC2 Ubuntu 12.04. It shuts down automatically around in 3 HOURS after it is started. Just to confirm that it is not the issue of my code I removed war file from the server and started with default [spdy.war and test.war] but the same outcome. It got shut down after 3 hours. Jetty does not log any error in the log. Just to mention that this issue started a month ago, before that it was working fine.
LOG -
Web server Started-
2016-11-28 18:00:30.694:INFO:oejs.Server:jetty-8.1.14.v20131031 2016-11-28     18:00:30.712:INFO:oejdp.ScanningAppProvider:Deployment monitor   /opt/jetty/webapps at interval 1 2016-11-28
18:00:30.718:INFO:oejd.DeploymentManager:Deployable added:  /opt/jetty/webapps/test.war 2016-11-28 18:00:30.748:INFO:oejw.WebInfConfiguration:Extract jar:file:/opt/jetty/webapps/test.war!/ to
/mnt/tmp/tmp/jetty-0.0.0.0-8080-test.war-_test-any-/webapp 2016-11-28 18:00:31.594:INFO:oejs.TransparentProxy:TransparentProxy @ /test/javadoc-proxy to http://download.eclipse.org/jetty/stable-
8/apidocs 2016-11-28 18:00:31.594:INFO:oejd.DeploymentManager:Deployable added: /opt/jetty/webapps/spdy.war 2016-11-28 18:00:31.596:INFO:oejw.WebInfConfiguration:Extract
jar:file:/opt/jetty/webapps/spdy.war!/ to /mnt/tmp/tmp/jetty-0.0.0.0-8080-spdy.war-_spdy-any-/webapp 2016-11-28 18:00:31.677:INFO:oejdp.ScanningAppProvider:Deployment monitor /opt/jetty/contexts at
interval 1 2016-11-28 18:00:31.678:INFO:oejd.DeploymentManager:Deployable added: /opt/jetty/contexts/javadoc.xml 2016-11-28 18:00:31.709:INFO:oejs.AbstractConnector:Started
SelectChannelConnector@0.0.0.0:8080

Just idle. No logging in between
Stopped automatically after 3 hours-
2016-11-28 21:11:27.567:INFO:oejs.Server:Graceful shutdown SelectChannelConnector@0.0.0.0:8080 2016-11-28 21:11:27.567:INFO:oejs.Server:Graceful shutdown o.e.j.w.WebAppContext
{/test,file:/mnt/tmp/tmp/jetty-0.0.0.0-8080-test.war-_test-any-/webapp/},/opt/jetty/webapps/test.war 2016-11-28 21:11:27.568:INFO:oejs.Server:Graceful shutdown o.e.j.w.WebAppContext
{/spdy,file:/mnt/tmp/tmp/jetty-0.0.0.0-8080-spdy.war-_spdy-any-/webapp/},/opt/jetty/webapps/spdy.war 2016-11-28 21:11:27.568:INFO:oejs.Server:Graceful shutdown o.e.j.s.h.ContextHandler
{/javadoc,file:/opt/jetty/javadoc/} 2016-11-28 21:11:28.589:INFO:oejsh.ContextHandler:stopped o.e.j.s.h.ContextHandler{/javadoc,file:/opt/jetty/javadoc/} 2016-11-28
21:11:28.601:INFO:oejsl.ELContextCleaner:javax.el.BeanELResolver purged 2016-11-28 21:11:28.601:INFO:oejsh.ContextHandler:stopped o.e.j.w.WebAppContext{/spdy,file:/mnt/tmp/tmp/jetty-0.0.0.0-8080-
spdy.war-_spdy-any-/webapp/},/opt/jetty/webapps/spdy.war 2016-11-28 21:11:28.664:INFO:oejsl.ELContextCleaner:javax.el.BeanELResolver purged 2016-11-28 21:11:28.665:INFO:oejsh.ContextHandler:stopped
o.e.j.w.WebAppContext{/test,file:/mnt/tmp/tmp/jetty-0.0.0.0-8080-test.war-_test-any-/webapp/},/opt/jetty/webapps/test.war

A: I started jetty ignoring the hangup signal and this work around seems to be working as of now.  I started jetty with this command [nohup java -jar start.jar &]. But root cause of shut down signal is still away from my sight.


text:
Q: OpenMDAO Error: object has no attribute '_post_setup_vars' I'm building a new OpenMDAO component. I do:
prob = Problem(impl=impl, root=myNewComponent(nTurbs=4, rotor_diameter=126.0))
prob.driver = ScipyOptimizer()
prob.driver.add_desvar('turbineX')
prob.driver.add_objective('AEP')
prob.setup()
prob.run()

..And OpenMDAO crashes with AttributeError: 'myNewComponent' object has no attribute '_post_setup_vars'. What does this message mean?

A: You forgot to put super(myNewComponent, self).__init__() in your component's __init__ function.


text:
Q: XPath find_elements_by_xpath() returns empty list, but XPath helper extension shows results I'm having trouble with getting the href attribute article links from the page with XPath.
So, this is the result from the query using the Chrome extension XPath Helper on https://www.ethics.senate.gov/public/index.cfm/dearcolleagueletters?page=1:
//table[@class="table recordList"]//@href

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from threading import Thread

url_xpath = '//table[@class="table recordList"]//@href'
url = 'https://www.ethics.senate.gov/public/index.cfm/dearcolleagueletters?page=1'

options = Options()
options.headless = True
# change filepath of chromedriver
driver = webdriver.Chrome(options=options, executable_path=r'C:\Users\User\Desktop\chromedriver')

try:
    driver.get(url)
    print("got url") #<- reaches here
    url_elements = driver.find_elements_by_xpath(url_xpath)
    print("url_elements", url_elements) # <- doesn't reach here
    for url_elements in url_elements:
        article_url = url_elements.get_attribute('href')
        print("article url", article_url)
except:
   pass

Where am I going wrong here?
Thanks

A: The issue is the xpath expression used.
Because you're using //@href at the end, you're getting an error because the returned results are not actually of type element but an attribute:
Message: invalid selector: The result of the xpath expression "//table[@class="table recordList"]//@href" is: [object Attr]. It should be an element.

Besides this, you're also getting the attachments icon href which may or may not be in your requirements.
To get only the article links you can use this xpath expression:
//table[@class="table recordList"]//a[@class=\'ContentGrid\']

If you need both, the article URL and attachments URL you can use this:
//table[@class="table recordList"]//a[@class='ContentGrid' or @title='View Files']


text:
Q: Menu 'title' transition with pop-out effect I'm dealing with an interesting problem now. I have a menu which consists of nested list inside a list. Something like this:

         Icon title

Span element with a class title is supposed to be hidden off screen and should pop-out on hover. My problem is, that I can't force this popping-out span to 'slide' underneath the both menus.
Here is the fiddle.
What am I doing wrong? I didn't design the page I'm just trying to make it work.
Note:
The class 'icons' is the reminiscent of the older version in which user was able to switch between icons or text displayed in the menu.
UPDATE
I found a workaround. Instead of hiding the title span off screen I changed it visibility to hidden and show it on hover. The only problem is that the text is shown without transition effect and it looks bad when transition is slower.
span.title {
  position: absolute;
  height: inherit;
  background-color: #3a5fcd;
  line-height: inherit;
  padding: 0 .5rem;
  white-space: nowrap;
  transition: all ease-in-out 0.1s;
  width: 0px;
  visibility: hidden;
}

&:hover, &:focus {
  span.title {
    left: 100%;
    width: auto;
    transition: all ease-in-out 0.1s;
    width: 10em;
    visibility: visible;
  }
}

Here is the link to updated fiddle.


text:
Q: Oracle INSTR equivalent in Spark SQL I tried to replicate the oracle Instr function, but it seems to me that there are not all the arguments that exist in Oracle. I receive this error and I would like to include this transformation in a "plataforma" field in the table but I can't:
SELECT
SUBSTR(a.SOURCE, 0, INSTR(a.SOURCE, '-', 1, 2) - 1) AS plataforma,
COUNT(*) AS qtd
FROM db1.table AS as a
LEFT JOIN db1.table2 AS b ON a.ID=b.id
GROUP BY SUBSTR(a.SOURCE, 0, INSTR(a.SOURCE, '-', 1, 2) - 1)
ORDER BY qtd

The Apache Spark 2.0 database encountered an error while running this
  query.
      Error running query: org.apache.spark.sql.AnalysisException: Invalid number of arguments for function instr. Expected: 2; Found: 4;
  line 8 pos 45

I made the transformation of the field that way but I don't know if it is the correct one:

How can I replicate the same Oracle function in Spark? I need to do just this:
Source:
apache-spark-sql
sql-server-dw

Result:
apache-spark
sql-server

A: What you're looking for is substring_index function :
substring_index('apache-spark-sql', '-', 2)

It returns the substring before 2 occurrences of -.
I suppose you want to get the substring before the last occurrence of -. So you can count the number of - in the input string and combine it with substring_index function like this:
substring_index(col, '-', size(split(col, '-')) - 1)

Where size(split(col, '-')) - 1 gives the number of occurences of -.


text:
Q: Web Scraping Shopee (Import Image Url) I'm trying to scrape shopee product names, prices and images. However, I can't seem to extract the images. Is it because of the html? I just can't seem to find the class for images in dataImg
import pandas as pd
from selenium import webdriver
from bs4 import BeautifulSoup

driver =webdriver.Chrome('chromedriver')

products=[]
prices=[]
images=[]

driver.get('https://shopee.co.id/search?keyword=laptop')

content=driver.page_source
soup=BeautifulSoup(content)
soup

for link in soup.find_all('div',class_="_3EfFTx"):
    print('test')
    print(link)

for link in soup.find_all('div',class_="_3EfFTx"):
    #print(link)
    dataImg=link.find('img',class_="_1T9dHf V1Fpl5")
    print(dataImg)
    name=link.find('div',class_="_1Sxpvs")
    #print(name.get_text())
    price=link.find('div',class_="QmqjGn")
    #print(price.get_text())

    if dataImg is not None:
        products.append(name.get_text())
        prices.append(price.get_text())
        images.append(dataImg['src'])

df=pd.DataFrame({'Product Name':products,'Price':prices,'Images':images})
df

A: The website uses JS to load the images, to bypass this, you need selenium with a small delay. Here is the code to download the image src:
from selenium import webdriver
from time import sleep

products=[]
prices=[]
images=[]

driver = webdriver.Chrome(r'F:\Sonstiges\chromedriver\chromedriver.exe')
driver.get('https://shopee.co.id/search?keyword=laptop')

sleep(8)
imgs = driver.find_elements_by_class_name('_1T9dHf')
for img in imgs:
    img_url = img.get_attribute("src")
    if img_url:
        print(img_url)
driver.quit()

In order to get the image, just do this using the fetched URIs. If you use Beautiful soup just because it runs in the background, is here the soloution for running selenium headless (in the background).

A: What happens?
You grab the source while not all content is loaded. If you wait a bit longer, this wont help cause only the first images are loaded, the rest of images will only be loaded if they come into view.
How to fix that?
You have to wait a bit and than scroll in steps down to the bottom of the page:
time.sleep(5)
for i in range(10):
    driver.execute_script("window.scrollBy(0, 350)")
    time.sleep(1)

Example
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
import time

driver =webdriver.Chrome('chromedriver')

products=[]
prices=[]
images=[]

driver.get('https://shopee.co.id/search?keyword=laptop')

time.sleep(5)
for i in range(10):
    driver.execute_script("window.scrollBy(0, 350)")
    time.sleep(1)

content=driver.page_source
soup=BeautifulSoup(content)

for item in soup.select('div[data-sqe="item"]'):
    dataImg=item.img
    name=item.find('div',class_="_1Sxpvs")
    price=item.find('div',class_="QmqjGn")

    if dataImg is not None:
        products.append(name.get_text())
        prices.append(price.get_text())
        images.append(dataImg['src'])

df=pd.DataFrame({'Product Name':products,'Price':prices,'Images':images})
df

Output
Product Name    Price   Images
0   [ACQ] Meja Laptop Lipat Portable    Rp51.990    https://cf.shopee.co.id/file/83a9e6e8ecad7a3db...
1   LENOVO Thinkpad CORE i5 Ram 8GB/ 2TB/1TB/500GB...   Rp2.100.000 - Rp4.200.000   https://cf.shopee.co.id/file/44fbc24f5c585cda1...
2   HP Laptop 14s-cf3076TU/i3-1005G1/256GB SSD/14"...   Rp6.599.000Rp6.598.999  https://cf.shopee.co.id/file/170a45679aa5002f1...
...


text:
Q: Solr won't add my fields : schema.xml I am working with Solr 5.2.1 , i got everything working fine but i can't add field to index.
Here is my schema.xml
      <schema name="example" version="1.5">
<fields>
    <field name="COTID" type="string" indexed="true" stored="true" required="true"/>
     <field name="COTREF" type="string" indexed="true" stored="true" required="true" multiValued="false"/>
    <field name="COTTYPEREF" type="string" indexed="true" stored="true" required="true" multiValued="false"/>
    <field name="COTTYPE" type="string" indexed="true" stored="true" required="true" multiValued="false"/>
     <field name="COTTEXTE" type="string" indexed="true" stored="true" required="false" multiValued="true"/>
</fields>
<uniqueKey>COTID</uniqueKey>
<types>
<fieldType name="string" class="solr.StrField" sortMissingLast="true"/>
<fieldType name="date" class="solr.TrieDateField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
<!-- lots of details -->
</fieldType>
<fieldType name="currency" class="solr.CurrencyField" precisionStep="8" defaultCurrency="USD" currencyConfig="currency.xml"/>
</types>
</schema>

can you help please ?
Thanks

A: If you modify any of Solr configuration files you need to Restart your Solr so that it starts according to your configuration setting. you should restart Solr or reload your core and check what error you are getting.
(refer below URL, change URL names according to you) to reload core

http://127.0.0.1:8080/solr/admin/cores?action=RELOAD&core=core1


text:
Q: how to find a Minimum Salary In sql? my database reads only first integer of the salary according to the first integer it will give the result
example:
salary
3000
2000
10000

in this  minimum is 2000 but it will display the 10000 as a minimum salary
because its reads only first integer of the value
select min(Salary) as Minimum_Salary
from tbl_Employee

and it will give the result is 10000 as a minimum salary

A: Change column type from "varchar" to "int"

A: You are storing the salary as a string rather than as a number.  You can change the type of the column, something like:
alter table tbl_Employee alter column salary money;

However, that does not work in all databases.
When calculating the minimum, you can convert to a numeric type:
select min(cast(salary as numeric(18, 2))
from tbl_Employee;


text:
Q: How to prove a variety is not closed (in a certain larger one)? Here is the problem:

Show by example that the subgroup of an algebraic group generated by two non-irreducible closed subsets need not be closed.

and a hint is given:

Use the cyclic subgroups of $GL(2, \mathbb{C})$ generated by $\begin{pmatrix}
 1 & 0 \\
 0 & -1
\end{pmatrix}$ and $\begin{pmatrix}
 1 & 1 \\
 0 & -1
\end{pmatrix}$.

Now, let $G_1 = \{ \begin{pmatrix}
 1 & 0 \\
 0 & 1
\end{pmatrix}, \begin{pmatrix}
 1 & 0 \\
 0 & -1
\end{pmatrix} \} $ and $G_2 = \{ \begin{pmatrix}
 1 & 0 \\
 0 & 1
\end{pmatrix}, \begin{pmatrix}
 1 & 1 \\
 0 & -1
\end{pmatrix} \}$ (the cyclic subgroups generated by $\begin{pmatrix}
 1 & 0 \\
 0 & -1
\end{pmatrix}$ and $\begin{pmatrix}
 1 & 1 \\
 0 & -1
\end{pmatrix}$
). Both are closed and non-irreducible subsets (subgroups). The subgroup generated by $G_1$ and $G_2$ is $G = \{ \begin{pmatrix}
 1 & n_1 \\
 0 & 1
\end{pmatrix}, \begin{pmatrix}
 1 & n_2 \\
 0 & -1
\end{pmatrix} : n_1, n_2 \in \mathbb{Z} \} $. As $G$ is a set of discrete points in $GL(2, \mathbb{C} )$, can it be not closed?
In another way, set $G_1 = \{ \begin{pmatrix}
 a & 0 \\
 0 & a
\end{pmatrix}, \begin{pmatrix}
 b & 0 \\
 0 & -b
\end{pmatrix} : a,b \in \mathbb{C}^* \} $ and $G_2 = \{ \begin{pmatrix}
 a & 0 \\
 0 & a
\end{pmatrix}, \begin{pmatrix}
 b & b \\
 0 & -b
\end{pmatrix} : a,b \in \mathbb{C}^* \}$. They are closed and non-irreducible. And the subgroup of $GL(2, \mathbb{C})$ generated by $G_1$ and $G_2$ is $G= \{ \begin{pmatrix}
 a & 0 \\
 0 & a
\end{pmatrix}, \begin{pmatrix}
 b & 0 \\
 0 & -b
\end{pmatrix}, \begin{pmatrix}
 c & c \\
 0 & -c
\end{pmatrix}, \begin{pmatrix}
 d & d \\
 0 & d
\end{pmatrix} : a,b,c,d \in \mathbb{C}^* \} $. Isn't it closed? And why?
I don't know if I am wrong somewhere.
To prove a variety is closed, we often make the target variety into the inverse image of a closed variety.
But how to prove a variety is not closed (in a certain larger one)?
Many thanks.

A: Assuming that you are supposed to use Zariski topology, then let's consider the ideal $I(G)$ of polynomials in $R=\mathbf{C}[x_{11},x_{12},x_{21},x_{22}]$ that vanish at all points of $G$. Clearly $x_{11}-1,x_{21},x_{22}^2-1\in I(G)$. Let $J$ be the ideal generated by these three polynomials. We shall prove that actually $J=I(G)$. As the generators of $J$ belong to $I(G)$, clearly $J\subseteq I(G)$. The reverse inclusion
requires a little bit of work.
Let $q$ be an arbitrary polynomial in $I(G)$. The argument is based on the observation that
we can write $q$ in the form $q=p+j$, where $j\in J$, and the other polynomial is of the form $p=f(x_{12})+x_{22}g(x_{12})$, with $f,g\in\mathbf{C}[x_{12}]$. This follows from the facts that

*

*For all positive integers $k$ the power $x_{11}^k\equiv 1\pmod J$, because the polynomial $x_{11}-1\in J$,

*Any multiple of $x_{21}$ is in $J$, because $x_{21}\in J$,

*For all positive integers $k$ the power $x_{22}^{k+2}\equiv x_{22}^k\pmod J$, because
the polynomial $x_{22}^2-1\in J$. Applying this recursively we can replace a term with a high power of $x_{22}$ with another one, where the exponent is either zero or one. All this by moving within a single coset of $J$.

We have
$$
p\left(\begin{array}{cc}1&n\\0&1\end{array}\right)=f(n)+g(n),
$$
and
$$
p\left(\begin{array}{cr}1&n\\0&-1\end{array}\right)=f(n)-g(n).
$$
In order for both of these to vanish simultaneously we must have $f(n)=g(n)=0$. This
must happen for all $n\in\mathbf{Z}$. This is possible if and only if $f=g=0$, because a non-zero polynomial has only finitely many zeros in $\mathbf{C}$. Therefore we must actually have $p=0$, so $q\in J$, and $I(G)=J$.
Thus the Zariski closure of $G$ consists of the zero set of polynomials in $J$, but this set
$$
V(I(G))=V(J)=\left\{\left(\begin{array}{cr}1&z\\0&\pm1\end{array}\right)\mid z\in\mathbf{C}\right\}
$$
is larger than $G$.


text:
Q: Jenkins: 2 master nodes using NFS I´m thinking about the following high availability solution for my enviroment:

*

*Datacenter with one powered on Jenkins master node.

*Datacenter for desasters with one off Jenkins master node.
Datacenter one is always powered on, the second is only for disasters. My idea is install the two jenkins using the same ip but with a shared NFS. If the first has fallen, the second starts with the same ip and I still having my service successfully
My question is, can this solution work?.
Thanks all by the hekp ;)

A: I don't see any challenges as such why it should not work. But you still got to monitor in case of switch-over because I have faced the situation where jobs that were running when jenkins abruptly shuts down were still in the queue when service was recovered but they never completed afterwards, I had to manually delete the build using script console.
Over the jenkins forum a lot of people have reported such bugs, most of them seems to have fixed, but still there are cases where this might happen, and it is because every time jenkins is restarted/started the configuration is reloaded from the disk. So there is inconsistency at times because of in memory config that were there earlier and reloaded config.
So in your case, it might happen that your executor thread would still be blocked when service is recovered. Thus you got to make sure that everything is running fine after recovery.


text:
Q: Docker container can't find path reference I'm attempting to run a node.js server with a React frontend using a Docker container on my local Synology NAS. I was able to get the node.js server functioning using this guide.
I then attempted to add the React front end, however I'm getting this error:
ReferenceError: path is not defined ... at /app/lib/app.js:7
app.use(express.static(path.join(__dirname, 'client/build)));

I'm able to run the server locally, so it seems that this would be an issue related to Docker, but I'm not quite sure where to look to resolve the issue.
For reference, the Dockerfile I'm using:
# test using the latest node container
FROM node:latest AS teststep

WORKDIR /app
COPY package.json .
COPY package-lock.json .
COPY lin ./lib
COPY test ./test
RUN npm ci --development

# test
RUN npm test

# build production packages with the latest node container
FROM node:latest AS buildstep

# Copy in package.json, install
# and build all node modules
WORKDIR /app
COPY package.json .
COPY package-lock.json .
RUN npm ci --production

# This is our runtime container that will end up
# running on the device.
FROM node:alpine

WORKDIR /app

# Copy our node_modules into our deployable container context.
COPY --from=buildstep /app/node_modules node_modules
COPY lib ./lib

# Launch our App.
CMD ["node", "lib/app.js"]

App.js:
const express = require('express')
const app = express()
const path = require('path');
const port = 3000

app.use(express.static(path.join(__dirname, 'client/build')));

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

A: The problem was fixed by resolving the "lin" typo, then deleting the existing container and executing the run.sh script.


text:
Q: timeout on running protractor tutorial with internet explorer I use protractor 3.30 with ie driver 2.52.0 and ie 11.
I want to follow the protractor tutorial with internet explorer:
My protractor config file is:
exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['performance_test.js'],
    capabilities: {
        'browserName': 'internet explorer',
        'ignoreZoomSetting': true,
        'platform': 'ANY',
        'version': '11'
    }
};

My test file is from the tutorial:
describe('angularjs homepage todo list', function() {
    it('should add a todo', function() {
        browser.get('https://angularjs.org');

        element(by.model('todoList.todoText')).sendKeys('write first protractor test');
        element(by.css('[value="add"]')).click();

        var todoList = element.all(by.repeater('todo in todoList.todos'));
        expect(todoList.count()).toEqual(3);
        expect(todoList.get(2).getText()).toEqual('write first protractor test');

        // You wrote your first test, cross it off the list
        todoList.get(2).element(by.css('input')).click();
        var completedAmount = element.all(by.css('.done-true'));
        expect(completedAmount.count()).toEqual(2);
    });
});

When I run the line:

protractor conf.js

I get the following error:

[14:16:18] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[14:16:18] I/launcher - Running 1 instances of WebDriver
  Started
A Jasmine spec timed out. Resetting the WebDriver Control Flow.
F
Failures:
1) angularjs homepage todo list should add a todo
Message:
      Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
    Stack:
      Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at Timer.listOnTimeout (timers.js:92:15)
1 spec, 1 failure
Finished in 30.027 seconds
[14:18:46] I/launcher - 0 instance(s) of WebDriver still running
[14:18:46] I/launcher - internet explorer11 #01 failed 1 test(s)
[14:18:46] I/launcher - overall: 1 failed spec(s)
[14:18:46] E/launcher - Process exited with error code 1

When I look at the selenium log i see as last command
14:16:29.347 INFO - Done: [execute script: try { return (function (model, using, rootSelector) {
  var root = document.querySelector(rootSelector || 'body');
  using = using || document;

  if (angular.getTestability) {
    return angular.getTestability(root).
        findModels(using, model, true);
  }
  var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:'];
  for (var p = 0; p < prefixes.length; ++p) {
    var selector = '[' + prefixes[p] + 'model="' + model + '"]';
    var elements = using.querySelectorAll(selector);
    if (elements.length) {
      return elements;
    }
  }
}).apply(this, arguments); }
catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [todoList.todoText, null, body]]
14:16:29.357 INFO - Executing: [send keys: 0 [org.openqa.selenium.remote.RemoteWebElement@bdfbd98 -> unknown locator], [write first protractor test]])
14:16:53.470 INFO - Executing: [delete session: d575f16c-51f0-4b0e-9531-1bcd00d3b7e2])
14:18:45.352 INFO - Done: [send keys: 0 [org.openqa.selenium.remote.RemoteWebElement@bdfbd98 -> unknown locator], [write first protractor test]]
14:18:46.356 INFO - Done: [delete session: d575f16c-51f0-4b0e-9531-1bcd00d3b7e2]

What is wrong here?

A: I had identical problem I think. Try to add this to your config:
jasmineNodeOpts: {
    defaultTimeoutInterval: 2500000,
},


text:
Q: Yguard and Android Obfuscation I want to know how to use yguard to obfuscate and android library project. I tried but each time blank jar is generated.
I also tried ProGuard but it does not seems to be obfuscating the string in class files.
Here is my build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="project" default="yguard" basedir=".">
    <target name="init">
        <property name="project_name" value="Utils"/>
        <property name="srcDir" value="src\com\example\utils"/>
        <property name="classDir" value="gen\com\example\utils"/>
        <property name="jar" value="${project_name}.jar"/>
        <property name="obfjar" value="${project_name}_obf.jar"/>
        <property name="renamelog" value="${project_name}_renamelog.xml"/>
        <property name="shrinklog" value="${project_name}_shrinklog.xml"/>
        <property name="mainclass" value="Utils"/>
        <mkdir dir="${classDir}" />
    </target>

    <target depends="jar" name="yguard">
        <taskdef name="yguard" classname="com.yworks.yguard.YGuardTask" classpath="libs/yguard.jar"/>
        <yguard>
            <inoutpair in="${jar}" out="${obfjar}"/>
            <attribute name="Deprecated"/>
            <shrink logfile="${shrinklog}">
              <keep>
                <method name="void CopyStream(InputStream is, OutputStream os)" class="${mainclass}" />
              </keep>
            </shrink>

            <rename mainclass="${mainclass}" logfile="${renamelog}">
                <keep>
                    <class classes="none" methods="public" fields="none">
                            <patternset>
                              <include name="com.example.utils.*"/>
                            </patternset>
                          </class>
                </keep>
            </rename>

        </yguard>

    </target>

    <!-- compile -->
    <target name="compile" depends="init">
        <javac srcdir="${srcDir}" includes="com/example/utils/*.java" destdir="${classDir}">
        </javac>
    </target>

    <!-- create .jar -->
    <target name="jar" depends="compile">
        <jar jarfile="${jar}" basedir="${classDir}" includes="com/example/utils/*"/>
    </target>

    <!-- run project -->
    <target name="run" depends="yguard">
        <java classname="${mainclass}" fork="true">
            <classpath>
                <pathelement location="${obfjar}"/>
            </classpath>
        </java>
    </target>

    <!-- removes all that has been built -->
    <target name="clean" depends="init">
        <delete dir="${classDir}" includeEmptyDirs="true" />
    </target>
</project>

And my com.example.utils.Utils file, which is a Utility Class and will be used in other projects:
package com.example.utils;
public class Utils {

    public static String url1 = "http://www/url1";
    public static String url2= "http://www/url2";

    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }

    public static InputStream downloadUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
    }

    public static String downloadStringfromUrl(String urlString) throws IOException
    {
        InputStream is = Utils.downloadUrl(urlString);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null)
            sb.append(line);
        is.close();

        return sb.toString();
    }
}


text:
Q: Remove initializeScrollBars() from Custom view in Android API level 21 I have one custom class having initializeScrollBars() in its constructor.
In API 21, the method was removed, so i am not able to build the app on Lollipop 5.0.I have searched and found that, there is no alternative provided by android officially.
(https://developer.android.com/sdk/api_diff/21/changes/android.view.View.html).
I have checked this link: initializeScrollbars is undefined? and noticed that one developer suggest us to remove the method and let it on the View class by defining R.styleable.View_scrollbars attr which is not internal.
I just don't get it.
Google have answered for this issue as:
"The API has been removed because R.styleable is not public or stable. There is no safe way to pass a TypedArray into that method. Don't call the method."(Ref: https://github.com/GDG-Korea/PinterestLikeAdapterView/issues/31)

*

*Can anyone light me a path how to remove the method
initializeScrollbars() from the custom view?

*Can i simply remove initializeScrollbars() from constructor ?

*What is the best way to initialize scrollbars of a custom view.?


text:
Q: How find this determinant \begin{vmatrix}
    2 & 4 & 4 & \dots  & 4 & 4 \\
    4 & 4 & 4 & \dots  & 4 & 4 \\
    4 & 4 & 6 & \dots  & 4 & 4 \\
    \vdots & \vdots & \vdots & \ddots & \vdots \\
    4 & 4 & 4 & \dots  & 2n-2 & 4 \\
    4 & 4 & 4 & \dots  & 4 & 2n
\end{vmatrix}
I tried to get a triangular matrix, subtracting the lines, but it did not work out

A: \begin{eqnarray*}
\begin{vmatrix}
    2 & 4 & 4 & \dots  & 4 & 4 \\
    4 & 4 & 4 & \dots  & 4 & 4 \\
    4 & 4 & 6 & \dots  & 4 & 4 \\
    \vdots & \vdots & \vdots & \ddots & \vdots \\
    4 & 4 & 4 & \dots  & 2n-2 & 4 \\
    4 & 4 & 4 & \dots  & 4 & 2n
\end{vmatrix}
\end{eqnarray*}
Subtract the second row off all the other rows to get
\begin{eqnarray*}
\begin{vmatrix}
    -2 & 0 & 0 & \dots  & 0 & 0 \\
    4 & 4 & 4 & \dots  & 4 & 4 \\
    0 & 0 & 2 & \dots  & 0 & 0 \\
    \vdots & \vdots & \vdots & \ddots & \vdots \\
    0 & 0 & 0 & \dots  & 2n-6 & 0 \\
    0 & 0 & 0 & \dots  & 4 & 2n-4
\end{vmatrix}
\end{eqnarray*}
The product on the leading diagonal is $\color{red}{-2^{n+1} (n-2)!}$.

A: $$ Q^T D Q = H  $$
$$\left(
\begin{array}{rr}
1 & 0 \\
2 & 1 \\
\end{array}
\right)
\left(
\begin{array}{rr}
2 & 0 \\
0 &  - 4 \\
\end{array}
\right)
\left(
\begin{array}{rr}
1 & 2 \\
0 & 1 \\
\end{array}
\right)
 = \left(
\begin{array}{rr}
2 & 4 \\
4 & 4 \\
\end{array}
\right)
$$
$$\left(
\begin{array}{rrr}
1 & 0 & 0 \\
2 & 1 & 0 \\
2 & 1 & 1 \\
\end{array}
\right)
\left(
\begin{array}{rrr}
2 & 0 & 0 \\
0 &  - 4 & 0 \\
0 & 0 & 2 \\
\end{array}
\right)
\left(
\begin{array}{rrr}
1 & 2 & 2 \\
0 & 1 & 1 \\
0 & 0 & 1 \\
\end{array}
\right)
 = \left(
\begin{array}{rrr}
2 & 4 & 4 \\
4 & 4 & 4 \\
4 & 4 & 6 \\
\end{array}
\right)
$$
$$\left(
\begin{array}{rrrr}
1 & 0 & 0 & 0 \\
2 & 1 & 0 & 0 \\
2 & 1 & 1 & 0 \\
2 & 1 & 0 & 1 \\
\end{array}
\right)
\left(
\begin{array}{rrrr}
2 & 0 & 0 & 0 \\
0 &  - 4 & 0 & 0 \\
0 & 0 & 2 & 0 \\
0 & 0 & 0 & 4 \\
\end{array}
\right)
\left(
\begin{array}{rrrr}
1 & 2 & 2 & 2 \\
0 & 1 & 1 & 1 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
\end{array}
\right)
 = \left(
\begin{array}{rrrr}
2 & 4 & 4 & 4 \\
4 & 4 & 4 & 4 \\
4 & 4 & 6 & 4 \\
4 & 4 & 4 & 8 \\
\end{array}
\right)
$$
$$\left(
\begin{array}{rrrrr}
1 & 0 & 0 & 0 & 0 \\
2 & 1 & 0 & 0 & 0 \\
2 & 1 & 1 & 0 & 0 \\
2 & 1 & 0 & 1 & 0 \\
2 & 1 & 0 & 0 & 1 \\
\end{array}
\right)
\left(
\begin{array}{rrrrr}
2 & 0 & 0 & 0 & 0 \\
0 &  - 4 & 0 & 0 & 0 \\
0 & 0 & 2 & 0 & 0 \\
0 & 0 & 0 & 4 & 0 \\
0 & 0 & 0 & 0 & 6 \\
\end{array}
\right)
\left(
\begin{array}{rrrrr}
1 & 2 & 2 & 2 & 2 \\
0 & 1 & 1 & 1 & 1 \\
0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 1 \\
\end{array}
\right)
 = \left(
\begin{array}{rrrrr}
2 & 4 & 4 & 4 & 4 \\
4 & 4 & 4 & 4 & 4 \\
4 & 4 & 6 & 4 & 4 \\
4 & 4 & 4 & 8 & 4 \\
4 & 4 & 4 & 4 & 10 \\
\end{array}
\right)
$$
$$\left(
\begin{array}{rrrrrr}
1 & 0 & 0 & 0 & 0 & 0 \\
2 & 1 & 0 & 0 & 0 & 0 \\
2 & 1 & 1 & 0 & 0 & 0 \\
2 & 1 & 0 & 1 & 0 & 0 \\
2 & 1 & 0 & 0 & 1 & 0 \\
2 & 1 & 0 & 0 & 0 & 1 \\
\end{array}
\right)
\left(
\begin{array}{rrrrrr}
2 & 0 & 0 & 0 & 0 & 0 \\
0 &  - 4 & 0 & 0 & 0 & 0 \\
0 & 0 & 2 & 0 & 0 & 0 \\
0 & 0 & 0 & 4 & 0 & 0 \\
0 & 0 & 0 & 0 & 6 & 0 \\
0 & 0 & 0 & 0 & 0 & 8 \\
\end{array}
\right)
\left(
\begin{array}{rrrrrr}
1 & 2 & 2 & 2 & 2 & 2 \\
0 & 1 & 1 & 1 & 1 & 1 \\
0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 \\
\end{array}
\right)
 = \left(
\begin{array}{rrrrrr}
2 & 4 & 4 & 4 & 4 & 4 \\
4 & 4 & 4 & 4 & 4 & 4 \\
4 & 4 & 6 & 4 & 4 & 4 \\
4 & 4 & 4 & 8 & 4 & 4 \\
4 & 4 & 4 & 4 & 10 & 4 \\
4 & 4 & 4 & 4 & 4 & 12 \\
\end{array}
\right)
$$


text:
Q: Getting error Invalid block tag on line 80: 'NOUN_LIST|count_ordered', expected 'endblock'. Did you forget to register or load this tag? I created a custom tag and getting error as :

Request Method:     GET
Request URL:    ""
Django Version:     2.2.1
Exception Type:     TemplateSyntaxError
Exception Value:    Invalid block tag on line 80: ''NOUN_LIST|count_ordered'', expected 'endblock'. Did you forget to register or load this tag?

My Project Structure is :

custom_tag.py :
from django import template
register = template.Library()
@register.simple_tag
def count_ordered(value):
    dict = sorted(value, key=lambda val:len(val.list),reverse=True)
    return dict

I am calling this tag as :
{% load custom_tag %}
{% NOUN_LIST|count_ordered as list %}
{{ list }}


text:
Q: Why incorrect convert from string to date? In my Kotlin code:
   const val TS_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"
   val ts = responseJsonObject.get("TS").getAsString()
   val tsDate = SimpleDateFormat(TS_DATE_PATTERN).parse(ts)
   val tsDateAsString = SimpleDateFormat(TS_DATE_PATTERN).format(tsDate)
   logger.info("ts = " + ts + " -> tsDate = " + tsDate + " -> tsDateAsString = " + tsDateAsString)

And here the (formatted for readability) result:
ts             = 2019-01-14T22:56:30.429582
tsDate         = Mon Jan 14 23:03:39 EET 2019
tsDateAsString = 2019-01-14T23:03:39.582

As you can see the ts and tsDateAsString have different times, although they came from the same starting point.
E.g. ts = 22:56:30 but in tsDateAsString = 23:03:39
Why?

A: As a suggestion: whenever you can, use java.time-utilities.
SimpleDateFormat has a special handling for the milliseconds. Everything that is parsed by the S is treated as milliseconds. As long as you deal with 3-digit-milliseconds, everything is fine (you may even just use a single S (i.e. .S) for the milliseconds to parse them), but if you use 6-digit-milliseconds as input then you also get a 6-digit-millisecond(!)-value.
The 6-digit-milliseconds then are actually 3-digit seconds + the 3-digit milliseconds. That is where the deviation is coming from.
How to solve that? Well either shorten the input time string and lose some precision or use the preferred DateTimeFormatter instead with a pattern matching your input, i.e. yyyy-MM-dd'T'HH:mm:ss.SSSSSS:
val TS_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
val formatter = DateTimeFormatter.ofPattern(TS_DATE_PATTERN)

val tsDate = formatter.parse(ts) // now the value as you would expect it...

Transforming that to a TimeStamp will work as follows:
Timestamp.valueOf(LocalDateTime.from(tsDate))