text:
Q: Confusion with Jstl tag c:forEach items I have a confusion about c:forEach items="${} JSTL tag.
I have a category of items, filled with some articles T wanna show those articles by category and I couldn't figure out how to do so in the jsp file knowing that everything that precedes works perfectly fine.
I am able to show categories with c:forEach items="${categories}, and articles with c:forEach items="${articles}, and now I wanna show the articles that belong to one category, I tried c:forEach items="${categorie.articles} but nothing.
DAOImpl
// Articles by category
    @Override
    public List
 articleParCategorie(Long idCat)
    {
        Query req = em.createQuery("select a from Article a where a.categorie.idCategorie=:x");
        req.setParameter("x", idCat);
        return req.getResultList();
    }

Controller
// Action for articles by category
                    @RequestMapping(value="/ConsultCat")
                    public String ArtParCat(Long idCat, Model model)
                    {
                        model.addAttribute("categories", metier.listCategories());
                        model.addAttribute("articles", metier.articleParCategorie(idCat));
                        return "ArticleParCat";
                    }

JSP file
this is what i tried, it returns the view but with no categories or articles
<c:forEach items="${categorie.articles}" var="cat">

                                            ${cat.article.titre}

${cat.description}

                                </c:forEach>

A: the code in both Class category and Class Article, and code in the view ListCategories (which returns the categories perfectly).
Categorie Class:
@Entity
@Table(name="CATEGORIE")
public class Categorie implements Serializable
{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long idCategorie;
    private String nomCategorie;
    private String description;
    private byte [] photoCat;

    @OneToMany(mappedBy="categorie")
    private Collection
 articles;

Article Class
@Entity
@Table(name="ARTICLE")
public class Article implements Serializable
{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long idArticle;
    private String titre;
    private String texte;
    private Date date;
    private byte [] photo;

    @ManyToOne
    @JoinColumn(name="ID_CAT")
    private Categorie categorie;

The list of categories View :

                                <c:forEach items="${categories}" var="cat">

                                            ${cat.nomCategorie}

${cat.description}

                                            See more

                                            edit
                                            delete

                                </c:forEach>


text:
Q: Is there an alternative to Template Method pattern when using common logic? I have a problem. Most of the solutions in the project follow the Template Method design pattern. At the same time, along with the complexity of business logic, solutions are becoming more and more confusing.
For example, there is some Copier interface:
public interface Copier {

    void copy() {
        copyA();
        copyB();
    }
}

Some classes can implement this interface by this way:
public class MusicCopier implements Copier {

    @Override
    protected void copyA() {
        SomeUtils.copy(new File(...), new File(...)));
    }

    @Override
    protected void copyB() {
        // three arguments here
        SomeUtils.copy(new File(...), new File(...)), new File(...));
    }
}

public class DocumentsCopier implements Copier {

    @Override
    protected void copyA() {
        SomeUtils.copy(new File(...), new File(...)));
    }

    @Override
    protected void copyB() {
        // three arguments here
        SomeUtils.copy(new File(...), new File(...), new File(...)));
    }
}

Then somewhere these classes are used like this:
Copier musicCopier = new MusicCopier();
Copier documentsCopier = new DocumentsCopier();

musicCopier.copy();
documentsCopier.copy();

Etc. Great. Here comes the idea to replace the interface with an abstract class and bring the main logic there. Then the abstract class will look like this:
public abstract class Copier {

    protected void copy() {
        copyA();
        copyB();
    }

    protected void copyA() {
       SomeUtils.copy(getASource(), getADest()));
    }

    protected void copyB() {
       SomeUtils.copy(getBSource(), getBDest(), getBExcluded()));
    }

    // and these terrible methods overridden in superclasses:
    protected void getASource() {}
    protected void getBSource() {}
    protected void getADest() {}
    protected void getBDest() {}
    protected void getBExcluded() {}
    // protected void getOrSetWTF() {}
}

Accordingly, the subclasses will be as follows:
public class MusicCopier extends Copier {

    @Override
    protected void getASource() { /* pass some path here */}

    @Override
    protected void getBSource() {/* pass some path here */}

    @Override
    protected void getADest() {/* pass some path here */}

    @Override
    protected void getBDest() {/* pass some path here */}

    @Override
    protected void getBExcluded() {/* pass some path here */}
}

Etc. It turns out that we are "setting up logic", which is now all in an abstract class.
And the more complicated it is, the more "get" (or "set"?) there are. All this creates confusion and such code is simply unpleasant to write - especially if the project is large and developers have to "configure superclasses".
In some subclasses, I need to do something else in copyA() or in copyB(). Then I have to override these methods entirely:
@Override
protected void copyA() {
    doSomethingHere();

    SomeUtils.copy(new File(...), new File(...)));

    doSomethingHereTo();
}

Or put these "doSomething" methods also in an abstract class and then override/implement it in subclasses.
Is there patterns or combinations of them that would help get rid of this ugly design?

A: I would suggest instead of have a lot of methods to override, each returning one piece of info, to combine this methods so one object containing them all can be returned as result in one method.
It seems to me this info is related, so why not put them all together in an 'RoutingInfo'-class or something.
You could refactor your class to have only a few 'template-methods', which return objects containing related information.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replace all values in a column of hive table with a given value I have a hive table with schema -
customer_id string
country string
start_date string
end_date string

I want to replace all the values with a given string in end_date column which is in yyyy-mm-dd format but stored as a string.
Looking at the hive functions, I found out two of them - regexp_replace and translate. Refer -Hive wiki

A: @bunny: You will not be able to update the existing column using the UDF's mentioned. if you want to update the column, you will have to use UPDATE (provided that you have hive >= 0.14 AND the table is created accoringly - fileformat-clustering-bucketing). I'm sure you're not looking for this approach !
Both the udfs mentioned ( regexp_replace and translate) are used to obtain the required output but not replace the existing data.
The only option I see is to overwrite the complete table with the updated column something


text:
Q: move-only struct calls copy constructor in std::map in MSVC I have a vector of map. The maps contain a struct that is move-only.
When I try to interact with this structure, I get compilation errors on MSVC.
Here's a sample code:
#include <map>
#include <memory>
#include <vector>

struct S {
    std::unique_ptr<int> a;
};

int main() {
    std::vector<std::map<float, S>> s;

    s.emplace_back();

    return 0;
}

I get an error on the s.emplace_back() line:
C:/data/msvc/14.28.29333/include\xmemory(701): error C2280: 'std::pair<const float,S>::pair(const std::pair<const float,S> &)': attempting to reference a deleted function
C:/data/msvc/14.28.29333/include\utility(209): note: see declaration of 'std::pair<const float,S>::pair'
C:/data/msvc/14.28.29333/include\utility(209): note: 'std::pair<const float,S>::pair(const std::pair<const float,S> &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'S::S(const S &)'
<source>(7): note: 'S::S(const S &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'std::unique_ptr<int,std::default_delete<int>>::unique_ptr(const std::unique_ptr<int,std::default_delete<int>> &)'
C:/data/msvc/14.28.29333/include\memory(2686): note: 'std::unique_ptr<int,std::default_delete<int>>::unique_ptr(const std::unique_ptr<int,std::default_delete<int>> &)': function was explicitly deleted
C:/data/msvc/14.28.29333/include\xtree(358): note: see reference to function template instantiation 'void std::_Default_allocator_traits<_Alloc>::construct<_Ty,_Ty&>(_Alloc &,_Objty *const ,_Ty &)' being compiled
        with
        [
            _Alloc=std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<std::allocator<std::pair<const float,S>>>::void_pointer>>,
            _Ty=std::pair<const float,S>,
            _Objty=std::pair<const float,S>
        ]
C:/data/msvc/14.28.29333/include\xtree(358): note: see reference to function template instantiation 'void std::_Default_allocator_traits<_Alloc>::construct<_Ty,_Ty&>(_Alloc &,_Objty *const ,_Ty &)' being compiled
        with
        [
            _Alloc=std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<std::allocator<std::pair<const float,S>>>::void_pointer>>,
            _Ty=std::pair<const float,S>,
            _Objty=std::pair<const float,S>
        ]
C:/data/msvc/14.28.29333/include\xtree(2027): note: see reference to function template instantiation 'std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer>::_Buynode<std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer>>,_Ty&>(std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer>> &,std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *,_Ty &)' being compiled
        with
        [
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Ty=std::pair<const float,S>
        ]
C:/data/msvc/14.28.29333/include\xtree(2027): note: see reference to function template instantiation 'std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer>::_Buynode<std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer>>,_Ty&>(std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer>> &,std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *,_Ty &)' being compiled
        with
        [
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Ty=std::pair<const float,S>
        ]
C:/data/msvc/14.28.29333/include\xtree(1741): note: see reference to function template instantiation 'std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Buynode<std::pair<const float,S>&>(std::pair<const float,S> &)' being compiled
        with
        [
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>
        ]
C:/data/msvc/14.28.29333/include\xtree(1741): note: see reference to function template instantiation 'std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Buynode<std::pair<const float,S>&>(std::pair<const float,S> &)' being compiled
        with
        [
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>
        ]
C:/data/msvc/14.28.29333/include\xtree(1762): note: see reference to function template instantiation 'std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy_or_move<std::pair<const float,S>,std::integral_constant<bool,false>>(std::pair<const float,S> &,std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy_tag,_Is_set)' being compiled
        with
        [
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>,
            _Is_set=std::integral_constant<bool,false>
        ]
C:/data/msvc/14.28.29333/include\xtree(1762): note: see reference to function template instantiation 'std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy_or_move<std::pair<const float,S>,std::integral_constant<bool,false>>(std::pair<const float,S> &,std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy_tag,_Is_set)' being compiled
        with
        [
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>,
            _Is_set=std::integral_constant<bool,false>
        ]
C:/data/msvc/14.28.29333/include\xtree(1728): note: see reference to function template instantiation 'std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy_nodes<_Moveit>(std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *,std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *,_Moveit)' being compiled
        with
        [
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>,
            _Moveit=std::_Tree<std::_Tmap_traits<float,S,std::less<float>,std::allocator<std::pair<const float,S>>,false>>::_Copy_tag
        ]
C:/data/msvc/14.28.29333/include\xtree(1728): note: see reference to function template instantiation 'std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy_nodes<_Moveit>(std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *,std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer> *,_Moveit)' being compiled
        with
        [
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>,
            _Moveit=std::_Tree<std::_Tmap_traits<float,S,std::less<float>,std::allocator<std::pair<const float,S>>,false>>::_Copy_tag
        ]
C:/data/msvc/14.28.29333/include\xtree(902): note: see reference to function template instantiation 'void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy<std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy_tag>(const std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>> &,_Moveit)' being compiled
        with
        [
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>,
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Moveit=std::_Tree<std::_Tmap_traits<float,S,std::less<float>,std::allocator<std::pair<const float,S>>,false>>::_Copy_tag
        ]
C:/data/msvc/14.28.29333/include\xtree(902): note: see reference to function template instantiation 'void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy<std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Copy_tag>(const std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>> &,_Moveit)' being compiled
        with
        [
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>,
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Moveit=std::_Tree<std::_Tmap_traits<float,S,std::less<float>,std::allocator<std::pair<const float,S>>,false>>::_Copy_tag
        ]
C:/data/msvc/14.28.29333/include\map(111): note: see reference to function template instantiation 'std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Tree<std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer>>>(const std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>> &,_Any_alloc &&)' being compiled
        with
        [
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>,
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Any_alloc=std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<std::allocator<std::pair<const float,S>>>::void_pointer>>
        ]
C:/data/msvc/14.28.29333/include\map(111): note: see reference to function template instantiation 'std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::_Tree<std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<_Alloc>::void_pointer>>>(const std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>> &,_Any_alloc &&)' being compiled
        with
        [
            _Kty=float,
            _Ty=S,
            _Pr=std::less<float>,
            _Alloc=std::allocator<std::pair<const float,S>>,
            _Any_alloc=std::allocator<std::_Tree_node<std::pair<const float,S>,std::_Default_allocator_traits<std::allocator<std::pair<const float,S>>>::void_pointer>>
        ]
C:/data/msvc/14.28.29333/include\map(111): note: while compiling class template member function 'std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>>::map(const std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>> &)'
C:/data/msvc/14.28.29333/include\xmemory(701): note: see reference to function template instantiation 'std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>>::map(const std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>> &)' being compiled
C:/data/msvc/14.28.29333/include\vector(687): note: see reference to class template instantiation 'std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>>' being compiled
C:/data/msvc/14.28.29333/include\vector(705): note: see reference to function template instantiation 'void std::vector<std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>>,std::allocator<std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>>>>::_Emplace_back_with_unused_capacity<>(void)' being compiled
<source>(12): note: see reference to function template instantiation 'void std::vector<std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>>,std::allocator<std::map<float,S,std::less<float>,std::allocator<std::pair<const float,S>>>>>::emplace_back<>(void)' being compiled
Compiler returned: 2

You can check the code in action on godbolt here: https://godbolt.org/z/qvMPYdc5q
It works in clang and GCC but not in MSVC (latest and v19.28).
I saw somewhere that MSVC requires the ctor & dtor to be noexcept for the map to use the move constructor, but even when defining noexcept ctors & dtors for the S struct, I get the same error.
What is MSVC doing that requires a copy in this piece of code? How can I force the move here?


text:
Q: What is conditioning in spatial statistics? Could someone explain to me:
the concept of "conditioning" in spatial statistics in a fairly advanced context?
Here is an example to clarify the question:
Step 1) generate a 2D point process, here 6 realization are shown:

Step 2) choose a region from one realization

Step 3) try to fill the rest of same size region, here I used the same PP:

Step 4) remove the overlapped region and merge with given part:

Step 5) assume you did right!

Step 6) ask question now:
Is the result is a conditioned PP on a set of given points?
Step 7) wait keeping hope that somebody will answer your question thoroughly:)

A: The answer is clearly "yes". Your resulting pattern at the end of step 5 is conditioned on the points in the top corner. Imagine doing steps 3,4 and 5 again. You'll get the same points in the top left corner, and different points elsewhere.
There's also the element of working out how you've generated the new points given the points in the corner. Did you use the number of points in the small square to estimate the density, and then generate the new points conditional on that density? There's another conditioning.


text:
Q: How do I get input from JTextField from other panels I am new to using JTextFields and was curious on how to get input from 3 different panels. The panels will take numbers from inputs and average the scores. For that, I want to access all 3 panels to do the math. I have a panel for three different people's scores that I want to average. So I would like to get mattsTotalScore and add it with timsTotalScore and BensTotalScore and make the average appear after a button on a fourth panel.
import javax.swing.*;
import java.awt.*;

public class MattPanel extends JPanel {

    public MattPanel(){
        Dimension size = getPreferredSize();
        size.width = 250;
        setPreferredSize(size);
        setBorder(BorderFactory.createTitledBorder("Matt's Scores"));

        JLabel memMatt = new JLabel("MEMORABILITY :");
        JTextField textMemMattPane = new JTextField(10);

        JLabel comMatt = new JLabel("COMPOSITION :");
        JTextField textComMattPane = new JTextField(10);

        JLabel mixMatt = new JLabel("MIX/MASTER :");
        JTextField textMixMattPane = new JTextField(10);

        JLabel soundMatt = new JLabel("SOUND DESIGN :");
        JTextField textSoundMattPane = new JTextField(10);

        JLabel enjoyMatt = new JLabel("ENJOYMENT :");
        JTextField textEnjoyMattPane = new JTextField(10);

        setLayout(new GridBagLayout());

        GridBagConstraints gc = new GridBagConstraints();

        ///First Column ///////////////////////
        gc.anchor = GridBagConstraints.LINE_END;
        gc.weightx = 0.5; gc.weighty = 0.5;
        gc.gridx = 0; gc.gridy = 0;
        add(memMatt, gc);

        gc.gridx = 0; gc.gridy = 1;
        add(comMatt, gc);

        gc.gridx = 0; gc.gridy = 2;
        add(mixMatt, gc);

        gc.gridx = 0; gc.gridy = 3;
        add(soundMatt, gc);

        gc.gridx = 0; gc.gridy = 4;
        add(enjoyMatt, gc);

        //Second Column //////////////////////
        gc.anchor = GridBagConstraints.LINE_START;
        gc.gridx = 1; gc.gridy = 0;
        add(textMemMattPane,gc);

        gc.gridx = 1; gc.gridy = 1;
        add(textComMattPane,gc);

        gc.gridx = 1; gc.gridy = 2;
        add(textMixMattPane,gc);

        gc.gridx = 1; gc.gridy = 3;
        add(textSoundMattPane,gc);

        gc.gridx = 1; gc.gridy = 4;
        add(textEnjoyMattPane,gc);
    }
}

A: You could try to use the getComponents() method from JPanel to get all components, although you would have to somehow identify the TextFields like:
MattPanel panel = new MattPanel();
int sum = 0;
int nr = 0;
for(Component comp : panel.getComponents()){
    if(comp instanceof JTextField){
        String text = ((JTextField)comp).getText();
        sum += Integer.parseInt(text);
        nr ++;
    }
}
double avg = sum/nr;


text:
Q: Why is my callback function acting this way? Okay, the problem asks me to update a string. When the char is followed by an A, I callback my addOne function and delete the A. When my char is followed by a B, I callback my subtractOne function and delete the B. Here is what I have, and my test variable - 123A456B should return 124455. Instead it returns 1231455. Can someone help me figure out why? I feel like I am missing something obvious. Thank you!

const test = '123A456B'

function addOne(num) {
  return num + 1
}

function subtractOne(num) {
  return num - 1
}

function updateString(string) {
  let result = ''
  for (let i = 0; i < string.length; i++) {
    if (string[i] === 'A' || string[i] === 'B') {
    } else if (string[i + 1] === 'A') {
      result += addOne(string[i])
    } else if (string[i + 1] === 'B') {
      result += subtractOne(string[i])
    } else result += string[i]
  }
  return result
}
console.log(updateString(test))

A: You need to convert those strings intro numbers when you do your addition. You can use the shorthand + prefix, parseInt(n) or Number(n)
function addOne (num){
  return +num + 1
}

function subtractOne (num){
  return +num - 1
}

const test = '123A456B'

function addOne (num){
  return +num + 1
}

function subtractOne (num){
  return +num - 1
}

function updateString(string){
  let result = ''
    for(let i = 0; i < string.length; i++){
    if(string[i] === 'A' || string[i] === 'B'){
    }else if(string[i + 1] === 'A'){
        result += addOne(string[i])
    }else if(string[i + 1] === 'B'){
      result += subtractOne(string[i])
    }else result += string[i]
  }
  return result
}
console.log(updateString(test))


text:
Q: Why do I get a white/blank page on new React app? This is solved - Here's what it was:
I had confused create-react-app with start-react-app, which still created an app, which caused the confusion.
I've recently created a new react app, but it gives me a white/blank page. I do see the default favicon and the title of the app.
I've done the basics steps to create the app:
npx start-react-app frontend
cd frontend
npm start
It gives me following error:
imacs-imac:frontend imac$ npm start

> frontend@0.1.0 start /Users/imac/Desktop/project/frontend
> node scripts/start.js

Project is running at http://localhost:9000/
webpack output is served from /
Content not from webpack is served from /Users/imac/Desktop/project/frontend/public
webpack: wait until bundle finished: /
(node:2016) Warning: Accessing non-existent property 'cat' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2016) Warning: Accessing non-existent property 'cd' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'chmod' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'cp' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'dirs' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'pushd' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'popd' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'echo' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'tempdir' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'pwd' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'exec' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'ls' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'find' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'grep' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'head' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'ln' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'mkdir' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'rm' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'mv' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'sed' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'set' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'sort' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'tail' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'test' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'to' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'toEnd' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'touch' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'uniq' of module exports inside circular dependency
(node:2016) Warning: Accessing non-existent property 'which' of module exports inside circular dependency
Hash: 0f0125be68c02e27c57615ee1d2b5825
Version: webpack 2.7.0
Time: 20771ms
                                 Asset       Size  Chunks                    Chunk Names
static/js/main.0f0125be68c02e27c57615ee1d2b5825.js    2.91 MB       0  [emitted]  [big]  main
                            index.html  329 bytes          [emitted]
chunk    {0} static/js/main.0f0125be68c02e27c57615ee1d2b5825.js (main) 1.07 MB [entry] [rendered]
   [84] (webpack)/hot/emitter.js 77 bytes {0} [built]
   [85] ./src/index.js 665 bytes {0} [built]
   [86] (webpack)-dev-server/client?http://localhost:9000 7.93 kB {0} [built]
   [87] (webpack)/hot/dev-server.js 1.57 kB {0} [built]
   [90] ./src/App.js 1.97 kB {0} [built] [failed] [1 error]
  [111] ./~/loglevel/lib/loglevel.js 8.86 kB {0} [built]
  [118] ./~/react-dom/index.js 59 bytes {0} [built]
  [204] ./~/react/react.js 56 bytes {0} [built]
  [205] ./~/strip-ansi/index.js 161 bytes {0} [built]
  [208] ./src/index.css 996 bytes {0} [built]
  [209] ./~/url/url.js 23.3 kB {0} [built]
  [211] (webpack)-dev-server/client/overlay.js 3.67 kB {0} [built]
  [212] (webpack)-dev-server/client/socket.js 1.08 kB {0} [built]
  [215] (webpack)/hot nonrecursive ^\.\/log$ 160 bytes {0} [built]
  [217] multi (webpack)-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./index.js 52 bytes {0} [built]
     + 203 hidden modules

ERROR in ./src/App.js
Module build failed: TypeError: Cannot read property 'replace' of undefined
    at EventEmitter.module.exports.api.report (/Users/imac/Desktop/project/frontend/node_modules/eslint/lib/eslint.js:991:31)
    at RuleContext.report (/Users/imac/Desktop/project/frontend/node_modules/eslint/lib/rule-context.js:130:25)
    at report (/Users/imac/Desktop/project/frontend/node_modules/eslint-plugin-react/lib/rules/jsx-indent.js:132:15)
    at /Users/imac/Desktop/project/frontend/node_modules/eslint-plugin-react/lib/rules/jsx-indent.js:311:11
    at Array.forEach (<anonymous>)
    at checkLiteralNodeIndent (/Users/imac/Desktop/project/frontend/node_modules/eslint-plugin-react/lib/rules/jsx-indent.js:310:28)
    at EventEmitter.handleLiteral (/Users/imac/Desktop/project/frontend/node_modules/eslint-plugin-react/lib/rules/jsx-indent.js:374:7)
    at EventEmitter.emit (events.js:412:35)
    at NodeEventGenerator.applySelector (/Users/imac/Desktop/project/frontend/node_modules/eslint/lib/util/node-event-generator.js:265:26)
    at NodeEventGenerator.applySelectors (/Users/imac/Desktop/project/frontend/node_modules/eslint/lib/util/node-event-generator.js:294:22)
    at NodeEventGenerator.enterNode (/Users/imac/Desktop/project/frontend/node_modules/eslint/lib/util/node-event-generator.js:308:14)
    at CodePathAnalyzer.enterNode (/Users/imac/Desktop/project/frontend/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js:602:23)
    at CommentEventGenerator.enterNode (/Users/imac/Desktop/project/frontend/node_modules/eslint/lib/util/comment-event-generator.js:98:23)
    at Traverser.enter (/Users/imac/Desktop/project/frontend/node_modules/eslint/lib/eslint.js:929:36)
    at Traverser.__execute (/Users/imac/Desktop/project/frontend/node_modules/estraverse/estraverse.js:330:31)
    at Traverser.traverse (/Users/imac/Desktop/project/frontend/node_modules/estraverse/estraverse.js:434:28)
 @ ./src/index.js 13:11-27
 @ multi (webpack)-dev-server/client?http://localhost:9000 webpack/hot/dev-server ./index.js
Child html-webpack-plugin for "index.html":
    chunk    {0} index.html 547 kB [entry] [rendered]
        [0] ./~/lodash/lodash.js 544 kB {0} [built]
        [1] ./~/html-webpack-plugin/lib/loader.js!./public/index.html 1.52 kB {0} [built]
        [2] (webpack)/buildin/global.js 509 bytes {0} [built]
        [3] (webpack)/buildin/module.js 517 bytes {0} [built]
webpack: Failed to compile.

Additional Code/Info
project/frontend
node_modules
public
scripts
src
.eslintrc.json
.gitignore
package-lock.json
package.json
readme.md
webpack.config.js

webpack.config.js
'use strict';
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var autoprefixer = require('autoprefixer');

/**
 * webpack.config.js 可以 export 一个 object,或者是一个 env 为参数的 function
 */
module.exports = function (env) {
    /**
     * 判断是否是生产环境。 当命令行运行 `webpack --env.production` 时, env.production 的值为 true
     * https://webpack.js.org/configuration/configuration-types/#exporting-a-function-to-use-env
     */
    const isProduction = env && env.production === true;

    return {
        // 设定代码的入口,入口可以是一个或者多个,即可以传入一个 array
        // https://webpack.js.org/configuration/entry-context/
        context: path.resolve(__dirname, "src"),
        entry: './index.js',

        // 打包好的代码存放的位置和文件名
        // 这里的 [name].[hash].js 的格式意味着会自动生成一个带 hash 的文件名
        // https://webpack.js.org/configuration/output/
        output: {
            path: path.resolve(__dirname, 'build'),
            filename: 'static/js/[name].[hash].js'
        },

        module: {
            /**
             *  loader 相当于一个预处理器。
             *  因为正常来说,webpack 只能解析 js,因此,如果过我们要引入非 js 的模块
             *  就需要一个预处理器来告诉 webpack 该如何处理这个文件,比如 css、图片等
             *  https://webpack.js.org/concepts/loaders/
             */
            loaders: [
                /**
                 * eslint-loader
                 * 在构建之前,自动进行 eslint 检查
                 * 这里的配置设定为,如果有 error,那么就不能继续构建
                 * https://github.com/MoOx/eslint-loader
                 */
                {
                    enforce: "pre",
                    test: /\.js$/,
                    include: path.resolve(__dirname, 'src'),
                    loader: "eslint-loader",
                    options: {
                        failOnError: true,
                        fix: true
                    }
                },
                /**
                 * babel-loader
                 * 将 es6 转化为 es5
                 * https://github.com/babel/babel-loader
                 */
                {
                    test: /\.(js|jsx)$/,
                    include: path.resolve(__dirname, 'src'),
                    loader: 'babel-loader',
                    query: {
                        babelrc: false,
                        presets: [require.resolve('babel-preset-react-app')],
                    },
                },
                /**
                 * css-loader & style-loader
                 *  用来处理代码中 import './style.css' 的情况
                 *  如果是开发环境,那么作为 style 标签插入到 html 中
                 *  如果是正式环境,那么生成单独的文件,作为 link 插入的 html 中
                 *  https://github.com/webpack-contrib/css-loader
                 *  https://github.com/webpack-contrib/style-loader
                 */
                {
                    test: /\.css$/,
                    loader: isProduction ?
                        ExtractTextPlugin.extract({ fallback: 'style-loader', use: [
                            {
                                loader: require.resolve('css-loader')
                            },
                            {
                                loader: require.resolve('postcss-loader'),
                                options: {
                                    plugins: () => [
                                        require('postcss-flexbugs-fixes'),
                                        autoprefixer({
                                            browsers: [
                                                '>1%',
                                                'last 4 versions',
                                                'Firefox ESR',
                                                'not ie < 9',
                                            ],
                                            flexbox: 'no-2009',
                                        }),
                                    ],
                                },
                            }
                        ] }) :
                        [ 'style-loader', 'css-loader', ]
                },
                /**
                 * json-loader
                 * https://github.com/webpack-contrib/json-loader
                 */
                {
                    test: /\.json$/,
                    loader: 'json-loader'
                },
                // "file" loader for svg
                // https://github.com/webpack-contrib/file-loader
                {
                    test: /\.svg$/,
                    loader: 'file-loader',
                    query: {
                        name: 'static/media/[name].[hash:8].[ext]'
                    }
                }
            ]
        },
        /**
         * plugin 是 webpack 完成各种复杂功能的核心
         * 比如,这里面用的 HtmlWebpackPlugin,即可将生成的 js,生成 script 标签插入到指定的 html 里
         * 又比如,ExtractTextPlugin 可以加 css 生成 link 插入
         * https://webpack.js.org/concepts/plugins/
         */
        plugins: [
            new InterpolateHtmlPlugin({
                PUBLIC_URL: '' // 用于替换 index.html 里面的 %PUBLIC_URL%
            }),
            new HtmlWebpackPlugin({
                inject: true,
                template: '../public/index.html',
                minify: {
                    removeComments: true,
                    collapseWhitespace: true,
                    removeRedundantAttributes: true,
                    useShortDoctype: true,
                    removeEmptyAttributes: true,
                    removeStyleLinkTypeAttributes: true,
                    keepClosingSlash: true,
                    minifyJS: true,
                    minifyCSS: true,
                    minifyURLs: true
                }
            }),
            new ExtractTextPlugin('static/css/[name].[hash].css'),
            new webpack.HotModuleReplacementPlugin(), // 用于热加载
            // 可以替换代码中的变量
            // https://webpack.js.org/plugins/define-plugin/#use-case-service-urls
            new webpack.DefinePlugin({
                'SERVICE_URL': isProduction ?
                    JSON.stringify("http://pro.example.com") :
                    JSON.stringify("http://dev.example.com"),
                "process.env": {
                    NODE_ENV: isProduction ?
                        JSON.stringify("production") :
                        JSON.stringify("development")
                }
            })
        ],
        /**
         * webpack 自带的开发 server,配合 webpack-dev-server 命令使用
         * https://webpack.js.org/guides/development/#webpack-dev-server
         * https://webpack.js.org/configuration/dev-server/
         */
        devServer:{
            hot: true,
            contentBase: path.join(__dirname, "public"),
            compress: true,
            port: 9000,
            publicPath: '/',
            // 设置代理,比如,请求 /api/abc 会代理制 http://localhost:7000/abc
            // https://webpack.js.org/configuration/dev-server/#devserver-proxy
            // https://github.com/chimurai/http-proxy-middleware#http-proxy-middleware-options
            proxy: {
                "/api": {
                    target: "http://localhost:7000/",
                    pathRewrite: {"^/api" : ""},
                    secure: false,
                    changeOrigin: true
                }
            }
        },
        // 为压缩以后的代码提供 source map 方便调试
        // https://webpack.js.org/configuration/devtool/
        devtool: isProduction ?
            'hidden-source-map' :
            'cheap-module-eval-source-map',
    };
}

package.json
{
    "name": "frontend",
    "dependencies": {
        "react": "^15.5.4",
        "react-dom": "^15.5.4"
    },
    "version": "0.1.0",
    "devDependencies": {
        "autoprefixer": "^7.1.1",
        "babel-core": "^6.24.1",
        "babel-eslint": "^7.2.3",
        "babel-loader": "^7.0.0",
        "babel-preset-react-app": "^2.2.0",
        "css-loader": "^0.28.1",
        "eslint": "^3.19.0",
        "eslint-config-airbnb": "^15.0.1",
        "eslint-loader": "^1.7.1",
        "eslint-plugin-import": "^2.2.0",
        "eslint-plugin-jsx-a11y": "^5.0.1",
        "eslint-plugin-react": "^7.0.1",
        "extract-text-webpack-plugin": "^2.1.0",
        "file-loader": "^0.11.1",
        "html-webpack-plugin": "^2.28.0",
        "json-loader": "^0.5.4",
        "postcss-flexbugs-fixes": "^3.0.0",
        "postcss-loader": "^2.0.5",
        "react-dev-utils": "^1.0.0",
        "style-loader": "^0.17.0",
        "webpack": "^2.5.1",
        "webpack-dev-server": "^2.4.5"
    },
    "scripts": {
        "start": "node scripts/start.js",
        "build": "export NODE_ENV=production && rm -rf ./build && webpack --env.production --optimize-minimize"
    }
}

src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
    state = { loading: false };

    componentDidMount() {
        // 测试 devServer 的代理功能
        // fetch('/api/category')
        //     .then(resp => resp.json())
        //     .then(res => console.log('here here', res));
    }

    render() {
        return (

Welcome to React

{ this.state.loading.toString() }

          To get started, edit src/App.js and save to reload.

        );
    }
}

export default App;

Does anyone have an idea of what could cause this, and how to fix it?
Thanks in advance

A: It should be npx create-react-app frontend not npx start-react-app
Replace start by create:
npx create-react-app frontend
cd frontend
npm start

Or are you purposely try to create a React from that?
That's definitely a mistake.


text:
Q: Handling shared/tmp in a Ruby on Rails project when the deploy user is different than the run user I have two users on my server, an Ubuntu 12.04 virtual server that I manage myself:

*

*projectx is used to deploy the application and is the user/group for most files in /var/www/projectx

*projectx_rails and it's used to run the Rails application. That way, the running rails application doesn't have access to modify the source code.

Some directories, like public/uploads, are configured to belong to projectx_rails:projectx_rails, so that the rails app can write the uploaded files.
My problem comes to the directory tmp. This directory is located in /var/www/projectx/shared and linked to each release in the usual capistrano way of handling releases. The problem is that some files created during deployment are then not writable by the running rails app and files created by the rails app are not writable by the deployment process.
Is there a way to handle this? Having all the files there belong to projectx_rails:projectx_rails and be group writable would be good enough, but I'm not sure how to trigger this.
I'm using: Capistrano 3, Rails 3.2, Ruby 2.1.2, Unicorn 4.8.3, nginx.

A: Well, this is my theory. It is obviously hard to test on my end, so consider it conjecture.
First: make a group that both users belong to. Like projectx_shared.
Second: make this group the group owner of the tmp directory:
chown projectx_rails:projectx_shared tmp

Third: set the setgid bit on this directory:
chmod g+s tmp

Now, the group owner of files added to tmp should be set to projectx_shared automatically. I think this will apply to capistrano tasks as well.
I'm assuming when you deploy, files already get rw-rw-r-- permissions automatically. If not, you'll need to set your UMASK to 002 in your, e.g. .bashrc as well.
Let me know if it works...

A: May be use ACL for shared files? The only thing that, enable ACL support in fstab.
setfacl -m d:u:projectx:rwx,u:projectx:rwx,\
d:u:projectx_rails:rwx,u:projectx_rails:rwx /var/www/projectx/shared/tmp

A: You can run commands on the remote machine through capistrano. You could run a directory owner change after, lets say, symlinking the application.
In your deploy.rb file, add a callback for it:
after 'deploy:create_symlink' do
  run "chown -R projectx_rails:projectx_rails #{current_release}/tmp"
end

A: My current solution is to have this task:
namespace :deploy do
  desc "Fix permissions"
  task :fix_permissions do
    on roles(:app) do
      execute "sudo chown -R projectx_rails:projectx_rails #{shared_path}/tmp"
      execute "sudo chmod ug+rwX,o+rw #{shared_path}/tmp"
    end
  end
end

and run it both at the beginning and the end of my deployment:
after "deploy:started", "deploy:fix_permissions"
before "deploy:restart", "deploy:fix_permissions"

and to make it work I had to add this to my sudoers:
projectx ALL=NOPASSWD: /bin/chown -R projectx_rails\:projectx_rails /var/www/projectx/shared/tmp
projectx ALL=NOPASSWD: /bin/chmod ug+rwX\,o+rw /var/www/projectx/shared/tmp

which makes me rather uncomfortable.

A: 1) ensure both projectx and projectx_rails are members of the group projectx
2) add this to deploy:
task :change_tmp_pems do
   run "chmod -Rf 775 #{shared_path}/tmp"
end
after "deploy:started", :change_tmp_pems

the -f will silently fail / skip any files it doesn't have access to, so that wont be an issue.
4 lines of code, pretty succinct.
Dont messa about with chown as it requires sudo normally and is unnecessary.


text:
Q: How can i include Proxy Server authentication in a Rest request? I have a rest request as follows
            var client = new RestClient(url);
            var request = new RestRequest { Method = Method.GET, Resource = $"v2/userdetails" };
            request.AddHeader("Authorization", $"Bearer {token}");
            var response = client.Execute(request);
            if (response.StatusCode == HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<List<UserDetails>>(response.Content);
            return null;

It returns null, I was informed that there is a Proxy Server in the middle.
So do I need to include the proxy server settings in the request and authenticate first ?
If so how can i do  that ?


text:
Q: Differential inequality implies estimation From the inequality
\begin{equation}
y^\prime(t) + C_1 y^\alpha(t) \le C_2, \quad y(0) = y_0
\end{equation}
for $t \in (0,T)$ and constants $C_1,C_2, \alpha > 0$,
I want to imply
\begin{equation}
y(t) \le \max\left\{y_0,\left(\frac{C_2}{C_1}\right)^{\frac1\alpha}\right\}
\end{equation}
for all $t \in (0,T)$.
I tried to do separation of variables with the transformation $z:=y^\alpha$, but I didn't get the above estimation.
Does someone know how to do this?
For $\alpha = 1$ this is contained in the proof of Lemma 4.5 in https://math.uni-paderborn.de/fileadmin/mathematik/ag-partielle-differentialgleichungen/Publikationen/Winkler/2020/winkler_2d_KS_NaSto_repulsion_homepage.pdf.

A: $y$ can not grow indefinitely, if $y'\ge 0$ then obviously $y^α\le \frac{C_2}{C_1}$, so that $y$ can not grow above $\left(\frac{C_2}{C_1}\right)^\frac1α$. On the other hand, if $y'<0$ on an initial segment, then $y$ is falling, so also $y\le y_0$ there. While a falling segment can be followed by an increasing segment, the first restriction will kick in, so that in total really $$y(x)\le\max\left(y_0,\left(\frac{C_2}{C_1}\right)^\frac1α\right).$$


text:
Q: How to add/remove class on header when scrolling on a scrollable fixed positioned element? I want to add/remove class on header when user scroll to main content. All header, main and footer are fixed positioned. I tried this one but not working. Most important thing is only main is scrollable with fixed.

$(window).scroll(function() {
  if ($(window).scrollTop() >= 1) {
    $('header').addClass('fixed');
  } else {
    $('header').removeClass('fixed');
  }
});
html,
body {
  height: 100%;
}

header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: #2d2d2d;
}

footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background: #d2d2d2;
}

main {
  padding: 0 25%;
  position: fixed;
  top: 60px;
  bottom: 40px;
  left: 0;
  right: 0;
  overflow-y: auto;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A: Your mistake was targeting the class $('.header') instead of element $('header').

$('main').scroll(function() {
  if ($('main').scrollTop() >= 1) {
    $('header').addClass('fixed');
  } else {
    $('header').removeClass('fixed');
  }
});
html,
body {
  height: 100%;
  margin: 0;
}

.fixed {
  background: red;
}

header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: #2d2d2d;
}

footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background: #d2d2d2;
}

main {
  padding: 0 25%;
  position: fixed;
  top: 60px;
  bottom: 40px;
  left: 0;
  right: 0;
  height: 100%;
  overflow-y: scroll;
}

Bacon ipsum dolor amet t-bone tail filet mignon buffalo, capicola beef ribs brisket. Bresaola hamburger chicken strip steak. Turkey pork chop kevin, doner ham pancetta ball tip burgdoggen rump shankle. Sausage corned beef ribeye, picanha brisket shoulder
    shankle pork venison turkey rump. Ball tip kielbasa pig porchetta, brisket boudin filet mignon. Beef porchetta tri-tip shankle spare ribs short loin short ribs ham brisket.

Jerky burgdoggen tri-tip, turkey cow meatball fatback beef ham hock pastrami salami porchetta capicola leberkas. Pork shankle bresaola pastrami rump ball tip brisket andouille picanha corned beef pig shank sausage. Picanha t-bone short loin, kielbasa
    ribeye ham hock pork belly pork chop shank drumstick. Cupim porchetta jerky pig kielbasa cow turkey.

Flank pig prosciutto beef ribs. Pastrami flank ball tip filet mignon cupim hamburger boudin sausage drumstick shoulder shankle. Turducken tongue sirloin leberkas salami capicola t-bone andouille, pork chop tail. Landjaeger tail jerky, ribeye sausage
    alcatra frankfurter beef prosciutto pork. Kielbasa ham hock frankfurter sausage ball tip cupim beef ribs alcatra leberkas bresaola bacon. Swine biltong shoulder venison filet mignon.

Short ribs strip steak t-bone bresaola, chuck jowl salami spare ribs landjaeger biltong brisket beef ribs doner sirloin. Flank tenderloin ground round burgdoggen beef ribs tri-tip. T-bone shank biltong picanha, boudin rump pancetta short ribs chuck.
    Meatball salami short ribs pork belly, beef ribs cow pork chop jowl frankfurter shoulder short loin bresaola.

Landjaeger leberkas ribeye ham hock pork chop spare ribs pork loin tenderloin. Landjaeger turkey turducken, drumstick ham ball tip chicken andouille. Alcatra sirloin salami prosciutto beef ribs. Landjaeger pancetta tenderloin, shank pork loin chuck
    shoulder porchetta capicola sausage. Fatback tail burgdoggen doner tenderloin ball tip turkey biltong sausage pancetta pork short loin.


text:
Q: how to solve the swift compiler error while changing the project location xcode 9.2? As i creating my own custom framework.My framework was developed by the combination of both objective c and swift.When i changing the project location the project was not build and showing the swift compiler error but it working fine where i created.
#import <Foundation/Foundation.h>
#import <SpeechSDK/SpeechRecognitionService.h>//Here i am getting the error like Include of non-modular header inside framework module

//#import "AppDelegate.h"
#import "SpeechService.h"

The swift compiler error was
1)/Users/xxxxx/Desktop/SofiaPersonalAssistant 2/SofiaPersonalAssistant/SofiapersonalassisT.framework/Headers/precomp.h:56:9: Include of non-modular header inside framework module 'SofiapersonalassisT.precomp': '/Users/muruganandamc/Desktop/SofiaPersonalAssistant 2/SofiaPersonalAssistant/SpeechSDK.framework/Headers/SpeechRecognitionService.h'
2)Could not build Objective-C module 'SofiapersonalassisT'


text:
Q: Grouping levels - multiindex in python pandas pivot_table I've a multiindex dataframe in pandas that looks this (created using pivot_table):

I need help to add a level above (or below) the Date level showing the day of the date like this:

I know I can get the day of a date like this:
lt.DATE.dt.strftime('%a')
#lt is a dataframe and DATE is a column it.

Here is the code reporduce a similar pivot_table:
import pandas as pd
import numpy as np

dlist = pd.date_range('2015-01-01',periods=5)
df = pd.DataFrame(dlist, columns=['DATE'])
df['EC'] = range(7033,7033+len(df))
df['HS'] = np.random.randint(0,9,5)
df['AH'] = np.random.randint(0,9,5)
pv = pd.pivot_table(df, columns=[df.DATE, 'EC'], values=['HS','AH'])
pv = pv.unstack(level=1).unstack(level=0)

A: I got the solution! Here it goes:
import pandas as pd
import numpy as np

dlist = pd.date_range('2015-01-01',periods=5)
df = pd.DataFrame(dlist, columns=['DATE'])
df['EC'] = range(7033,7033+len(df))
df['HS'] = np.random.randint(0,9,5)
df['AH'] = np.random.randint(0,9,5)
df['DAY'] = df.DATE.dt.strftime('%a')
pv = pd.pivot_table(df, columns=[df.DATE.dt.date, df.DAY, 'EC'], values=['HS','AH'])
pv = pv.unstack(level=[1,2]).unstack(level=0)
pv.to_excel('solution.xlsx')

And it produces an output like this:

Pay attention to the function unstack and set the list of levels that are required to be unstacked at a time.


text:
Q: Why ionic APK for android is generating under the build/outputs/apki/debug/ folder and its not opening in device? I am building a android APK normally it will generate inside output/apk/ folder but now its generating inside output/apk/debug folder, So my problem is when I install this generated APK in device it's not opening why ?
My ionic info :
@ionic/cli-utils  : 1.9.2
ionic (Ionic CLI) : 3.9.2

global packages:

  Cordova CLI : 8.0.0

local packages:

  @ionic/app-scripts : 3.1.8
  Cordova Platforms  : android 7.0.0
  Ionic Framework    : ionic-angular 3.9.2

System:

  Android SDK Tools : 26.1.1
  Node              : v8.11.0
  npm               : 5.6.0
  OS                : Windows 7


text:
Q: Is there a function to format numbers in influxdb I'm using grafana to connect to influxdb and display indicator data. I'm using SQL `select sum (siz) from quotes'like this. Is there a function that can format it in the form of 1,111,111? No such function has been found in the document.

A: Unfortunately, this isn't something that can be done by InfluxDB. Grafana has a long standing issue to provide this functionality:
https://github.com/grafana/grafana/issues/4252
However, this was something that was added to Chronograf a while back:
https://github.com/influxdata/chronograf/issues/3608


text:
Q: Como converter uma string salva em um arquivo .txt, para um número inteiro? Exemplo:
teste = open('teste.txt', 'w')
teste.write('6000')
teste.close()
Como eu converto o conteúdo do arquivo .txt em inteiro para poder fazer operações com ele? caso não tenha como fazer isso, como eu posso gravar dados sem perder-los quando reiniciar o meu programa?

A: Desta forma:
with open('data.txt', 'r') as file:
    data=int(float( file.read().replace('\n', '') ))

Quando você usa o open com with ele já fechará o arquivo. Por isso utilizei desta forma.


text:
Q: webpack does not output css Situation
I have a webpack setup, where I have a rule that extracts CSS and/or SASS from .ts files using the extract-text-webpack-plugin and sass-loader.
I import my SCSS file in a seperate .ts file
import './scss/style.scss'

Problem
A CSS file is expected to be in the output folder ( dist ).
The compilation completes without an error, yet there is no CSS file in the build folder.
Here is my webpack configuration:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var styleString = require('css-to-string-loader');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
  filename: "[name].css",
  disable: process.env.NODE_ENV === "development"
});
var helpers = require('./helpers');
var isProd = process.env.NODE_ENV === 'production';

module.exports = {
    entry: {
        polyfills: './src/polyfills.ts',
        vendor: './src/vendor.ts',
        app: isProd ? './src/main.aot.ts' : './src/main.ts'
    },

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [{
                test: /\.ts$/,
                loaders: [
                    'babel-loader',
                    {
                        loader: 'awesome-typescript-loader',
                        options: {
                            configFileName: isProd ?
                                helpers.root('tsconfig-aot.json') :
                                helpers.root('tsconfig.json')
                        }
                    },
                    'angular2-template-loader'
                ],
                exclude: [/node_modules/]
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015']
                }
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[ext]'
            },
            {
                test: /\.(json)$/,
                loader: 'file-loader?name=assets/mocks/[name].[ext]'
            },
            {
              test: /\.(css|scss)$/,
              loaders: ['to-string-loader', 'css-loader', 'sass-loader']
          }
        ]
    },

    plugins: [
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)@angular/,
            helpers.root('./src'), // location of your src
            {} // a map of your routes
        ),

        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),

        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
};

A: Reason
The reason there is not output CSS file is because you are not using the
const extractSass = new ExtractTextPlugin({
    filename: "[name].css",
    disable: process.env.NODE_ENV === "development"
});

in your CSS|SCSS rule
{
    test: /\.(css|scss)$/,
    loaders: ['to-string-loader', 'css-loader', 'sass-loader']
}

Solution
You have to make use of the use property like so:
{
    test: /\.(css|scss)$/,
    use: extractSass.extract({ // <==== Right here, note the "extractSass"
        use: [
            { loader: "to-string-loader" },
            { loader: "css-loader" },
            { loader: "sass-loader" }
        ],
        fallback: "style-loader"
    })
}

And add to your plugins array the ExtractTextPlugin instance ( extractSass ):
plugins: [
    extractSass
]

You might also want to take a look here.


text:
Q: Matlab Error using load Bad version or endian-key I have been trying to load a mat file on my distributed computing environment. When I load running in a matlab terminal on any computer I can load it no problem. When I submit it as a job to my cluster it fails saying
Error using load
Bad version of endian-key

even though the version of matlab is identical. Just the environment is changed. I have stripped away everything to just simply
load ~/Desktop/model.mat
disp('Done');
exit;

and the problem persists. We are running this using Sun Grid Engine.

A: That particular error message can either mean the file is corrupted, or it can mean that the system failed to allocate memory while loading the data (and no, that isn't obvious from the message...)


text:
Q: Get place details by reference - Google Map - Json I have a problem with display json url from google.
When i load my webpage i have a empty screen... no errors, no response
 $(document).ready(function() {

   $.getJSON('https://maps.googleapis.com/maps/api/place/details/json?reference=CpQBhQAAAO74ZZ0bYHAkFKV3rXb-sMyPIvTUaP8olqsu61cyWIR-f3bTpcN0PU_VA3RWTLyH3NeJLWxOpXBqmczZDfYE6EnYbayYl6HWn4xNZA8fJURcNiY4dbzWaTfjxx9HDe3C1JCLZUDRqHwlVudODDRmUsiiJMVSMJniKyimt9-qGgn1paABdlGXU7uduPHUjy9hoxIQr4QJPQjk5yt9FXzzFJnhQxoU3NRNlO-q1Q8y36urd8F_lsvgWHY&sensor=true&key=AIzaSyDSKYz8pCRLHglMPGo1ca6E-geDUQw', function(data) {
    $('#dictionary').empty();

 var html = '
';
 html += '
' + data.result.name + '
';
 html += '
' + data.result.website + '
';
 html += '
';
 html +=  data.result.rating;
 html += '
';
 html += '
';
 $('#dictionary').append(html);

   });
 });

Url is correct, structure of json is also correct.
Function works good only when i want read json from file for example (not from url):
$.getJSON('fileofjson.json'......

Thanks for help. Michal.
PS.
Parsing JSON from Google Map This is my first topic of this problem... here is a structure of json file.
I try to read json from google by:
 $('#container').load('http://google.com');
  $.ajax({
url: 'https://maps.googleapis.com/maps/api/place/details/json?reference=CpQBhQAAAO74ZZ0bYHAkFKV3rXb-sMyPIvTUaP8olqsu61cyWIR-f3bTpcN0PU_VA3RWTLyH3NeJLWxOpXBqmczZDfYE6EnYbayYl6HWn4xNZA8fJURcNiY4dbzWaTfjxx9HDe3C1JCLZUDRqHwlVudODDRmUsiiJMVSMJniKyimt9-qGgn1paABdlGXU7uduPHUjy9hoxIQr4QJPQjk5yt9FXzzFJnhQxoU3NRNlO-q1Q8y36urd8F_lsvgWHY&sensor=true&key=AIzaSyDSKYz8pCRLHglMPGo1ca6E-geDUQw',
type: 'GET',
success: function(res) {
    var headline = $(res.status).find('a.tsh').text();
    alert(headline);
}
});

but alert doesn't work, empty screen. Can somebody help me to parse this url to html? Thanks a lot.

A: See this related question and my answer. You can't, in general, load JSON from a remote source using Javascript, because of the Same Origin Policy. You'll need to use JSONP instead, if the Google API offers this.


text:
Q: Resizing an image using Magick.net I've got an image that I want to resize using Magick.net before displaying in an ASP .Net page, but when I look at the displayed image in my browser, it comes up as a broken image.
Here's what my code would look like if I wasn't resizing:
this.LogoBox.Image = _myModel.LogoImage;

Here's what my ImageMagick-using code looks like:
var logoToDisplay = new MagickImage(new Bitmap(_myModel.LogoImage));
logoToDisplay.Resize(imageWidth, imageHeight);
this.LogoBox.Image = logoToDisplay.ToBitmap();

When I take out the second ...Resize... line, nothing comes up. I can't seem to find good documentation for Magick.net, even on the CodePlex site.
Any thoughts?

A: When you use the ToBitmap method your image will be converted to Bmp. You probably want to use another image format, e.g. ImageFormat.Png or ImageFormat.Jpeg. Feel free to post a message here also: https://magick.codeplex.com/discussions. And can you also put up a link to the image you are trying to resize?


text:
Q: How can I copy (yank) text in `copy-mode-vi in` Tmux, while the terminal is outputting text? I often want to copy (yank) text in copy-mode-vi, while the terminal is outputting text.
However, it seems impossible to reliably mark the text, while the terminal is not still (i.e., it outputs text to the terminal, making the terminal content change).
Is there any way to "freeze" the terminal, so that I can mark and copy (yank) terminal output, while the terminal is outputting text?


text:
Q: How can i use ModelName.objects.aggregate(Sum('field_name')) here? I need to use Sum() instead of
if name in ingredients.keys():
    ingredients[name] += units
else:
    ingredients[name] = units

but I have no idea how, because I have a long chain of relations. Here is my code:
def shopping_list_ingredients(request):
    shopping_list = ShoppingList.objects.filter(user=request.user).all()
    ingredients = {}
    for item in shopping_list:
        for x in item.recipe.recipe_ingredient.all():
            name = f'{x.ingredient.title} ({x.ingredient.unit})'
            units = x.count
            if name in ingredients:
                ingredients[name] += units
            else:
                ingredients[name] = units
    download = []
    for key, units in ingredients.items():
        download.append(f'{key} - {units} \n')
    return download

A: def shopping_list_ingredients(request):
shopping_list = ShoppingList.objects.filter(user=request.user).all()
ingredients = {}
for item in shopping_list:
    #if item.recipe.recipe_ingredient.all().ingredient.unit is dict
    values = item.recipe.recipe_ingredient.all().ingredient.unit.values()
    total = sum(values)
    #if it's list
    total = sum(item.recipe.recipe_ingredient.all().ingredient.unit)


text:
Q: Toggling category markers with google maps I have multiple categories for the markers I show in my google map. The markers I have come from this dummydata I'm using for now:
var locations = [{
                    "Locatie":    "Den Bosch",
                    "Latitude":   "51.700651",
                    "Longitude":  "5.309143",
                    "Categorie":  "1"
                    },
                    {
                    "Locatie":    "Tilburg",
                    "Latitude":   "51.555728",
                    "Longitude":  "5.063324",
                    "Categorie":  "2"
                    },
                    {
                    "Locatie":    "Breda",
                    "Latitude":   "51.582190",
                    "Longitude":  "4.772186",
                    "Categorie":  "2"
                    },
                    {
                    "Locatie":    "Amsterdam",
                    "Latitude":   "52.361345",
                    "Longitude":  "4.887543",
                    "Categorie":  "1"
                    },
                    {
                    "Locatie":    "Utrecht",
                    "Latitude":   "52.076974",
                    "Longitude":  "5.103149",
                    "Categorie":  "1"
                    },
                    {
                    "Locatie":    "Heerenveen",
                    "Latitude":   "52.956084",
                    "Longitude":  "5.918884",
                    "Categorie":  "2"
                    },
                    {
                    "Locatie":    "Willekeurige Locatie",
                    "Latitude":   "57.956084",
                    "Longitude":  "8.918884",
                    "Categorie":  "2"
                    }];

As you can see I kept it simple and just made two categories, 1 or 2. The markers are placed on the map with this piece of code:
markers = [];

   var i, newMarker;

   for (i = 0; i < locations.length; i++) {
     newMarker = new google.maps.Marker({
       position: new google.maps.LatLng(locations[i].Latitude, locations[i].Longitude),
       map: map,
       title: locations[i].Locatie
     });

     newMarker.category = locations[i].Categorie;
     newMarker.setVisible(true);

     markers.push(newMarker);

     google.maps.event.addListener(newMarker, 'click', (function(newMarker, i) {
        return function() {
          infowindow.setContent(locations[i].Locatie);
          infowindow.open(map, newMarker);
        }
      })(newMarker, i));
   }

This step also works fine. Notice that when Google Maps loads I display all the markers regardless of the category they're in. Now what I want the user to be able to do is toggle markers from categories on and off, I have a function that fires when a toggle button is clicked:
function displayMarkers(category) {
  var i;

  for (i = 0; i < markers.length; i++) {
    if (markers[i].category === category) {
      markers[i].setVisible(true);
    }
    else {
      markers[i].setVisible(false);
    }
  }
}

What this does now is only show the markers that belong to the clicked category while it should toggle them on or off depending on if they were allready visible or not. I suppose i'd have to check if a category of markers is allready visible on the map or not and then based on that decide if I have to set setVisible to true or false for that specific group. I do not know how to achieve this with google maps. Does anyone know how I can achieve this? I added some other pieces of my code that might be relevant to the question.
jQuery that handles the buttons:
jQuery('.cat-toggle').click(
     function () {
       var category = jQuery(this).attr("title");
       displayMarkers(category);
       jQuery(this).toggleClass("selected");
     }
);

The HTML for the buttons:
category 1
category 2

A: Sorry if I deviate a little from your code.
But how about this?

*

*When creating the markers, you add an extra field 'visible' to var locations, and set it default to true
locations[i].visible = true;

Also, in the markup I prefer to keep data in the data- attribute, so example:
category 1

You read this value like this:
var cat = $(this).data('cat');

*

*Then my click event becomes this: look in the code, at  $('.cat-toggle').click

Here is some code you can copy/paste as is.
( The info window doesn't work in this code; you have the extra code... )
But the toggle works.

category 1
category 2

Groeten uit Brussel


text:
Q: how to send pickup instructions to the UberEats delivery driver I'm planning to use UberEats APIs for a project and one of the requests I got was, whether we could send messages to the UberEats Drivers? So the platform we are building is for resturents, and ideally once the resturent receives an order and accepts it, we want to send a message to the delivery driver, an small instruction message about the pickup location.
For example, "Hi, Come to counter 3 to pickup the order no: ****"
Is there a way we could achive this?


text:
Q: Linq to get List with most elements and biggest diff inside it's elements from a List> I have a List<List<int>> testLists
I want to find the longest one AND where the numbers inside the list have the biggest difference. I know there is a one liner Linq for it, but I can't seem to figure it out.
It has to be something like this:
List<int> myMaxTest = testLists
                           .OrderByDescending(s => s.Count) // Longest
                           .ThenBy( s => s.Max(s.Max() - s.Min())) // Biggest Difference
                           .First();  // Only one list from the top

This is not correct. It won't compile. My ThenBy part is not ok. Can you guys show me the way to do this?
Thanks!

A: Your ThenBy should just be
.ThenByDescending(s => s.Max() - s.Min()) // Biggest difference

You're currently asking for it to order the lists by each individual list's "highest Max - Min". That doesn't make sense, and that (luckily!) means it didn't compile.


text:
Q: Keyup function into form element I have a script I am using to copy a field into another input field using keyup blur paste. This script works, however I need to modify it to also go into two different form elements which are named data-cost="" and debt="", instead of the

This is the script as I have it now :
$(function () {
    $('#account_balance1').on('keyup blur paste', function() {
        var self = this;
        setTimeout(function() {
            var str = $(self).val();
            $("#viewer").text(str.replace(/^\$/, ''));
        }, 0);
    });

    $("#viewer").text($('#Website').val().replace(/^\$/, ''));
});

This is the html :

<input type="text" class="balance" id="account_balance1" name="cardb" value=""/>

<input data-cost="" debt="" value="" type="checkbox" name="f_2[]"/>

A: if you need the two attributes (data-cost and debt) to be each set to your value you need:
$("input[data-cost][debt]").attr('data-cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").attr('debt',str.replace(/^\$/, ''));

A: Just use that selector then
$("input[data-cost][data-debt]")

A: I think you're maybe having a fundamental misunderstanding of what the data attributes are for? You're aware that they will not be posted with the form? I think what you're looking for is the data function which will allow you to set the data attributes http://api.jquery.com/data/.
Perhaps you want data-cost and data-debt?
So if your input looks like this:
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" id="checkboxId" />

Then you can set the values in your javascript like this:
var value1="some value";
var value2="another value";
$('#checkboxId').data('cost', value1);
$('#checkboxId').data('debt', value2);

I don't believe having an attribute named simply "debt" as you have it above is valid.

A: I'd do it this way (setTimeout was useless) :
$(function () {
    $('#account_balance1').on('keyup blur paste', function () {
        var self = this;
        var nextCheckbox = $(self).next("input[type='checkbox']");
        var str = $(self).val();
        $("#viewer").text(str.replace(/^\$/, ''));
        nextCheckbox.data({
            cost: str,
            debt: str
        });
        /*
        You won't be able to see changes if you inspect element,
        so just check in console
        */
        console.log(nextCheckbox.data());

});

});
And your html markup must be slightly modified :

<input type="text" class="balance" id="account_balance1" name="cardb" value="" />

<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" />


text:
Q: What does this mean & what impact does it have: Failed to download repository information Today out of the clear blue I received the following message when I ran my updater under Ubuntu 13.10 laptop. Failed to download repository information. I see there are a ton of questions regarding this issue but this is not a duplicate because this is just more of an over view that I am looking for. So I did apt-get update and started seeing a bunch of 404 errors. I am far from a Linux pro, so how do I read these errors and how can I tell if these are important? I can tell you I have never manually modified the source list directly. And if these are dead ppa sources how can I remove and what does the letter mean in the below, almost looks like a drive letter but I dont have a W: drive.
W: Failed to fetch http://ppa.launchpad.net/pmcenery/ppa/ubuntu/dists/saucy/main/binary-amd64/Packages  404  Not Found
W: Failed to fetch http://ppa.launchpad.net/pmcenery/ppa/ubuntu/dists/saucy/main/binary-i386/Packages  404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.

A: Generally it means that this repository is offline or does not exist anymore.
You can remove it in software center, just click Edit in top bar and then in Software Sources, a new window should appear. In the new window go to the 2nd tab, then select and remove the pmcenery repository.


text:
Q: Value is not assigning inside then statement In this js file I have defined this const Device that is the name of the mobile im using. The thing is when I call Device from another js it returns it empty. Why?
import DeviceInfo from 'react-native-device-info';

var Device = ''

DeviceInfo.getDeviceName().then(deviceName => {
  Device = deviceName + ' ('+DeviceInfo.getSystemVersion()+')'
});

export default Device;

A: The reason why your current approach doesn't work is because DeviceInfo.getDeviceName is an asynchronous call that returns a Promise which resolves with the deviceName.
var Device = ''

DeviceInfo.getDeviceName().then(...)

// the call above will not wait before it goes to next line
// so `Device` will stay as empty string and will be exported as such

export default Device

Instead, if you want to re-use this logic in multiple places, I suggest turning this into a function, like in the following example:
import DeviceInfo from 'react-native-device-info';

function getDeviceFullName() {
  return DeviceInfo.getDeviceName()
    .then(deviceName => {
      return `${deviceName} (${DeviceInfo.getSystemVersion()})`
    })
}
export default getDeviceFullName

Then, somewhere else, you could call this function like in the following example:
import getDeviceFullName from './getDeviceFullName'

class App extends React.Component {
  state = {deviceName: ""}

  componentDidMount() {
    getDeviceFullName()
      .then(deviceName => {
        this.setState({ deviceName })
      })
      .catch(/* handle errors appropriately */)
  }

  render() {
    return this.state.deviceName === ""
      ? "Loading"
      : this.state.deviceName;
  }
}

EDIT as OP mentioned something about Formik integration.
Haven't tested this, but something like the following would be my approach.
class MyReactNativeForm extends React.Component {
  state = {
    initialValues: { email: "johndoe@gmail.com", deviceName: "" }
  }

  componentDidMount() {
    getDeviceFullName()
      .then(deviceName => {
        this.setState(prevState => {
          return {
            initialValues: {...prevState.initialValues, deviceName}
          }
        })
      })
      .catch(/* handle errors appropriately*/)
  }

  render() {
    return this.state.initialValues.deviceName === ""
      ? "Loading"
      : <Formik initialValues={this.state.initialValues} />
}

A: Edit: Someone else posted a great answer while I was typing mine up. My answer re-uses the value for Device because that is how the original question worked. Like the approved answer, you don't need to set it and forget it, but instead you can only return a cb/promise that always gets the most recent data.
Two things immediately stand out. Like @mhodges says, you can't reassign a value to a constant. Instead, you should use let.
Your next issue is trying to export the value returned by an asynchronous call. When you import Device from your js file, the export statement executes before you re-assign the value of Device.
What if you exported your async function or a callback instead?
Promise'able:
var Device;
export function getDeviceInfo() {
  if (Device) return Promise.resolve(Device);
  return DeviceInfo.getDeviceName().then(deviceName => {
    Device = deviceName + ' ('+DeviceInfo.getSystemVersion()+')';
    return Promise.resolve(Device);
  });
}

Usage might look like:
import { getDeviceInfo } from './utils';
getDeviceInfo().then((deviceInfo) => console.log('Got it!', deviceInfo));

Callback'able:
var Device;
export function getDeviceInfo(cb) {
  if (Device) return cb(Device);
  DeviceInfo.getDeviceName().then(deviceName => {
    Device = deviceName + ' ('+DeviceInfo.getSystemVersion()+')';
    cb(Device);
  });
}

Usage might look like:
import { getDeviceInfo } from './utils';
getDeviceInfo(function(deviceInfo) {
  console.log('Got it!', deviceInfo)
});


text:
Q: How to ensure the right parameters is passed to a function call declared in a loop? I'm new to node, but I love it already. Only issue is, the asynchronous functionality is killing me.
I am using the google package to get my websites' rankings in google as so:
for (var j=0;j<keywords.length;j++) {
    var keyword = keywords[j];

    google(keyword, function(err, next, links) {

    console.log('Searching for keyword "' + keyword + '" in google.' + google.tld + ' ('+ google.lang +')');
      if (err) console.error(err);

      for (var i = 0; i < links.length; ++i) {

        var rank = i+1;

        console.log(keyword + ' #'+ rank + ' - ' + links[i].link + ' | ' + links[i].title);
        //link.href is an alias for link.link
        //console.log(links[i].description + "\n");
      }
      console.log('\n');
    });

}

My problem is that it the console log shows the same keyword for all websites, although I have defined three in my keywords array.
What am I missing?

A: The immediate problem here is that the j and keyword variables go on changing before the callbacks are called.
A simple solution is to protect this variable in a closure :
for (var j=0; j<keywords.length; j++) {
    (function(j){
        var keyword = keywords[j];
        ...
    })(j);
}

When you're just working with a simple array, then you can also use a closure through forEach :
keywords.forEach(function(keyword, j){
     ...
});

To deal with this kind of asynchronous problems, you should now dive in promises which help structure your code in a clearer (and less indented) way. An introduction.


text:
Q: Is it possible to store Ajax call as an object? This isn't necessarily a "how to" question, but rather an ask to help improve upon my own understanding of JavaScript and Jquery. I've been using Jquery a lot lately in  my current job and all of my jquery involves a lot of AJAX calls. In several files I have at least 6 ajax calls for different situations and I was wondering if there was a more efficient way to do this from building the code. One of my colleagues who doesn't code suggested turning the AJAX call into a property and passing along arguments. Is this even possible? If not, is there a better and easier way to handle multiple AJAX calls in one file?
Thank you for your input and I hope to learn a lot from this
Here is an example of one of our AJAX calls
$.ajax({
      type: 'POST',
      url: '',
      data: {
        method: 'custCodeData',
        custCode: $('#custCode').val()
      },
      dataType: 'JSON',
      success: function (data) {
        var array = data.DATA;
        $("#response tr:not(:first)").remove();
        for (var i = 0; i < array.length; i++) {
          var newRow = table.insertRow();
          for (var j = 0; j < array[i].length; j++) {
            if (j < 7) {
              var cell = newRow.insertCell(j);
              cell.innerHTML = array[i][j];
            }

            if (j === 0) {
              if (array[i][0] == false) {
                cell.innerHTML = "No";
              }
              if (array[i][0] == true) {
                cell.innerHTML = "Yes";
              }
            }

            if (j === 2) {
              if (array[i][8] == false) {
                cell.innerHTML = `${array[i][2]}     `
              } else if (array[i][8] = true) {
                cell.innerHTML = `${array[i][2]}         `
              }
            }
          }
        }
        $("#response tr:contains(Yes)").css({"background-color": "#ff0000", "color": "#FFF"});
      }
    })

A: function doTheSameExactAJAXThingAgain(method){
    $.ajax({
      type: 'POST',
      url: '',
      data: {
        method: method,//<- METHOD here
        custCode: $('#custCode').val()
      },
      dataType: 'JSON',
      //...etc
}

doTheSameExactAJAXThingAgain('custCodeData');
doTheSameExactAJAXThingAgain('compNameData');
//etc.


text:
Q: While or Tail Recursion in F#, what to use when? Ok, only just in F# and this is how I understand it now :

*

*Some problems are recursive in nature (building or reading out a  treestructure to name just one) and  then you use recursion.  In these cases you preferably use tail-recursion to give the stack a break

*Some languagues are pure functional, so you have to use recursion in stead of while-loops, even if the problem is not recursive in nature
So my question : since F# also support the imperative paradigm, would you use tail recursion in F# for problems that aren't naturally recursive ones?  Especially since I have read the compiler recongnizes tail recursion and just transforms it in a while loop anyway?
If so : why ?

A: Honestly, any problem that you can solve with a loop is already a naturally recursive one, as you can translate both into (usually conditional) jumps in the end.
I believe you should stick with tail calls in almost all cases where you must write an explicit loop. It is just more versatile:

*

*A while loop restricts you to one loop body, while a tail call can allow you to switch between many different states while the "loop" is running.

*A while loop restricts you to one condition to check for termination, with the tail recursion you can have an arbitrarily complicated match expression waiting to shunt the control flow off somewhere else.

*Your tail calls all return useful values and can produce useful type errors. A while loop does not return anything and relies on side effects to do its work.

*While loops are not first class while functions with tail calls (or while loops in them) are. Recursive bindings in local scope can be inspected for their type.

*A tail recursive function can easily be broken apart into parts that use tail calls to call each other in the needed sequence. This may make things easier to read, and will help if you find you want to start in the middle of a loop. This is not true of a while loop.

All in all while loops in F# are only worthwhile if you really are going to be working with mutable state, inside a function body, doing the same thing repeatedly until a certain condition is met. If the loop is generally useful or very complicated, you may want to factor it out into some other top level binding. If the data types are themselves immutable (a lot of .NET value types are), you may gain very little from using mutable references to them anyway.
I'd say that you should only resort to while loops for niche cases where a while loop is perfect for the job, and is relatively short. In many imperative programming languages, while loops are often twisted into unnatural roles like driving stuff repeatedly over a case statement. Avoid those kinds of things, and see if you can use tail calls or, even better, a higher order function, to achieve the same ends.

A: Many problems have a recursive nature, but having thought imperatively for a long time often prevents us from seeing this.
In general I would use a functional technique wherever possible in a functional language - Loops are never functional since they exclusively rely on side-effects. So when dealing with imperative code or algorithms, using loops is adequate, but in functional context, they're aren't considered very nice.
Functional technique doesn't only mean recursion but also using appropriate higher-order functions.
So when summing a list, neither a for-loop nor a recursive function but a fold is the solution for having comprehensible code without reinventing the wheel.

A: The best answer is 'neither'.  :)
There's some ugliness associated with both while loops and tail recursion.
While loops require mutability and effects, and though I have nothing against using these in moderation, especially when encapsulated in the context of a local function, you do sometimes feel like you're cluttering/uglifying your program when you start introducing effects merely to loop.
Tail recursion often has the disadvantage of requiring an extra accumulator parameter or continuation-passing style.  This clutters the program with extra boilerplate to massage the startup conditions of the function.
The best answer is to use neither while loops nor recursion.  Higher-order functions and lambdas are your saviors here, especially maps and folds.  Why fool around with messy control structures for looping when you can encapsulate those in reusable libraries and then just state the essence of your computation simply and declaratively?
If you get in the habit of often calling map/fold rather than using loops/recursion, as well as providing a fold function along with any new tree-structured data type you introduce, you'll go far.  :)
For those interested in learning more about folds in F#, why not check out my first three blog posts in a series on the topic?

A: In order of preference and general programming style, I will write code as follows:
Map/fold if its available
let x = [1 .. 10] |> List.map ((*) 2)

Its just convenient and easy to use.
Non-tail recursive function
> let rec map f = function
    | x::xs -> f x::map f xs
    | [] -> [];;

val map : ('a -> 'b) -> 'a list -> 'b list

> [1 .. 10] |> map ((*) 2);;
val it : int list = [2; 4; 6; 8; 10; 12; 14; 16; 18; 20]

Most algorithms are easiest to read and express without tail-recursion. This works particularly well when you don't need to recurse too deeply, making it suitable for many sorting algorithms and most operations on balanced data structures.
Remember, log2(1,000,000,000,000,000) ~= 50, so log(n) operation without tail-recursion isn't scary at all.
Tail-recursive with accumulator
> let rev l =
    let rec loop acc = function
        | [] -> acc
        | x::xs -> loop (x::acc) xs
    loop [] l

let map f l =
    let rec loop acc = function
        | [] -> rev acc
        | x::xs -> loop (f x::acc) xs
    loop [] l;;

val rev : 'a list -> 'a list
val map : ('a -> 'b) -> 'a list -> 'b list

> [1 .. 10] |> map ((*) 2);;
val it : int list = [2; 4; 6; 8; 10; 12; 14; 16; 18; 20]

It works, but the code is clumsy and elegance of the algorithm is slightly obscured. The example above isn't too bad to read, but once you get into tree-like data structures, it really starts to become a nightmare.
Tail-recursive with continuation passing
> let rec map cont f = function
    | [] -> cont []
    | x::xs -> map (fun l -> cont <| f x::l) f xs;;

val map : ('a list -> 'b) -> ('c -> 'a) -> 'c list -> 'b

> [1 .. 10] |> map id ((*) 2);;
val it : int list = [2; 4; 6; 8; 10; 12; 14; 16; 18; 20]

Whenever I see code like this, I say to myself "now that's a neat trick!". At the cost of readability, it maintains the shape of the non-recursive function, and found it really interesting for tail-recursive inserts into binary trees.
Its probably my monad-phobia speaking here, or maybe my inherent lack of familiarity with Lisp's call/cc, but I think those occasions when CSP actually simplifies algorithms are few and far between. Counter-examples are welcome in the comments.
While loops / for loops
It occurs to me that, aside from sequence comprehensions, I've never used while or for loops in my F# code. In any case...
> let map f l =
    let l' = ref l
    let acc = ref []
    while not <| List.isEmpty !l' do
        acc := (!l' |> List.hd |> f)::!acc
        l' := !l' |> List.tl
    !acc |> List.rev;;

val map : ('a -> 'b) -> 'a list -> 'b list

> [1 .. 10] |> map ((*) 2);;
val it : int list = [2; 4; 6; 8; 10; 12; 14; 16; 18; 20]

Its practically a parody of imperative programming. You might be able to maintain a little sanity by declaring let mutable l' = l instead, but any non-trivial function will require the use of ref.

A:
for problems that aren't naturally recursive ones
  ..
  just transforms it in a while loop anyway

You answered this yourself.
Use recursion for recursive problems and loop for things that aren't functional in nature.
Just always think: Which feels more natural, which is more readable.


text:
Q: What is the meaning of application without abstraction in the left part? Lambda term can be:

*

*variable

*lambda abstraction (for example \x.t)

*application. If t and s are lambda terms, then ts is an application.

So, application with abstraction in the left part (for example (\x.t)a) looks good. It looks like function calling. But what does application mean when left part is a variable or other application? What does mean ab, ((\x.x)a)b or a(\x.x) if a and b are variables?

A: ((\x.x)b)c is a function application.  Here It applies b to c.
((\x.x)b)c
= bc

a(\x.y) is a function application, applying the function a to its sole argument, which happens to be a function, namely the function that returns y (a free variable).
One of the featues of the lamdba calculus is the ease in which functions can be applied to functions and functions can take other functions as arguments.  Your two examples show both cases nicely.
EDIT There are (at least) two versions of the lambda calculus: the untyped and the typed.  In the untyped calculus, which you are using here, anything can be applied to anything.  In the typed calculus there exist base types which are not functions, such as the type of propositions and the type of "individuals."  So you would only be able to write ab if the type of a were a function type mapping the type of b to something.