C++: How to display the last five names/lines when reading from a file?

Question: I've been trying to get this function to read the last five lines of a file. This is all I have so far. A similarly structured function that finds the first five lines and displays them worked fine and so does the part of this function that counts up the total number of lines.
Everything else seems to work fine except this part and I'm not sure what I'm doing wrong. I tried multiple different solutions (aka just moving the code around and deleting lines to see if it would help) but nothing worked. It can, however, display 46-50 with the colons but not the last five lines. If I were to display the names before the for loop part and within the while loop counting part, it would successfully display all of the names.
Help would be appreciated.
Thanks. (sorry if I'm not formatting this correctly)
<code>void displayLastFive(ifstream & fin)
{
    char name[81];
    int totalNumberOfLines = 0;

    fin.getline(name, 81);

    fin.clear();
    fin.seekg(0L, ios::beg);

    while (!fin.eof())
    {
        fin.getline(name, 81);
        totalNumberOfLines++;
    }

    for (int i = totalNumberOfLines - 5; i < totalNumberOfLines; i++)
    {
        fin.getline(name, 81);
        cout << i + 1 << ": " << name << endl;
    }

    cout << endl;
}
</code>
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/210353/discussion-on-question-by-mrambiguous-c-how-to-display-the-last-five-names-li).
Answer: answer was much simpler than I thought
<code> void displayLastFive(ifstream & fin)
{
    char name[81];
    int totalNumberOfLines;

    totalNumberOfLines = count(fin);

    fin.clear();
    fin.seekg(0L, ios::beg);

    for (int i = 0; i < totalNumberOfLines; i++)
    {
        fin.getline(name, 81);
        if (i >= totalNumberOfLines - 5)
        {
            cout << i + 1 << ": " << name << endl;
        }
    }

    cout << endl;
}
</code>


Make a p element both content editable and JQuery UI Sortable

Question: Is it possible to make a p element both content editable AND JQuery UI Sortable?
In my simple example below, the p elements are sortable but you cannot edit their text. Is there anyway to overcome this?
Note I have tried nesting p's in containers so that the container is sortable and the p is editable but I still cannot edit the inner p.

$(document).ready(function() {
   $( ".elements" ).sortable({
    connectWith: ".elements"
 });
});
p {
 height: 100px;
 background-color: red;
}

Foo. Help! I can be sorted but cannot be edited.

Bar. Help! I can be sorted but cannot be edited.

Comment: Try to get some help from here. https://stackoverflow.com/a/14745046/7844349
Answer: Through some random attempts at getting it to work, I found that setting focus on the element, and then moving the cursor to the end of the content editable (as shown here by  Nico Burns) is adequate to get the content editable working.
My guess is that the sortable prevents the content editable from getting focus because of some sort of event.preventDefault or cancelBubble.

$(document).ready(function() {
  $(".elements").sortable({
    connectWith: ".elements"
  });

  $(".elements p").on("click", function(e) {
    $(this).focus();
    setEndOfContenteditable(e.target);
  });
});

function setEndOfContenteditable(contentEditableElement) {
  var range, selection;
  if (document.createRange) //Firefox, Chrome, Opera, Safari, IE 9+
  {
    range = document.createRange(); //Create a range (a range is a like the selection but invisible)
    range.selectNodeContents(contentEditableElement); //Select the entire contents of the element with the range
    range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start
    selection = window.getSelection(); //get the selection object (allows you to change selection)
    selection.removeAllRanges(); //remove any selections already made
    selection.addRange(range); //make the range you have just created the visible selection
  } else if (document.selection) //IE 8 and lower
  {
    range = document.body.createTextRange(); //Create a range (a range is a like the selection but invisible)
    range.moveToElementText(contentEditableElement); //Select the entire contents of the element with the range
    range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start
    range.select(); //Select the range (make it the visible selection
  }
}
p {
  height: 50px;
  background-color: red;
}

Foo. Help! I can be sorted but cannot be edited.

Bar. Help! I can be sorted but cannot be edited.

Answer: Here is an example where when the element is clicked, the p tag is converted to an input tag, and when the focus is lost, its converted back to a p tag!

$(document).ready(function() {
 // How to associate a handle that sits outside the element to be dragged?
   $( ".elements" ).sortable({
    connectWith: ".foo"
 });

  function focusout(){
    var val = $('input[contenteditable*="true"]').val();
    var replacement2 = $('
'+val+'
');
    $('input[contenteditable*="true"]').replaceWith(replacement2);
    replacement2.on("click", clicked);
  }

  function clicked(){
    var replacement = $('<input contenteditable="true" value="'+this.innerHTML+'"/>');
    $(this).replaceWith(replacement);
    replacement.on("focusout", focusout);
    $('input[contenteditable*="true"]').focus();
  }

  $('p[contenteditable*="true"]').on("click", clicked);

});
p {
 height: 100px;
 background-color: red;
}

Foo. Help! I can be sorted but cannot be edited.

Bar. Help! I can be sorted but cannot be edited.

Answer: Probably it's not allowing the edition because Jquery is overwriting some event callback enabled by default in contenteditable=true elements.
You can try overwriting focusin and focusout events in order to allow that edition. Check how they are doing it in the link below:
Focus / blur events on contenteditable elements
I hope it'll help you ;)


how to move files located in on-premises windows based file share using scala?

Question: Background : I am using Azure ADFV2 to move data from fileshare to ADLS, after the file is moved successfully I want to archive the file within fileshare location.
How do I connect to on-premises windows based file share and move the files from one folder to another within the fileshare using scala. I am not sure how to establish the connectivity to a file share.
Comment: Too less of information. Better ask people in your organization about how they do it?
Comment: @SarveshKumarSingh - added more info
Comment: why do you have to use scala?
Comment: My last activity is spark in ADF, hence thought I can achieve within the scala code. Based on the success of spark activity, I have to achieve the files. If there is any other way in ADF also fine.
Comment: Maybe you could take a look of this? https://learn.microsoft.com/en-us/azure/data-factory/transform-data-databricks-jar
Answer: You can use file system linked service to establish the connectivity to a file share.

create a self-hosted integration runtime on ADF and install it on your machine.
create a file system linked service, and for "Connect via integration runtime" field, choose the self-hosted ir you created in 1.
configure you linked service and dataset as the doc instructs: https://learn.microsoft.com/en-us/azure/data-factory/connector-file-system
Comment: I don't have a problem with copy files from fileshare, I want to move files within fileshare. There is no move activity in ADF.
Comment: Sorry that I misunderstood. Adf does not support delete now but it's in the roadmap.


function call 'clear_all_cache' and 'clear_assign' is unknown or deprecated. error in smarty?

Question: I need to remove the cache when a user change language, but I get an error message.
<code>  $smarty = new Smarty;
 //$smarty->force_compile = true;
 $smarty->debugging = true;
 $smarty->caching = false;
 $smarty->cache_lifetime = 120;

 if (isset($_COOKIE['country']))
  {
 $country = $_COOKIE['country'];

  $language = "eng";

 if ($country == "NO"){
  $language = "nor";

  $smarty->clear_all_cache();
  }
 }
</code>
I also get this message when i use clear_assign:
<code>function call 'clear_assign' is unknown or deprecated
</code>
Answer: If you have recently upgrade your Smarty to version 3.x.x
some method names are changed
in your case "clear_assign" is changed to "clearAssign"
for more information get offline documentation of "Smarty 3.0.x" from HERE
or online documentation from HERE


Layered Design /Architecture

Question: we use html 5/angular SPA with Webapi at the service which communicates with DAL for dataaccess operations
Layer flow would be:
presentation(html5/angular controllers/service) --> web api --> DAL - -> DB.
we do not have BLL project as such. we are thinking to make DAL as combination of BLL + DAL. And we use DTO objects created through t4 templates and they are used for transfer of data between client and web api and DAL (we dont use EF, we use ADO.Net as underlying provider)

should we require a seperate BLL project or is it ok to combine BLL and DAL proj? considering it should be testable and extendable.
as mentioned, DTO objects are used throughout. should we require any model other than DTO to transfer the data between the client and webapi/DAL?

DAL :
public List GetCustomers {}  this uses Data access helper classes to get the customers and convert to DTO
above CustomerDAL.GetCustomers is being called by webapi project. At this point of time, any BL of (say. customer) is written in web Api project and sometimes at DAL project. we are thinking to move them to one project for consistency and testability.
any insights on this would be helpful.
Answer: The greatest value that I get out of having a separate BLL is that the most important / expensive bits of my application (the business logic), are in an area that has no dependencies on databases or web/http frameworks.  It means that when the next big thing (database, platform, etc) comes along, I can reuse my business layer.
More importantly, DAL and UI layers are MUCH more expensive to test.  When I'm writing unit tests at the UI or DAL layer, I'll end up testing 1-2 scenarios per function... When I'm testing at the BAL layer, I'll create many times more scenarios, because it's so cheap (effort-wise).  This gives me much better coverage for much less cost.
Perhaps your applications don't have much business logic.  If they are purely CRUD wrappers around database tables, it might not justify the expense. Most applications contain far more business logic than the developers want to admit though.  Look through your validations that you run in your WebAPI...  Those are likely all business rules.  Look at your security constraints, those are likely business rules as well.
Whether or not to use DTOs or a more complex domain model depends on your design, environment, and team constraints, and is not something I would feel comfortably addressing in a fifteen minute posting.  Fowler has some strong opinions, calling it an Anemic Domain Model antipattern, but I've seen it used quite successfully for large-scale projects.  One of the nice aspects to this model is the fact that you don't need quite as much of a coherent picture of the application model, which is often the case with large, dispersed teams.

Layered Design /Architecture


How to use ppx derive in utop?

Question: How can I use ppx derive (https://github.com/ocaml-ppx/ppx_deriving) in my utop?
For example, I have to following code:
<code>module A = struct
  module T = struct
    type t = int [@@deriving hash, sexp, compare]
  end
  include Core_kernel.Hashable.Make(T)
end;;
</code>
Answer: Simply entering:
<code>#require "ppx_jane";;
</code>
within utop will make these macros work
Comment: `utop[18]> #require "ppx_jane";;`

`utop[19]> type abc = A | B | C [@@deriving show];;`

`Error: Ppxlib.Deriving: 'show' is not a supported type deriving generator`

How to use ppx derive in utop?


Percorrer inputs com o mesmo name e pegar todos os values

Question: Tenho uma aplicação web na qual eu passo por input hidden um número dinâmico de values através
de um formulário para uma action do Delphi.
Na action, eu queria saber uma forma de pegar todos os values com o mesmo name.
Quando é um só value, eu uso request.ContentFields.Values['numero']
Estou passando os inputs do formulário da seguinte forma:
<input type="hidden" name="numero[]" value="123" />
<input type="hidden" name="numero[]" value="456" />
<input type="hidden" name="numero[]" value="789" />

Mas como eu pego todos dentro da action?

Da forma convencional retorna apenas o conteúdo do primeiro input.
Tentei criar um array dinâmico e passar para ele, mas não deu certo.
Comment: Está utilizando intraweb?
Comment: não Tiago. Aqui fazemos jogando o html dentro de um response.content
Comment: ok, interessante. Se souber algum link na web sobre uma aplicação parecida com o que vocês fazem eu ficaria contente de poder ver, pois gostaria de conhecer. Grato!
Comment: Mas a propósito, as propriedades **name** estão com o valor **numero[]**. você está jogando um índice nesses nomes, certo? Para que fique.. `numero[0], numero[1], numero[2]` e então receber por um vetor..
Comment: Tiago. O que eu queria era assar todos com o mesmo name e percorrer todos esses na action e pegar os valores. Como não estou conseguindo descobrir como fazer isso no delphi 7, estou passando para essa solução que você perguntou. Passarei vários inputs com names diferentes. Assim conseguirei pegar do outro lado tranquilamente.
Answer: Vamos lá, eu não sei como é isso que você está fazendo pelo Delphi, então vou utilizar uma abordagem que temos no C#.
Se você tem algo dessa forma:
<input type="hidden" name="numero[0]" value="123" />
<input type="hidden" name="numero[1]" value="456" />
<input type="hidden" name="numero[2]" value="789" />

Depois você teria algo mais ou menos assim no delphi:
type
  TIntegerArray: Array of Integer;

procedure TMinhaClass.MinhaAction(numero: TIntegerArray);
var
  I: integer;
begin
  // podendo então:
  for I := 0 to High(numero) do
  begin
     // fazer o que deseja com "numero[I]".
  end;
end;

Essa resposta é totalmente baseada em especulação.
Outro ponto é que os campos precisam ter sempre uma ordem, sem quebras, pois algo como:
numero[0]
numero[1]
numero[3]

Algo assim você receberia apenas os valores com índice 0 e 1 em sua action, o campo com índice 3 não receberia por conta da quebra.
Confirme isso também.
Comment: Entendi a sua abordagem. Mas o que eu tenho são com names iguais mesmo. Já estou desistindo e passando com names diferentes mesmo. Assim fica simples pega toso os valores com um for.


How do I connect Posts to Upvotes - ReactJS

Question: I have a laravelapi that fetches posts from the database and another one that fetches upvotes.
Now I want to display posts on my react component and show the length of upvotes for every particular post.
Here is how I have tried it out. But im getting the value as undefined on the console. Please help. Here is my code
import React, { useState, useEffect } from 'react';
import { useNavigate } from "react-router-dom";
import Menubar from "../../components/menubar/Menubar"
import PostSkeleton from '../../components/skeleton/PostSkeleton';
import PostWidget from '../../components/widgets/PostWidget';
import axios from 'axios';

function Community() {
    let navigate = useNavigate();
    const [posts, setPosts] = useState([]);
    const [upvotes, setUpvotes] = useState([]);
    const [limit, setLimit] = useState(4);
    const [isLoading, setIsLoading] = useState(true);
    const [loading, setLoading] = useState(false);

    function handleClick() {
        navigate("/add-post");
    }
    useEffect(() => {

        let isMounted = true;

        axios.get(`/api/posts?page=1&limit=` + limit).then(res => {
            if (isMounted) {
                if (res.data.status === 200) {
                    setPosts(res.data.posts);
                    setIsLoading(false);
                    setLoading(false);
                }
            }
        });
        return () => {
            isMounted = false
        };
    }, [limit]);

    const loadMore = () => {
        setLimit(limit + 4)
        setLoading(true);
    }

    useEffect(() => {

        let isMounted = true;

        axios.get(`/api/upvotes`).then(res => {
            if (isMounted) {
                if (res.data.status === 200) {
                    setUpvotes(res.data.upvotes);
                }
            }
        });
        return () => {
            isMounted = false
        };
    }, []);

    return (

            <Menubar />

                     navigate(-1)} className="headerButton goBack">

Community

                        <form>

                                    <input type="text" onClick={handleClick} className="form-control" placeholder="Tell the World Something" />

                        </form>

                    {isLoading && <PostSkeleton cards={4} />}

                    {posts.map((post) => (<PostWidget post={post} upvotes={upvotes.find(upvotes =>posts.postid === upvotes.post_id)} key={post.postid} />))}

                        <a onClick={loadMore} className={limit <= posts.length ? 'btn btn-text-primary mr-1' : 'btn btn-text-primary mr-1 disabled'}  >{loading ? <>Loading More</> : <>{limit <= posts.length ? <>Load More </> : 'All Posts Loaded'} </>}

    );
}
export default Community;

The PostWidget Component
import React, { useState, useEffect } from 'react';
import { Link } from "react-router-dom";
import { LazyLoadImage } from "react-lazy-load-image-component";
import axios from 'axios';
import toast, { Toaster } from 'react-hot-toast';

const PostWidget = ( {post, upvotes}) => {
    console.warn(upvotes && upvotes.length)

    const formatDate = (dateString) => {
        const options = { year: "numeric", month: "long", day: "numeric" }
        return new Date(dateString).toLocaleDateString(undefined, options)
    }

    return (

            <Toaster />

{post.user && post.user.firstname} {post.user && post.user.lastname}

                        {formatDate(post.created_at)}

                            <Link to={"/post-details/" + post.postid}>
                                <LazyLoadImage src={`http://localhost:8000/${post.postimage}`} alt="avatar" className="imaged w-100" />

                            </Link>
                            <Link to={"/fruit-details/" + post.fruit.id}>

                                {post.fruit.name}

                            </Link>

                        <Link to={"/post-details/" + post.postid}>

                                {post.postcontent}

                        </Link>

                                Upvote (5)

                                Downvote

                            <Link to={"/post-details/" + post.postid} className="comment-button" >

                                Comment
                            </Link>

    );
    }
export default PostWidget;

Comment: Some more code would be helpful. Maybe some minimal, reproducible code sample on codesandbox?
Comment: I have modified the question
Answer: upvotes={upvotes.find(upvotes =>posts.postid === upvotes.post_id)}

I think you need to use post.postId instead of posts.postid
Answer: This seems likely to be incorrect:
upvotes.find(upvotes =>posts.postid === upvotes.post_id)

Probably you meant to use the post being iterated over in the predicate, not the posts collection.
upvotes.find(upvote =>post.postid === upvote.post_id)

Comment: Thank you so much. I am still getting undefined when I try to check `console.warn(upvotes && upvotes.length)`


Is iterative-DFS faster than recursive-DFS?

Question: I have implemented Depth First Search algorithm in an iterative manner and a recursive manner. They both work fine on files with small sizes (less than 1 MB). However, when I try to run them over files with 50 MB, it seems like that the recursive-DFS (9 secs) is much faster than that using an iterative approach (at least several minutes). In fact, the iterative approach took ages to finish.
The only reason I chose to implement the iterative DFS is that I thought it may be faster than the recursive DFS.But this does not seem to be the case.
Is this expected  ?
Note that: I was already using java -Xmx1024m -Xms1024m -Xmn256m -Xss16m RunAlgo to increase the memory.
Below is the code I used to write the iterative DFS.
class IterativeDFS{
long time;
LinkedList<Vertex>topological_sort_list = new LinkedList<Vertex>();

public IterativeDFS(Digraph G){
    dfs(G);
}

public void dfs(Digraph G){
    for(Vertex u : G.getAllVertices()){
        u.set_color("WHITE");
        u.set_pi(-1);
    }
    time = 0;

    for(Vertex u : G.getAllVertices()){
        if(u.get_color().equals("WHITE")){
            dfs_stack(G, u);
        }
    }
}

public void dfs_stack(Digraph G, Vertex u){
    int size =  G.getAllVertices().size();

    /*
     *  to be able to iterate over each adjacency list, keeping track of which
     *  vertex in each adjacency list needs to be explored next.
     */
    HashMap<Vertex, Iterator<Vertex>> adj_map = new HashMap<Vertex, Iterator<Vertex>>();
    for(Vertex i : G.getAllVertices()){
        adj_map.put(i, G.adjEdges(i).iterator());
    }

    Stack<Vertex> stack = new Stack<Vertex>();
    // time++;          // white vertex u has just been discovered
    u.set_d(time);
    u.set_color("GRAY");
    stack.push(u);

    while(!stack.empty()){

        Vertex k = stack.peek();

        Vertex v = null;
        if(adj_map.get(k).hasNext()){
            v = adj_map.get(k).next();          // explore edges (k,v)
            if(v.get_color().equals("WHITE")){
                v.set_pi(k.get_node());
                //  time++;
                v.set_d(time);
                v.set_color("GRAY");
                stack.push(v);
            }
        } else{
                // v's adjacency list is exhausted
                Vertex t = stack.pop();
                time++;
                t.set_f(time);
                t.set_color("BLACK");
                /*
                 *  Topological Sort :
                 *      1. call DFS(G) to compute finishing times v.f for each vertex v
                 *      2. as each vertex is finished, insert it onto FRONT of linked list
                 *      3. return linked list of vertices
                 */
                topological_sort_list.addFirst(t);
        }
    }
}

public LinkedList<Vertex> topological_sort(){
    return topological_sort_list;
}

}

Comment: You need to show us the code...
Comment: Why don't you profile your program.  Also post code like @SteveP. mentions
Comment: answer to such kind of questions should always be implementation determined.
Comment: Why are you constructing iterators for every single vertex?  Why not just as you need them, storing them in the stack?
Comment: Because I want to be able to keep track of which vertex in each adjacency list needs to be explored next.
Comment: Sure, but you don't need to construct an iterator for every single vertex every time.  Just construct them as you visit them, and maintain them in the stack.
Comment: ah Yes. So, I should take it out of the loops and construct the hashmap outside the for-loops and construct iterator object only when I have not seen the same vertex object before (using factory method). Am I correct ?
Answer: If you're talking about time complexity, the answer is that both of them are the same. Regardless of implementation, the runtime of DFS is O(V), because you should be visiting each vertex in the graph exactly once. Moreover, the runtime is also Omega(V), because you access all the vertices in the graph once regardless of input size. This leaves the runtime of DFS at Theta(V).
The overall DFS algorithm remains the same regardless of implementation. Therefore, the runtime of recursive vs. iterative DFS should both be the same, at Theta(V).


Configuring MariaDB to log to mysql.log using rsyslog

Question: I'm a little stumped - there is something obvious I'm missing here. Recently I made the switch from mySQL to mariaDB. Everything is working so far - except for the logging, as I realized today.
All the logs of mariaDB are going into the /var/log/daemon.log-logfile instead of /var/log/mysql.log - and I cannot, for the life of me, figure out why.
So, according to the my.cnf of mariadb
# Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf.
#
# we do want to know about network errors and such
log_warnings            = 2

the logging is configured in /etc/mysql/conf.d/mysqld_safe_syslog.cnf. This file contains these line:
[mysqld_safe]
syslog
syslog-facility = mysql

So, okay - that should be fine, right?
But ps -ef|grep logger shows:
logger -t mysqld -p daemon.error

So...what? Why? I really do not understand why it is taking the "daemon" facility?
Okay, so digging a little deeper - I found the following. When trying to test the logging by invoking the logger myself, I get the following:
$> logger -p mysql.error test
logger: unknown facility name: mysql.

Okay, I thought - although that makes no sense to me, just use local1 then for now. But doing so, in changing the value in the mysqld_safe_syslog.cnf to
syslog-facility = local1

changes exactly nothing:
$> ps -ef|grep logger
logger -t mysqld -p daemon.error

I looked around, but could not find any viable information on this topic. Can you help me out? How do I get mariadb to log somewhere else?
Answer: Well, that was easy - my init-script was borked:
# priority can be overriden and "-s" adds output to stderr
ERR_LOGGER="logger -p daemon.err -t /etc/init.d/mysql -i"

Changed it and everything is fine. Didn't come to think of actually checking the init script... well... next time ;)
Answer: For systems with systemd, we will need set an override to send log to syslog with the below directives
`[Service]
 StandardOutput=syslog
 StandardError=syslog
 SyslogFacility=local5
 SyslogLevel=err`

use systemctl edit mariadb for editing the mariadb startup. Then move all selector rules from /etc/rsyslog.conf to /etc/rsyslog.d/rules.conf (note: this is avoid duplication of logs due to default rsyslog select rules), inside /etc/rsyslog.d/rules.conf set the following content
#custom mariDB logging
if $syslogfacility-text == 'local5' or $programname == 'mysqld-scl-helper' or $programname == 'mysqld*' then {
        action(type="omfile" file="/var/log/mariadb/mariadb-error.log")
        action(type="omfwd" Target="syslogserver.com" Port="514" Protocol="tcp")
        *.* stop
}

# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.*                                                 /dev/console

# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none;local5.none                /var/log/messages

# The authpriv file has restricted access.
authpriv.*                                              /var/log/secure

# Log all the mail messages in one place.
mail.*                                                  -/var/log/maillog

# Log cron stuff
cron.*                                                  /var/log/cron

# Everybody gets emergency messages
*.emerg                                                 :omusrmsg:*

# Save news errors of level crit and higher in a special file.
uucp,news.crit                                          /var/log/spooler

# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log

Finally you will need to comment log-error directive from mariadb configuration as it might prevent sending complete log messages to remote syslog server.


equation of a line parallel to a given ine at a constant disance?

Question: what is the equation of a line parallel to a given line say y=x at a constant disance of 1 unit from it?
I guess there will be 2 equations,one above x axis and other below x axis
Comment: will the answer be y=x+root(2) and y=x-root(2)?
Comment: Equation of any line parallel to $ y=x $ is $ y=x+k $. Find $ k $ according to your requirement. Yes there will be two lines but not the way you described.
Comment: how to find k? using the information that it is at a distance of 1 unit from y=x?
Comment: You can use the formula for distance of a point $(x_1,y_1)$ from the line $ax+by+c=0$, which is given by $\frac{|ax_1+by_1+c|}{\sqrt{a^2+b^2}}$
Comment: The required lines are not $y=x+1$ and $y=x-1$ .. !!
Comment: how can they be y=x+1 or x-1!! not possible
Comment: yes they are not the answer ...find $k$ using the above formula
Comment: yes, it's correct
Answer: The distance of a point $P=(x_P,y_P)$ from a stright line of equation $ax+by+c=0$ is given by:
$$
d=\dfrac{|ax_P+by_P+c|}{\sqrt{a^2+b^2}}
$$
(see here)
so, a generic point $(x,y)$ at distance $1$ from the line is such that:
$$
\dfrac{|ax+by+c|}{\sqrt{a^2+b^2}}=1
$$
and , separating the two case for the absolute value, you have the equations of two stright lines.


Parent / Child component communication angular 2

Question: I am failing to implement action button in child_1 component but the event handler is in sub child component child_2 as shown in the following code:
app.component.html (Parent Html)

    Welcome to {{title}}!

  <app-navigation></app-navigation>

app.component.html (Parent Component)
import { Component } from '@angular/core';
import { ProductService } from './productservice';
import {Product} from './product';

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      title = 'MobileShirtShoeApp';
    }

app.module.ts (Main Module)
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Product } from './product';
import { ProductService } from './productservice';
import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { DataTemplateComponent } from './data-template/data-template.component';

@NgModule({
  declarations: [AppComponent,NavigationComponent,DataTemplateComponent],
  imports: [BrowserModule,HttpModule],
  providers: [ProductService],
  bootstrap: [AppComponent]
})

export class AppModule { }

navigation.component.html (Child 1 HTML)
<fieldset>
  <legend>Navigate</legend>

     <button  (click)="loadMobiles()">Mobiles</button>

  <app-data-template></app-data-template>
</fieldset>

navigation.component.ts (Child 1 Component.ts)
import { Component, OnInit } from '@angular/core';
import { ProductService } from '../productservice';
import {Product} from '../product';
import {DataTemplateComponent} from '../data-template/data-template.component';

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {
  error: string;
  productArray: Product[];

  constructor(private myService: ProductService){
    this.myService = myService;
  }

  dataTemplateComponent: DataTemplateComponent = new DataTemplateComponent(this.myService);

  ngOnInit() {
  }

  loadMobiles() {
   return this.dataTemplateComponent.loadMobiles();
  }
}

data-template.component.html (Child 2 HTML) (NOT DISPLAYING DATA)
<fieldset>
    <legend>Requested Data</legend>
    Welcome

                {{product.id}} {{product.name}} {{product.price}}

</fieldset>

data-template.component.ts (Child 2 Component) (Contains Product service calling code)
import { Component} from '@angular/core';
import {Product} from '../product';
import {ProductService} from '../productservice';

@Component({
  selector: 'app-data-template',
  templateUrl: './data-template.component.html',
  styleUrls: ['./data-template.component.css']
})

export class DataTemplateComponent  {
  error: string;
  productArray: Product[];
  constructor(private productService: ProductService) {
    this.productService = productService;
  }

  loadMobiles(){
    let promise  = this.productService.fetchMobiles();
    promise.then(productArr => {
        return this.productArray = productArr;
      }).catch((err) => {
       this.error = err;
      });
  }
}

ProductService.ts
import 'rxjs/add/operator/toPromise';
import {Http, HttpModule} from '@angular/http';
import {Injectable} from '@angular/core';
import {Product} from './product';

@Injectable()
export class ProductService{
  http: Http;
  constructor(http: Http){
  this.http = http;
  console.log(http);
 }

fetchMobiles(): Promise<Product[]>{
  let url = "https://raw.githubusercontent.com/xxxxx/Other/master/JsonData/MobileData.json";
  return this.http.get(url).toPromise().then((response) => {
        return response.json().mobiles as Product[];
    }).catch(this.handleError);
}

private handleError(error: any): Promise<any> {
  console.error('An error occurred', error);
  return Promise.reject(error.message || error);
}
}

Sorry if the code bothers you. So basically i am failing to display service data in child_2.html when an action made in child_1.html.The service working fine and name is ProductService which uses Product.ts as an object to get the data in JSON format. Any kind of help is appreciated.
Comment: just gona comment while I'm looking at this, you should try and get out of the habit of converting http calls to promises. There isn't ever aneed to do so.
Answer: This doesn't work because the DataTemplateComponent you're instantiating in app-navigation isn't the same instance of DataTemplateComponent as the one on the page.  It's a brand new one that you instantiated and that isn't bound to the page at all.  What you're trying to achieve is component communication.  Specifically, parent / child component communication.  There are a number of ways to do this, the cleanest and most flexible / extensible way is with a shared service pattern. Basically, you declare a service with an observable in it that you inject into both services and one updates the observable while the other is subscribed to it, like this:
@Inject()
export class MyComponentCommunicationService {
    private commSubject: Subject<any> = new Subject();
    comm$: Observable<any> = this.commSubject.asObservable();
    notify() {
        this.commSubject.next();
    }
}

Then provide this service, either at the app module or possibly at the parent component depending on needs then in app navigation:
constructor(private commService: MyComponentCommunicationService) {}
loadMobiles() {
   this.commservice.notify();
}

and in data template:
constructor(private commService: MyComponentCommunicationService, private productService: ProductService) {}
ngOnInit() {
    this.commSub = this.commService.comm$.subscribe(e => this.loadMobiles());
}
ngOnDestroy() { this.commSub.unsubscribe(); } // always clean subscriptions

This is probably a little unneccessary since you already have the product service there.  You could probably just move the load mobiles logic into the product service and have that trigger an observable that the data template service is subscribed to, and have the nav component call the load mobile method on the product service, but this is just meant to illustrate the concept.
I'd probably do it like this:
@Inject()
export class ProductService {
    private productSubject: Subject<Product[]> = new Subject<Product[]>();
    products$: Observable<Product[]> = this.productSubject.asObservable();
    loadMobiles() {
        this.fetchMobiles().then(productArr => {
            this.productSubject.next(productArr);
          }).catch((err) => {
            this.productSubject.error(err);
          });
    }
}

then nav component:
loadMobiles() {
   this.myService.loadMobiles();
}

then data template:
ngOnInit() {
    this.productSub = this.productService.products$.subscribe(
        products => this.productArray = products,
        err => this.error = err
    );
}
ngOnDestroy() { this.productSub.unsubscribe(); } // always clean subscriptions

Comment: this isn't a catch at all.  Both approaches work equally well, the second one is just simpler and cleaner.
Comment: I am taking up the second one right now. Let me try and get back. Thank you anyway.
Comment: Just saying, it does not matter where you instantiate the http service for either approach.  You may be misunderstanding what I've said to do, so you should ask questions if you're unclear.
Comment: Thank you for explanation @bryan60 but there is a catch since i am instantiating HTTP in ProductService.ts i needed to instantiate in the service in data-template.component. But i am trying to apply your approach right now.


Uniqueness of solution to linear first-order ODE with singular points

Question: I want to solve a linear first-order ODE for $y(x)$, $x\in[0,1]$,
$$ \gamma(x)y'-ay=-a\gamma(x),\quad y(0)=0, $$
where $\gamma(x)$ is a known function with $\gamma(0)=0$, and $a>0$ is a known constant.
Because $\gamma(0)=0$ makes $x=0$ a singular point, does this ODE have unique solution if additional condition $y'(0)=1$ is given? If yes, how to prove it (or is there any existing theorem showing this)?
Some background of my question: $F(x)$ and $f(x)$ are the distribution function and density function of random variable $X$ on support $[0,1]$. Let $y(x)=F(x)/f(x)$ and function $\gamma(x)=\frac{y(x)}{1+y'(x)/a}$ is known. I want to get the distribution of $X$ by figuring out function $y(x)$.
Answer: In general you cannot expect to have a solution. Consider the particular case $\gamma(x)=b\,x$. If $a\ne b$, then
$$
y(x)=\frac{a\,b}{a-b}\,x
$$
satisfies the differential equation and $y(0)=0$. If moreover $b=a/(a+1)$, then $y'(0)=1$. On the other hand, if $a=b$, then the general solution is $y(x)=C\,x+a\,x\,\log x$, which is not $C^1$ at $x=0$.
Now suppose that $\int_0^xds/\gamma(s)<\infty$ and let $g(x)=a\int_0^xds/\gamma(s)$. Then the general solution is
$$
y(x)=C\,e^{g(x)}-a\,e^{g(x)}\int_0^x\,e^{-g(s)}\,ds.
$$
There is only one solution with$y(0)=0$, namely
$$
y(x)=-a\,e^{g(x)}\int_0^x\,e^{-g(s)}\,ds.
$$
Wether it satisfies $y'(0)=1$ will depend on $a$ and $\gamma$.


Is the field item delta in the database reliable?

Question: Use case / background:

A node type "product".
A taxonomy vocabulary "feature". E.g. "color" and "size". (forgive the name, it has nothing to do with the features module)
Every product can have up to one value for each feature. E.g. color = green, size = big.

At first, this sounds like I should be using one (single-valued) field per feature, instead of a taxonomy. But this really does not scale, because there are going to be many many features, and new features can be dynamically added.
Another option would be a new entity type or bundle "node feature value". Or a new field type with two database columns, which stores both the tid of the feature, and the value.
But I thought, what if I use a regular text field with a custom widget? I would use the "delta" to store the feature tid, and the text value for the value.
Because, let's face it, the delta would be redundant anyway, if there can be only one value per product x feature.
The only question is, how reliable are the deltas? Can it happen that something will "normalize" the deltas to a regular continuous integer sequence 0..n ?
Answer: The answer is definitely "no", but it's a hard "no", not engine-dependent like it might appear. Under normal operation, the 0..n delta reset happens before the data is ever sent for storage.
If field values are saved using the API (field_attach_submit() etc), then they're unconditionally run through _field_filter_items():
function _field_filter_items($field, $items) {
  $function = $field['module'] . '_field_is_empty';
  foreach ((array) $items as $delta => $item) {
    // Explicitly break if the function is undefined.
    if ($function($item, $field)) {
      unset($items[$delta]);
    }
  }
  return array_values($items);
}

As you can see, any indices you might have manually set in the $items array will be discarded, and the resulting array will always be indexed 0..n. I don't think Drupal gives you another opportunity to affect that array before the data is persisted.
Comment: Oh, very good to know. I managed to save entities with custom field item deltas by directly manipulating the node and then calling node_save(). I could confirm in the database that the custom deltas were saved. But seems that this does not work when saving the entity through a form.
Comment: Hmm that's interesting, I think you've identified a core bug there. If the SQL storage module relies on them being 0..n when loading, then all paths to saving the field data (except for direct DB manipulation) should normalise the deltas, if only for consistency. The mongodb module has it the right way round IMO
Comment: The core sql storage normalizes them on loading. So it does not really "depend" on the deltas being normalized in the database. At least not in the code snippet I was looking at.
Comment: But yes, could be considered a core bug, if one time it normalizes, and another time it does not.
Answer: Turns out the answer is "no":
/**
 * Implements hook_field_storage_load().
 */
function field_sql_storage_field_storage_load($entity_type, $entities, $age, $fields, $options) {
  [..]
        // Add the item to the field values for the entity.
        $entities[$row->entity_id]->{$field_name}[$row->language][] = $item;

This code from Drupal 7 core, field_sql_storage.module shows that at least some parts of Drupal show no respect for the $delta when loading the entity.
On the other hand, look at this contrib field storage implementation in mongodb, in mongodb_field_storage.module:
/**
 * Implements hook_field_storage_load().
 */
function mongodb_field_storage_field_storage_load($entity_type, $entities, $age, $fields, $options) {
  [..]
            $field_values[$language][$delta] = $column_values;

So there are storage engines that do respect the field item delta.
But with these two examples, we have to assume that support for the $delta is very inconsistent, and far from reliable.
So for my original problem, there is no way around a custom field type. Too bad..
EDIT: Relation module might be another possible solution.
Comment: It's actually a bit tighter than that, just putting an answer in...


Are functional languages inherently more parallelizable than their OO or imperative cousins?

Question: I've been reading and thinking a fair bit about this. The buzz seems to be that in the multi-core future, functional languages will become more popular. I'm a relative noob to functional programming. My only exposure was academic, and nothing complicated enough to really put this class of language through its paces.
So, as I understand it, pure functions can be easily and transparently parallelized. This is a great feature, since it means no hassles with writing threading code. However, it doesn't appear to give much help with serial code.
Example:

fooN( ... (foo3(foo2(foo1(0)))))

Serial calls like this seem to be a common and sometimes unavoidable issue. To me these are at the root of why parallelization is so difficult. Some tasks simply are (or appear to be) highly serial. Does having a "functional mindset" allow you to better decompose some seemingly serial tasks? Do any existing functional languages offer transparent mechanisms for better parallelizing highly serial code? Finally, are functional languages inherently more parallelizable than OO or imperative languages, and why?
Answer: Functional languages are more parallelizable than imperative and OO languages because of pure functions.  However, you're absolutely right, if you have these kinds of data dependencies, you can't parallelize it.  The main value of functional programming is making the parallelism that is present in your code easier to spot and reason about because only data dependencies, not shared mutable state, can get in the way.
In fact, because most mere mortal programmers have difficulty working in purely functional languages, and because the Draconian policy of completely disallowing mutable state can be inefficient, there's been some buzz about the idea of allowing individual function bodies to be written imperatively, but disallowing side effects across functions.  In other words, all functions that are to be parallelized would have to be pure.  Then, you could have mutable state for local variables to make the code easier to write and more efficient, but still allow safe, easy automatic parallelization of calls to these pure functions.  This is being explored in, for example, the 2.0 branch of the D language.
Comment: Purely functional languages (with appropriate mondas) are the key to the future. And you don't need to be an immortal programmer to zen it. You just need to approach problems a little differently.
Comment: Disagree.  Mutable state that exists for short periods of time in small scopes, such as local variables for a function, is a good thing because it makes implementation of functions easier and more efficient.  When it becomes problematic is for things like member and global variables.
Comment: Easier is a subjective term.  I used to think as you did, now I think the opposite.  I was correct both times.
Answer: It is mainly about side effects. If the compiler knows that some pieces of the code has no side effects, it can optimize based on the code structure to run some of those in parallel.
Consider linq on C# / which is semi-functional:
var someValues = from c in someArray
                where // some  comparisson with no side effects
                select c;

You are specifying the intention of what you want to do, if the compiler knew each piece of the expression has no side effects, it could safely assign different parts of the array to process on different cores. Actually there is a .AsParalell that will be coming on parallel linq (plinq), that will enable just that. The issue comes in that it won't be able to enforce the no side effects bit (being on a language/framework that has no support for it), which can get really ugly if the developers aren't aware. Because of that, they made it explicit, but you can see that causing trouble along the way.


Multiple link local default gateway IPv6 addresses once IPv6 enabled

Question: We have a Windows Server 2012 r2 host. Whenever I enable IPv6 on the host, it gets three IPv6 addresses and 16 IPv6 link local default gateway addresses. Could anyone help me understanding how this could happen? It's working fine with this configuration, by the way.
ipv6 address 1: 2001:4898:e0:f242:203a:b75b:dfe4:28d6
ipv6 address 2: 2001:4898:e0:f242:99f0:411d:2166:74dc
ipv6 address 3: 2001:4898:e0:f243:203a:b75b:dfe4:28d6
another ipv6 link-local address
16 default gateway ipv6 addresses
1 default gateway ipv4 address
Comment: It would help if you provided the actual console output. How many network interfaces do you have? Have you enabled DHCP on the server as well as a router?
Answer: You said you get many default gateway addresses, are all these different gateways on the same device, or are they from many different devices?
If you are getting multiple different default gateways from many different devices, then you almost certainly have your Route Advertisement daemons running in a miss-configured way on those various devices you are seeing.
Comment: Thanks for the help. They are from the same device. All those ip addresses and gateways belong to one single network interface.


Python -Intersection of multiple lists?

Question: I am playing with python and am able to get the intersection of two lists:
result = set(a).intersection(b)

Now if d is a list containing a and b and a third element c, is there an built-in function for finding the intersection of all the three lists inside d? So for instance,
d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]

then the result should be
[3,4]

Answer: set.intersection(*map(set,d))

Comment: If the `d` variable may have a length of zero the `set.intersection` function will raise a `TypeError` exception. I would recommend catching that exception and return `set()` (an empty set) instead in that degenerate case. This is better than checking the `len` of `d` beforehand as it may be a generator.
Comment: Not sure what's wrong here. Now it gives me: `TypeError: intersection() takes exactly one argument (2 given)`
Comment: Thanks a lot. +1 for that. I just couldn't use it because of my Python version :(
Comment: @AaronR: Good point, but the degenerate solution for set intersection is the universal set, not the empty set.  since there's no compact way to represent that in python, raising an exception (probably catching the type error and raising something more sensible) is still probably the right way to handle it.  Returning an empty set *is* the right thing to do for set union, however.
Comment: @TokenMacGuy: Yes, you're quite right; by analogy with http://en.wikipedia.org/wiki/Empty_product it would be the only set which would be guaranteed to not change the result of an intersection.
Comment: This is briliant but a further explanation would be appreciated and useful.
Comment: @CesareIurlaro It's a built-in function... Documentation link => [Built-in Types — Python 3.9.6 documentation](https://docs.python.org/3/library/stdtypes.html#frozenset.intersection)
Answer: for 2.4, you can just define an intersection function.
def intersect(*d):
    sets = iter(map(set, d))
    result = sets.next()
    for s in sets:
        result = result.intersection(s)
    return result

for newer versions of python:
the intersection method takes an arbitrary amount of arguments
result = set(d[0]).intersection(*d[1:])

alternatively, you can intersect the first set with itself to avoid slicing the list and making a copy:
result = set(d[0]).intersection(*d)

I'm not really sure which would be more efficient and have a feeling that it would depend on the size of the d[0] and the size of the list unless python has an inbuilt check for it like
if s1 is s2:
    return s1

in the intersection method.
>>> d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]
>>> set(d[0]).intersection(*d)
set([3, 4])
>>> set(d[0]).intersection(*d[1:])
set([3, 4])
>>>

Comment: @Legend. Thanks for cleaning up my post. but remember: 'Thus spoke the Lord: "Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are the devil's apples!"'
Comment: @AaronMcSmooth: It gives me `AttributeError: 'list' object has no attribute 'intersection'` if I do that. Am I missing something?
Comment: @Legend. you have to map it to a set first. I somehow missed the fact that they were lists. After that, you can just pass lists (or any other iterable) to the `intersection` method
Comment: @AaronMcSmooth: Actually, not sure why but I'm getting this error no matter what solution I try: `TypeError: intersection() takes exactly one argument (3 given)`
Comment: @Legend. both my answer and TokenMacGuy's work for me on python 2.6 and 3.1
Comment: @AaronMcSmooth: Aah... Is there some solution for Python 2.4 by any chance?
Comment: @AaronMcSmooth: Today's a bad day. Sorry. When I define the intersection, it gives me: `UnboundLocalError: local variable 'set' referenced before assignment` I don't understand why it is considering set as a local variable.
Comment: @AaronMcSmooth: I edited your answer to something that works. Thanks for the help.
Comment: @AaronMcSmooth: Aye aye captain! Thou shall remember that for next time... Thanks! :)
Comment: Lobbeth thou thy holy space bar of Antioch.
Comment: I believe you made a typo:
`result = set(d[0]).intersection(*d[:1])`
should be:
`result = set(d[0]).intersection(*d[1:])`. Otherwise you're just getting the first list back.
Answer: @user3917838
Nice and simple but needs some casting to make it work and give a list as a result. It should look like:
list(reduce(set.intersection, [set(item) for item in d ]))

where:
d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]

And result is:
[3, 4]

At least in Python 3.4
Answer: You can get the intersection of an arbitrary number sets using set.intersection(set1, set2, set3...).  So you just need to convert your lists into sets and then pass them to this method as follows:
d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]
set.intersection(*[set(x) for x in d])

result:
{3, 4}

Answer: I find reduce() to be particularly useful. In fact, the numpy documents recommend using reduce() to intersect multiple lists: numpy.intersect1d reference
To answer your question:
import numpy as np
from functools import reduce
# apply intersect1d to (a list of) multiple lists:
reduce(np.intersect1d, [list_1, list_2, ... list_n])

Answer: Lambda reduce.
from functools import reduce #you won't need this in Python 2
l=[[1, 2, 3, 4], [2, 3, 4], [3, 4, 5, 6, 7]]
reduce(set.intersection, [set(l_) for l_ in l])

Comment: you require a list of set , this would fail saying that 'descriptor intersection requires set'

Python -Intersection of multiple lists?


how to call python method from odoo 9 javascript

Question: I have a piece of code to call the python method in javascript , but the code did not work , and an error will be show .i.e.
 error: Some modules could not be started
 Failed modules: ["group_js.costume"]
 Debug:  Object {group_js.costume: Object}

and my .py file is
class group_js(osv.osv):
  _name = "group_js"
  _description = "Group JS"
  _columns={
      'js' : fields.text('Javascript',required = True , store=True),
     }
 @api.multi
 def get_record(self):
     return [(i.js) for i in self]

my .js file is
odoo.define('group_js.costume', function (instance) {
     new instance.web.Model("group_js").call("get_record",[list_of_record]).then(function(result){
     console.log("hiiii");
   });
});

so i have no idea how to fix that , so please help me for fix this error .
Thanks
Answer: To call a method from the odoo python model you have Model().call() in javascript.
For example think of following model in py file.
class group_js(models.Model):
   _name = "model.example"
   _description = "Example model"

   def get_record(self):
       return ''

And from the javascript file you can call it as:
new Model("model.example").call("get_record",[args]).then(function(result){
    console.log(result);//show in console Hello
});

Here the further details of call method:
/**
 * Call a method (over RPC) on the bound OpenERP model.
 *
 * @param {String} method name of the method to call
 * @param {Array} [args] positional arguments
 * @param {Object} [kwargs] keyword arguments
 * @param {Object} [options] additional options for the rpc() method
 * @returns {jQuery.Deferred<>} call result
 */

Comment: where do you import Model from ?


testing-library/react how to test invalid inputs when they dynamically generate error message

Question: I am using Form in react. It has card number field. So if the user enters "333" and enters a tab, there is a dynamic message which shows up saying, "Card number needs to be a 16 digit number".
I am writing tests using @firstname.lastname@example.com and firstname.lastname@example.com.
Form Component:
CardForm.ts
users React-text-mask, Material UI to show an input which does validation by a schema which has a method to see if the input value is 16 or not and returns an error which is then displayed as helper text.
<form onSubmit={handleSubmit}>
<FormInput
  name="cardNumber"
  label="Card Number"
  inputMode="numeric"
  value={values.cardNumber}
  placeholder="XXXX-XXXX-XXXX-XXXX"
  validation={validationSchema.cardNumber}
  mask={formMasks.cardNumber}
/>
<Button
  type="submit"
  disabled={!values.card || validationSchema.cardNumber.errors.length === 0}
>
  CONFIRM CARD
</Button>
</form>

CardForm.test.tsx
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import { CardForm } from '../components/Forms/CardForm';

const setup = () => {
    const utils = render(<CardEmailForm />);
    const input = utils.getByPlaceholderText('XXXX-XXXX-XXXX-XXXX');
    return {
        input,
        ...utils,
    };
};

test('show error message when card number entered is less than 16 digits', async () => {

    const { input, ...utils } = setup();

    fireEvent.change(input, {
        target: { value: '333' }, // I am giving the value 333 to the input
    });

    expect((input as HTMLInputElement).value).toBe('333 -    -    -    '); //works

    /* if I lose focus from the input, the error message shows up as helper text at the bottom of the input as shown above */
    fireEvent.blur(input);

    /* now I am just expecting to read the error from the DOM based on h6 helper text, but this keeps giving me ERROR. */

    expect(await utils.getByRole('heading')).toHaveTextContent(
        'Card Number should be 16 numbers'
    );
});

ERROR!

 > 29 |     await screen.getByRole('heading');
         |               ^
      30 |  expect(screen.getByRole('heading')).toHaveTextContent(
      31 |      'Card Number should be 16 numbers'
      32 |  );

      at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:34:12)
      at getMultipleElementsFoundError (node_modules/@testing-library/dom/dist/query-helpers.js:21:35)

Can someone help me write the expect statement so that once I give wrong input and then blur, I am able to read the error off the screen?
Answer: If you are using MUI inputs/forms, I believe the helper text is wrapped in an HTML paragraph element:

Incorrect entry.


$A$ and $B$ are $3\times 3$ real matrices such that $\operatorname{rank}(AB)=1$, then $\operatorname{rank}(BA$) can not be which of the following?

Question: I was thinking about the problem that says:

If $A$ and $B$ are $3\times 3$ real matrices such that $\operatorname{rank}(AB)=1$, then $\operatorname{rank}(BA)$ can not be which of the following?
  (a) $0$
  (b) $1$
  (c) $2$
  (d) $3$.

My attempt: I have chosen suitable $3 \times 3 $ matrices for $A$ and $B$ keeping in mind that $\operatorname{rank}(AB)=1$. Say for example if I take $A$ and $B$ to be
$$A = \begin{pmatrix}
1 &2  &0 \\
0 & 0 &0 \\
0 & 0 &0
\end{pmatrix}$$
and
$$B = \begin{pmatrix}
-2 &1  &0 \\
1 & 0 &0 \\
0 & 0 &0
\end{pmatrix}$$
respectively, then I see $\operatorname{rank}(AB) = \operatorname{rank}(BA) = 1$. So, option (b) can not be correct. Do I have to keep choosing the matrices and then observe which of the option holds good. Is this kind of approach right to tackle the problem? I am looking for a direct way (e.g. application to some theorem) which can give me the result. I have also noticed that $AB$ and $BA$ are similar matrices as we see that $A^{-1}(AB)A=BA$. Is this observation going to help me in any way? Thanks in advance for your time.
Comment: How do you know det$A\neq0$?
Comment: Thanks for pointing out..Yes ,indeed det($A$) can be zero.
Answer: If you only want to solve the problem, then as the others have pointed out, (d) is impossible and hence the answer is (d). It is helpful, however, to constuct some examples to convince yourself that (a)-(c) are really possible (this is also a sanity check against misprints). For this purpose, you may consider the matrices
$$
A=\begin{pmatrix}1\\&1\\&&0\end{pmatrix},\ B=\begin{pmatrix}b&0&1\\0&0&0\\0&c&0\end{pmatrix}.
$$
Then $\operatorname{rank}(AB)=1$. Now you may try to choose some appropriate values of $b$ and $c$ to make $\operatorname{rank}(BA)$ equal to $0,1$ or $2$.
Comment: How we can choose b and c for rank (BA)=2?
Comment: @MeetPatel Can you calculate $BA$?
Comment: i didnt tried . i just cmnt through logic, btw how you create such two matrix? by just try and error or you used something tricky ?
Comment: @MeetPatel Let $A$ be fixed. If there exist three examples of $B$ such that $\operatorname{rank}(AB)=1$ in all three examples but the respective values of $\operatorname{rank}(BA)$ are equal to $0,1$ and $2$, then $A$ must be of rank 2. Therefore $A$ is equivalent to the matrix in my answer. Now it becomes easier to construct $B$.
Answer: According to these properties of ranks listed on Wikiepdia :
http://en.wikipedia.org/wiki/Rank_(linear_algebra)
If $A$ is $m \times n$

$\operatorname{rank}(AB) \leq \min(\operatorname{rank}(A), \operatorname{rank}(B))$ if $B$ is $n \times k$
$\operatorname{rank}(AB) = \operatorname{rank}(A)$ if $B$ is $n \times k$ of rank $n$

Note that in your situation $m$, $n$ and $k$ is $3$
By property (1) the only way to have $\operatorname{rank}(BA) = 3$ is to have both $\operatorname{rank}(A) = 3$ and $\operatorname{rank}(B) = 3$. Since $\min(\operatorname{rank}(A), \operatorname{rank}(B)) = \min(\operatorname{rank}(B), \operatorname{rank}(A))$.
But in that situation, we can apply property (2): $B$ is $3 \times 3$ of rank $3$ and so $\operatorname{rank}(AB) = \operatorname{rank}(A) = 3$.
So you can't have at the same time $\operatorname{rank}(BA) = 3$ and $\operatorname{rank}(AB) \neq 3$ using $3 \times 3$ matrix only.
Thus answer (d) is correct.
Comment: thanks a lot.I have got it.
Answer: This question has lots of good answers.But I just want to share a very short answer.It may already be discussed in the previous answers,so really sorry to answer again.
$AB$ is a $3\times 3$ matrix,rank$(AB)=1\ne3\Rightarrow AB$ is not of full rank$\Rightarrow \operatorname{det}(AB)=0\Rightarrow \operatorname{det}(BA)=0\Rightarrow BA$ is not of full rank$\Rightarrow$rank$(BA)\ne3$
Answer: The answer is (d), i.e. if $rank(AB)=1$, then $rank(BA)$ cannot be $3$. Let's prove it by contradiction. Suppose $A, B$ are $3\times 3$ matrices such that $rank(AB)=3$, then $AB$ is invertible. This implies that $A$ and $B$ are invertible (otherwise, if $A$ is not invertible, then $A$ could not be full rank, i.e. $rank(A)<3$. This would imply that $rank(AB)\leq rank(A)<3$, which contradicts $rank(AB)=3$. Similarly you can prove that $B$ is invertible). Then $BA$ is invertible since product of invertible matrices is invertible. This implies that $rank(BA)=3$, which contradicts to the assumption that $rank(AB)=1$.
To see that (a), (b), (c) are possible, we can construct some examples of $A$ and $B$. As you have shown that (b) is possible (In fact, we can just take $A$ to be any rank 1 matrix, i.e. $rank(A)=1$ and $B$ to be the identity. Then $AB=BA=A$ has rank $1$).
I will leave other cases to you.
Comment: i have one question.If i want to prove it by contradiction,then should not i keep the condition that $rank(AB)=1$ intact and then take the supposition that if possible let us assume that $rank(BA)=3$ and then finally see what happens? with regards..
Comment: @Paul: Is (a) possible? For rank$(BA)=0\implies BA=0\implies (AB)^2=0\implies$ rank$(AB)^2=0\implies$ min{rank($AB$), rank($AB$)} $ =0\implies$rank $(AB)=0.$


WordPress: Echo Javascript for Google Ads Conversion Page

Question: I'm trying to add some Javascript coming from Google for Ad Conversions on the thank you page. So this script should only appear on one page. Trying to use an if statement in PHP to echo the code but running into errors. This is what I currently have (with the Google ID replaced with something generic):
<?php if ( is_page( 'thankyou' )) {
    echo '';
?>

The first and third echo's are fine but the middle one is not. What might be the proper fix?
Answer: You need to escape the single quotes in the brackets of gtag().
Try echo 'gtag(\'event\', \'conversion\', {\'send_to\': \'AW-12345678901234567890123456\'});' instead.
Answer: Your second echo line breaks your string.
You have 2 options to fix this:
1. Change the inner quotes to double quotes
echo 'gtag("event", "conversion", {"send_to": "AW-12345678901234567890123456"});';

2. Break out of the quotes.
You can use back slashes to not break out of your main string.
echo 'gtag(\'event\', \'conversion\', {\'send_to\': \'AW-12345678901234567890123456\'});';

I have also noticed on the second echo you were missing a semi colon.
Source: PHP-Strings
Comment: Thanks to the both of you for the answers. Unfortunately, all the ideas brought up the WSOD. Put WP  DEBUG on and got the following:

 Parse error: syntax error, unexpected end of file in /home/hellod8/public_html/wp-content/themes/mytheme/header.php on line 99
Comment: @AdamBell did you close your if statement. In your code snippet you are missing a }


Simplifying presentation of elements of finite field

Question: Let me describe my question through an example. Finite field of order (for example) 8 can be constructed as $\mathbb{F}_8 = \mathbb{F}_2[t]/(t^3 + t + 1)$. So one of a natural presentation of the field is the following.
$$ \mathbb{F}_8 = \{0, 1, t, t + 1, t^2, t^2 + 1, t^2 + t, t^2 + t + 1\} $$
On the other hand, since the multiplicative group of the field $\langle \zeta \rangle$ is cyclic, the following is also a presentation of the field (as GAP do).
$$ \mathbb{F}_8 = \{0, 1, \zeta, \zeta^2, \zeta^3, \zeta^4, \zeta^5, \zeta^6 \} $$
Is there a handy way to get the later presentations from the former ones?
Of course, I can rewrite all the later presentations by relation $t^3 = t + 1$ in advance. But what I would like to do is calculating the later presentation directly when I needed (e.g. when I get the former presentation from matrix multiplication). I would appreciated it if you show me an algorithm for this.
Thank you.
Edit: I rewrite $t$ in the second presentation to $\zeta$. I would also appreciated if you show me a way to find out a primitive $\zeta$ in terms of $t$ (though as DonAntonio already commented, perhaps there is no hope to do so in general).
Comment: I don't think there's a general way to know *in general* what a *primitive element* (i.e., generator of the multiplicative group of a finite field) is. The best you can hope for is precisely doingwhat you did...and **distinguish** between your $\;t$'s !
Comment: Ok now: in **this particular** case, @Taro, there is no problem: since $\;|\Bbb F_8^*|=7\;$ is a prime, *any* non-zero element different of $\;1\;$ is a generator... In the case, for example, of $\;\Bbb F_{16}\;$ you'll already have more options, since $\;\Bbb F_{16}^*\;$ is a group of order $\;15=3\cdot 5\;$ and thus it has *only* $\;2\cdot 4=8\;$ generators. The fastest, general way I can think of checking is take a non-unit element $\;x\;$ and check whether $\;x^3\neq 1\,,\,\,x^5\neq1\;$...and then you have a generator! :) . For other cases this may take a longer while, of course.
Comment: FWIW: Whenever I run computer calculations involving a finite field, say $\Bbb{F}_{4096}$ or some such, the first thing the program does will be to build look-up-tables going back and forth from one presentation of elements to the other. This is needed e.g. to speed up multiplication in the field. All because this is the easiest way. For all but [the smallest fields](http://math.stackexchange.com/a/591254/11619), in which case I (used to ?) have those table memorized, this is essentially the only way. Probably GAP does it that way, too.
Comment: You can get away with using a single look up table, if you use Zech logarithms. Then everything else is reduced to integer arithmetic. I prefer not to do my implementations that way, because with your first presentation addition (in characteristic two) becomes bitwise XOR, which is too efficient to pass up.
Comment: Even in the case of a field of prime order $p$, there is no easy way to get from the representation $\{0,1,2,\dots,p-1\}$ to the representation $\{0,1,g,g^2,\dots,g^{p-2}\}$; there no simple formula that gets you $g$ from knowing $p$. This is closely related to the "discrete logarithm problem"; cryptosystems have been based on the difficulty of solving this problem.
Comment: The $t$ in the first is not the same as the $t$ of the second, no?
Comment: @JérémyBlanc I'm not sure what happens in general. In this case, however, the first $t$ and the second $t$ is the same.
Comment: Ah OK. Seems like a coincidence. If you could prove that the same $t$ works, then you have the answer to your problem in general, which does not seem really possible as DonAntonio says.
Comment: @Taro, you have $\;t^3=t+1\;$ , so it doesn't seem logical to write *with the same* $\;t\;$ both sets as you did...and it is also a coincidence, as already noted by Jeremy.
Comment: @DonAntonio Thank you for your comment and answer. I edited my question.
Answer: You can directly check that, talking of the multiplcative group of the field $\;\Bbb F_8\;$ ,we have that $\;ord(t+1)=7\;$ , and thus you can define
$$w:=t+1\implies \Bbb F_8=\{0,1,w,w^2,w^3,w^4,w^4,w^6\}$$
Again, in your post: the first $\;t\;$ (4th line) and the second $\;t\;$ (7-th line) are not necessarily the same, though in this case, passing from one representation to the other, works.
Comment: Though I casually ask this question (because the former presentations are a bit space consuming), hoping if there are some nice algorithm, now I understand it is much harder than I expected from comments of you and others.


How to use PyCharm as a GIT diff tool from the command line?

Question: On the PyCharm Help Website I see you can use PyCharm as a diff tool from the Command Line to compare two files. That's awesome! However is there a way to take it a step further and use it as a git diff tool.
So I can just type pycharm diff file_name.py and get the GIT differences same way you would if you were on PyCharm have setup the GIT integration and press CTRL + D to see the differences.
Answer: Yes you can.
First you need to enable the command-line launcher:

To enable invoking PyCharm operations from the command line, follow
  these steps

On macOS or UNIX:

Make sure PyCharm is running.
On the
  main menu, choose Tools | Create Command-line Launcher. The dialog box
  Create Launcher Script opens, with the suggested path and name of the
  launcher script. You can accept default, or specify your own path.
  Make notice of it, as you'll need it later.
Outside of PyCharm, add the path and name of the launcher script to your path.

On Windows:

Specify the location of the PyCharm executable
  in the Path system environment variable. In this case, you will be
  able to invoke the PyCharm executable and other PyCharm commands from
  any directory.

https://www.jetbrains.com/help/pycharm/running-pycharm-as-a-diff-or-merge-command-line-tool.html
Then add the following lines to your ~/.gitconfig:
[diff]
        tool = pycharm
[difftool "pycharm"]
        cmd = /usr/local/bin/charm diff "$LOCAL" "$REMOTE" && echo "Press enter to continue..." && read
[merge]
        tool = pycharm
[mergetool "pycharm"]
        cmd = /usr/local/bin/charm merge "$LOCAL" "$REMOTE" "$BASE" "$MERGED"
        keepBackup = false

(for Windows users these details might be slightly different)
Comment: FYI to all, the Jetbrains Toolbox takeover of making the command line tools has chosen to rename the `charm` script to `pycharm`
Comment: This also allows you to use Pycharm as your git *merge* tool, with `git mergetool -- /my/unmerged/file`.
Comment: @Noumenon indeed, this is mostly what I use it for! I just wish it wasn't so painfully slow to start up, and didn't have to close and re-open for each individual file in the merge conflict...
Comment: I just do all of my merging and rebasing using Pycharm as my Git client, even for Java. This trick is only for files other people committed without finishing the merge.
Comment: Anyone, here's the relevant docs to understand the `.gitignore` file syntax: https://git-scm.com/docs/git-config#_configuration_file.


Proof closure of $\mathbb{Z}$ under addition, especially that $m+(-n) \in \mathbb{Z}$ with $m\in\mathbb{N}, n\in\mathbb{N}$

Question: I need help with the following task:
Prove that $\mathbb{Z}$ is closed under addition
We define the set of integers as $\mathbb{Z}$= {${n:n\in\mathbb{N}}$} $\cup$ {$0$} $\cup$ {$-n:n\in\mathbb{N}$}. Also $0$ $\notin$ $\mathbb{N}$
The additon of integers, defined as the sum of two integers (or the result we get on adding two or more integers), has the following properties:
A1) $x+(y+z)=(x+y)+z$ $\forall x,y,z \in \mathbb{Z}$
A2) $x+y=y+x$ $\forall x,y,z \in \mathbb{Z}$
A3) There exists exactly one element $0$ $\in \mathbb{Z}$ with the property $x+0=x$ $\forall x\in \mathbb{Z}$
A4) For each $x\in\mathbb{Z}$ there exists exactly one element $-x\in\mathbb{Z}$ with the property $x+(-x)=0$
It seems to be a very easy task. Unfortunately I don't have a clue how to prove the case that $$m+(-n) \in \mathbb{Z}   ,( m\in\mathbb{N}, n\in\mathbb{N})$$
I found posts here were people simply answered, yeah m+(-n) = m-n and the difference of two natural numbers is an integer. But without a proof, this is not sufficient and unfortunately I didn't found any proof for this. We obviousle have to differentiate between thre cases: m>n, m=n, m<n. I wanted to prove this task with help of induction, since it helped me for my proof that $\mathbb{N}$ is closed under addition. But in this case, it gets complicated.
Anyone an idea, how to prove this easily? I am thankful for any advice.
Comment: You gave the definition of $\mathbb Z$, but not the definition of addition of integers.
Comment: "The addition of integers, defined as the sum of two integers (or the result we get on adding two or more integers" - this is extremely circular and doesn't define a thing. You must instead construct $\Bbb Z$ from $\Bbb N$ in the usual manner (find it on Wiki) and observe the construction of addition. Then you can show the result. As it stands you don't have any definitions that make the question provable. In fact, axioms $A1-A4$ assume that $x+y\in\Bbb Z$ implicitly already...
Answer: I think at the very least you should assume this property from the naturals, this is the one derived directly from the successors definition.
$$m\ge n\implies \exists a\in\mathbb N\mid m=n+a$$
Then you can proceed from the axioms you gave:
$m+(-n)=(n+a)+(-n)\,\stackrel{A_1}{=}\,(n+(-n))+a\,\stackrel{A_4}{=}\,0+a\,\stackrel{A_2}{=}\,a+0\,\stackrel{A_3}{=}\,a\in\mathbb Z$
For the case $m\le n\ $ or $\,n=m+a$ you have to prove first that: $$-(m+a)=(-m)+(-a)$$
$(m+a)+(-m)+(-a)=(m+(-m))+(a+(-a))=0+0=0$
And then proceed the same way as before:
$m+(-n)=m+(-m)+(-a)=0+(-a)=(-a)+0=(-a)\in\mathbb Z$


Debugging the minlength validation jquery program

Question: I wrote a jquery program for validating minlength but it is not working.
I dont know how to solve that 'select_this' problem in there.
I am a beginner in jquery.

$(document).ready(function(){
 $('input[type="text"]').on('focus',function(){
  var select_this = $(this);
  minlength = select_this.attr('mLength');
  if(minlength != 0 && minlength > 0 && select_this.val().length < minlength ){
   select_this.after(''+ minlength +' characters are required. ');
  }
 }).keyup(function(){
  if(select_this.val().length >= minlength ){
   select_this.next().remove();
  }
 }).blur(function(){
  select_this.next().remove();
 });
});

      5<input type="text" mLength="5" />

      10<input type="text" mLength="10" />

Answer: the scope of your variable
var select_this = $(this);

inside the focus event handler is available inside that handler function only, if you need to access it in other events handler functions  then declare it there as well.

$(document).ready(function(){
 $('input[type="text"]').on('focus',function(){
  var select_this = $(this);
  minlength = select_this.attr('mLength');
  if(minlength != 0 && minlength > 0 && select_this.val().length < minlength ){
   select_this.after(''+ minlength +' characters are required. ');
  }
 }).keyup(function(){
        var select_this = $(this);
  minlength = select_this.attr('mLength');
  if(select_this.val().length >= minlength ){
   select_this.next().remove();
  }
 }).blur(function(){
        var select_this = $(this);
  select_this.next().remove();
 });
});

      5<input type="text" mLength="5" />

      10<input type="text" mLength="10" />


What's the difference between these two sets of nylon strings (Folk vs non-folk)?

Question: I was looking for nylon strings and noticed that Ernie Ball has two different sets available that are both gauge 28 to 42 and have ball ends.
One is sold as "Ernesto Palla" Nylon, the other as "Earthwood Folk Nylon".

What is the difference? Does "Folk" imply a particular tone?
Answer: The top package has silver and/or nickel windings on the bottom three strings, the bottom package has 80/20 bronze windings on the bottom three strings. That's why the packages have those words on the front.
I'm not sure but I expect the top package has a brighter tone and is intended for classical style guitar. The bottom package probably has a darker sound that might be used more with folk, rock, and pop style playing.
Answer: The term "folk guitar" is often used to describe a guitar which is designed for use with nylon strings like a classical guitar, but has a string spacing closer to that of an acoustic guitar and for whatever reason uses a tailpiece with notches for ball-end strings rather than one which is suitable for tying plain-end strings.  This latter "feature" has unfortunately resulted in many such instruments being strung with ball-end steel strings and consequently destroyed by the higher string tension.
Using plain-end nylon strings on a folk guitar would require affixing some sort of blobby thing at the end; I would guess that sliding on a bead and then using the flame from a match to melt the nylon string into a blob would probably work, but I've never tried that.  Using ball-end folk guitar strings is probably a much easier approach.  Tying the knot required for a classical guitar might be awkward with a ball-end string, but cutting off the ball end should yield a plain-end string suitable for use with a classical guitar that would otherwise have trouble with a ball-end string.
Comment: I have an ukulele with those bridge slots. There are ball end strings for those, but overhand knot works just fine.


JSONP callback out of order

Question: I apologise if this is a repeated question. I have done my research but I am still unable to come up with an answer:
I am writing a small JSONP API. The desired outcome:

The programmer creates an instance of the JSON class.
var json = new jsonpRequest (

"http://url.to.web_service",

searchParam //passed in as an associative array

);

The programmer then declares var myJSON = jsonpRequest.getJsonP()

This will return the JSONP into the myJSON variable to be processed.
The API successfully takes in the parameters when the instance of the class is constructed, generates a link to the services w/ the desired parameters and injects it into the DOM via script tags using this function:
jsonpRequest.prototype.fetchJsonp = function(){

    var request = that.getRequest();

     //creates a script element

     var jsonpCall = document.createElement('script');

     //gets jsonp request
     jsonpCall.src = request;

     //adds script to DOM, which goes on to request the JSONP from the service.
     document.head.appendChild(jsonpCall);

};

EDIT: For the sake of clarity: this definitely does return the data set that is requested.
The function I am using as my callback is:
jsonpRequest.prototype.processCallback = function(data){

    alert(data);
    that.setListOfResults(data);

};

It is called in the link as: &callback=jsonpRequest.prototype.processCallback
The processCallback function takes in the data from the request and stores it in a variable within the class using the setListOfResults function.
After the data has been stored I would like to return the data from the request to the myJSON variable. This is the getJsonp function that the programmer invokes in step 2 of the process:
jsonpRequest.prototype.getJsonp = function(){

    that.buildRequest();
    that.fetchJsonp();

    return that.listOfResults;

};

The issue:
Here is what I am calling after I define my JSON API class:
         var myJSON = json.getJsonp();

         console.log(myJSON);

Because it is asynchronous, it is moving on to the console log before the callback function is invoked, resulting in MYJSON to be undefined. I am not sure how I can daisy chain my code together in such a way where it runs the callback before moving on.
I tried to emulate the solution from How can I get this JSONP call to return a value?. I may be missing a step or I am perhaps ignorant of something! Any help to clarify this would be greatly appreciated. Thank you in advance :).
P.S. I would like to avoid using JQuery etc... It would be beneficial to keep this strictly as raw JavaScript.
Comment: In order to see the value of `myJSON` you'll have to wait until the server response comes back. Try testing with a `setTimeout`. You can't setup a variable with asynchronous data and immediately expect the result.
Comment: Hey there hitautodestruct, thanks for the suggestion :). I was aware of `setTimeout` being a possible solution. It's a perfectly valid solution. However, I was reluctant to do so after the points Relfor made in http://stackoverflow.com/questions/17465011/how-can-i-get-this-jsonp-call-to-return-a-value. Still, I could perhaps implement `setTimeout` as a fail safe for if the server is not responding :). Thanks!
Comment: Hey, just an FYI the setTimeout is not a good solution since you never know exactly how much time it will take the server to respond. I suggested it merely for testing purposes.
Comment: Hey, yeah that was my hang up with it too, thanks for suggesting it for testing purposes though!
Answer:
I am not sure how I can daisy chain my code together in such a way where it runs the callback before moving on.

You can't do that. You must rely on callbacks. Add a callback parameter to your jsonpRequest constructor, and invoke that callback after you do setListOfResults(data). You may also wish to allow for setting the this context in which the callback will be executed.
jsonpRequest.prototype.processCallback = function(data){

    alert(data);
    that.setListOfResults(data);
    that.callback.apply(that.context, [data]);

};

Comment: Thank you! This makes perfect sense - I had an a-ha moment after I read it, it made the process make much better sense. I implemented the code, went to try it and the server seems to have gone down! Ha ha. I will check the code ASAP and I'll mark this as answered if it all works :)
Comment: Worked like a charm. Thanks very much for helping me get the process in my head :).

JSONP callback out of order


Difference between set IFS as $'\n' and $' \n'

Question: #!/bin/bash

show="ls -al /"
IFS=$'\n'
$show

The result is like bash: ls -al /: No such file or directory.
The shell cannot return expected result.
If I change IFS as $' \n' (notice I added a space), it is ok.
I do not have much knowledge about IFS, could someone explain it?
Comment: http://mywiki.wooledge.org/WordSplitting
Answer: In the first case:
show="ls -al /"
IFS=$'\n'
$show

The whole string ls -al / is being treated as the command name by shell, since IFS doesn't have a space in it and spaces in your variable don't induce word splitting.  It is as good as writing the command as "$show" which completely suppresses word splitting.
In the second case, word splitting does happen since space is a part of IFS.

See also:

How does IFS work in Bash?
Word splitting in Bash with IFS set to a non-whitespace character
BashFAQ/050 - I'm trying to put a command in a variable, but the complex cases always fail!
Comment: i change IFS to read file each line as below:
`a:1 \n
b:2`
I do not know a good way to read it with bash, do you have a good idea?


How Do These Decorative Chords Contribute to Diatonic Modulation in Aldwell and Schachter's Example?

Question: I'm studying diatonic modulation via example (e) in Unit 26 of "Harmony & Voice Leading" by Aldwell and Schachter and need some clarification. The progression moves from an F major to an E7 - Am cadence. While I grasp the overall concept of leading to an authentic cadence, I'm struggling to distinguish between the functional chords driving the modulation and the decorative ones.
Could someone please explain the inclusion of non-essential chords within this progression? I'm interested in understanding the progression as a whole, as each chord contributes to the progression's flow and harmonic richness.
Many thanks.
Comment: What leads you to believe any of the chords are non-essential, since that factor isn't mentioned in the exercise's description.
Comment: @Aaron great point--I guess I thought it was implied, since they say that the options they present are not the only ones and because they don't explain every chord.  I see they refer to the I, V, II and/or IV chords, but they dont elaborate on the use of inversions as seen, for example, in the 4th and 6th chords in the progression
Comment: Okay, I think that clarifies things, for me at least. Thanks.
Answer: As a starting point, here's a RNA of the passage:
VI  ii[6-5]  V[4-2]  i[6]  ii[6]  Cad[6-4]  V[7]  i.

Clearly the final V-i is essential, since it most strongly states A minor. There is a weaker V-i between chords 3 and 4, but, by nature of the inversions involved, and it's placement between two predominant chords on either side (chords 1, 2 and 5, 6), it doesn't really serve a cadential function. Instead, one can interpret the first six chords as a prolonged predominant.
By that interpretation, one might conclude something along the lines of

Chord 1 is essential, by definition of the exercise.
Chord 6 is essential, being the predominant immediately leading to the dominant.
Chords 7 and 8 are essential, comprising the cadence confirming A minor.
The remaining chords are non-structural, comprising an extended predominant transitioning from the VI chord to the Cad[6-4] chord.


Setting up REST post request

Question: I am having issues sending a POST request to create a node with Drupal 8 Core REST. Here are the steps I have went through several times. Note that these steps are in effort to produce a working example, I am not worried about the security implications as of yet.

Install latest version of drupal 8
Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization)
Go to permissions page. Find RESTful Web Services permissions and allow delete, get, patch, and post for all users. Find Node Article permissions, allow create, delete and edit for all users.
Launch Dev HTTP Client in Chrome. Input the following request:

After hitting Send, I receive the following message which I believe should be a 201 and not a 200 if a node were to successfully be created. I think the REST part is working, its just I cant seem to figure out how to get POST to create a node.

I am having trouble finding any documentation on making post requests to Drupal 8 REST. Insight into how to construct these requests so that Drupal can parse them successfully would be very helpful.
Comment: When I was fiddling with D8 REST I had to change the hal+json to json in some configuration file and then it started to work. I was never able to get hal+json format working.
Comment: do you recall what file it was you edited? did you edit it preinstallation or postinstallation? Did it result in being able to create nodes? If so what would a POST request to create an article look like?
Comment: https://www.drupal.org/node/2076725
Comment: I forked original module and fixed this bug and pull request. I hope accept this branch.
You can download it in https://github.com/setali/drupal_cors
Answer: As I still ran into a lot of 403 errors, I'll summarize my overall solution (Drupal 8.0.1).
Setup and configuration
Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization). Enable the relevant permissions of RESTful Web Services and for creating the relevant Nodes.
Get a CSRF token
GET http://your-drupal8/rest/session/token
POST to create a new node
POST http://your-drupal8/entity/node?_format=hal+json
Note that the URL for POST seems to be /entity/node rather than /node.
Headers
Authorization: Basic QWRt...
X-CSRF-Token: zCf...

Data
{
"title": [
  { "value": "atest2" }
],
"type": [
  { "target_id": "article" }
],
"_links": {
  "type": { "href": "http://your-drupal8/rest/type/node/article" }
}
}

Comment: How do you get the value for the `Authorization` header? I thought Basic meant you pass in `username:password` as the value.
Comment: Couples question: 1) Do you need an authorization header if you allow anonymous users to create articles and perform post requests? 2) Don't you need a 'Content-Type': 'application/hal+json' in the header as well?
Comment: I've been trying to sort this out for ages and this still does not work for my local dev site. I have enabled *|* on CORS, allowed GET & POST for content in the REST-UI and I keep getting a 500. Any ideas what else could be required?
Answer: I posted the solution on the (identical) issue on drupal.org:
https://www.drupal.org/node/2472451#comment-9903259
Also see the Dev HTTP Client screenshot attached in that comment.
Basically there are a couple of things wrong in your example:

endpoint is /entity/node
add Accept header "application/json"
add CSRF token (which can be requested via /rest/session/token)
Comment: I tried the very same thing but, returns 415
Comment: just got the 201 from your instructions. thank you.
Comment: Accept headers are no longer used: https://www.drupal.org/node/2501221 - Instead use `?_format=json` in the query string for the URL.
Comment: @tyler.frankenstein I thought post requests only accepted hal+json

Setting up REST post request


ellipsis does not work for few words

Question: I have following css for ellipsis. It works for few texts. But for few texts it does not work.
Note - this is for a two line
Please help
.myclass {
    max-width: 210px;
    width: 290px;
    height: 3em;
    min-height: 3em;
    overflow: hidden;
    text-overflow: ellipsis;
    overflow: hidden;
    display: block;
}

Comment: Can you made snippet ?
Comment: _"It works for few texts. But for few texts it does not work."_ Makes no sense whatsoever
Comment: My text is very long. when it goes to second line ellipsis does not work
Comment: May be you should give this a try... https://codepen.io/martinwolf/pen/qlFdp
Answer: Use Following code

Lorem Ipsum is simply dummy text of the printing and
   typesetting industry.

ellipsis does not work for few words


JavaScript remove an IIFE event listener

Question: I'm trying to remove click events from a list of id's after adding them with an IIFE like this
function setupPlayer(player){
  var squareState = {};
  for (i = 0; i < allSquares.length; i++) {
      if(allSquares[i].innerHTML === "") {
        // set up a click event for each square
         document.getElementById(allSquares[i].getAttribute('id')).addEventListener('click', (clickSquare)(i));
      }
    }
}

The clickSquare function returns
function clickSquare(i){
  var num = i;
  return function() {
      document.getElementById(allSquares[num].getAttribute('id')).innerHTML=player;
  }
}

Then I try to remove them with
function removeClickEvents(){
  for (let i = 0; i < allSquares.length; i++) {
    document.getElementById(allSquares[i].getAttribute('id')).removeEventListener('click', clickSquare);
  }
}

I've tried naming the returned anonymous function and using  removeEventListener on that to no avail.
Comment: You either remove all (isn't there an API function to remove _all_ events listeners?), or you need to keep a pointer to the actual function. Sending in the function.creating function is useless - that's an entirely different pointer (to a different function object). There is no magic or crystal ball:The event system simply stores all callback function pointers in a structure and when you remove one tries to find the one you send in for removal in that structure. Also seee https://stackoverflow.com/a/4386514/544779
Comment: What are the elements of `allSquares` array? Are there elements with duplicate `id` within the `document`? What is purpose of `document.getElementById(allSquares[i].getAttribute('id'))`?
Answer: To remove event listener from a DOM element you need to pass the same function you used while adding event listener, as the parameter.
In javascript when you create an object it creates a new instance of that object class, so it won't be equal to another object even if it is created with same parameters
Example:
{} != {} // returns true
[] != [] // returns true

Same goes with function, whenever you write function (){} it creates a new instance of Function class.
Example:
function a() {
    return function b() {}
}
a() != a() // returns true

Solution:
So for you to be able to remove the event listeners, you will have to store the functions you have passed to addEventListener
var listeners = [];

function setupPlayer(player) {
    var squareState = {};
    for (i = 0; i < allSquares.length; i++) {
        if(allSquares[i].innerHTML === "") {
            listeners[i] = clickSquare(i);
            document.getElementById(allSquares[i].getAttribute('id')).addEventListener('click', listeners[i]);
        }
    }
}

function clickSquare(i) {
    var num = i;
    return function() {
        document.getElementById(allSquares[num].getAttribute('id')).innerHTML=player;
    }
}

function removeClickEvents() {
    for (let i = 0; i < allSquares.length; i++) {
        if(listeners[i]) {
            document.getElementById(allSquares[i].getAttribute('id')).removeEventListener('click', listeners[i]);
        }
    }
}

From your code where you are using
document.getElementById(allSquares[i].getAttribute('id'))

I am assuming that allSquares[i] is a DOM element already, your code can be more simplified
var listeners = [];

function setupPlayer(player) {
    var squareState = {};
    for (i = 0; i < allSquares.length; i++) {
        if(allSquares[i].innerHTML === "") {
            listeners[i] = clickSquare(i);
            allSquares[i].addEventListener('click', listeners[i]);
        }
    }
}

function clickSquare(i) {
    var num = i;
    return function() {
        allSquares[num].innerHTML=player;
    }
}

function removeClickEvents() {
    for (let i = 0; i < allSquares.length; i++) {
        if(listeners[i]) {
            allSquares[i].removeEventListener('click', listeners[i]);
        }
    }
}

Answer: The function is being called immediately at (clickSquare)(i). At code at Question allSquares appears to be the element itself, clickSquare function can be referenced directly and event.target can be used within event handler to reference the current element in allSquares collection

let player = 123;

setInterval(() => player = Math.random(), 1000);

onload = () => {

  let allSquares = document.querySelectorAll("div[id|=square]");

  let button = document.querySelector("button");

  button.onclick = removeClickEvents;

  function setupPlayer(player) {
    var squareState = {};
    for (let i = 0; i < allSquares.length; i++) {
      if (allSquares[i].innerHTML === "click") {
        // set up a click event for each square
        allSquares[i].addEventListener('click', clickSquare);
      }
    }
  }

  function clickSquare(event) {
    console.log(event.target);
    event.target.innerHTML = player;
  }

  function removeClickEvents() {
    for (let i = 0; i < allSquares.length; i++) {
      allSquares[i].removeEventListener('click', clickSquare);
    }
  }

  setupPlayer(player);

}

click

click

click

<button>remove events</button>


Elasticsearch Two sibling aggregations cannot have the same name

Question: I'm running Elastic 1.4.4 and have created some code with a range aggregation and a sub-aggregation (cardinality).
If I run my code with a matchall query and some filterquery to get a subset all works fine.
I see the range aggregation and the expected values for the sub-aggregation.
But as soon as I add a query things fall apart.
I run into an error: "Two sibling aggregations cannot have the same name".
This seems strange since I have the same aggregation/sub-aggregation defined before without any problem.
This is basically what I do:
<code>SearchResponse response =
client.prepareSearch(esIndex)
.setQuery(query)
.setFrom(startAt)
.setSize(topSize)
.addAggregation(AggregationBuilders.cardinality(UNIQUE_IPS).field(Constants.MAIN_COLLAPSE_FIELD))
.addAggregation(collapse)
.addAggregation(filtersetbranche)              \
.addAggregation(Constants.FTE_RANGES_AGGS.subAggregation(AggregationBuilders.cardinality("ftecounts").field(Constants.MAIN_COLLAPSE_FIELD)))
.execute()
.actionGet();
</code>
Comment: It would really help if you added a complete example that reproduces the issue. It's difficult to figure out what's going on based on the bits and pieces provided.
Answer: I found the issue.
I added a subaggregation to the Constants.FTE_RANGES_AGGS dynamically.
So, the first time I call this piece of code all is fine.
But the next time I added the same subaggregation with the same name hence the error "Two sibling aggregations cannot have the same name".
So, I have to rewrite it to use a copy of the Constant or do it in a different way.