text:
Q: Haskell scope of a function I am trying to do something that will take as an input functions defined after 'where' clause and output a string composed of it. It is mentioned to be something that will scope the functions listed after 'where' clause to writeOut function.
What I want to come with(It's not working):
writeOut :: [Char] -> [Char]
writeOut x = x
 where
 number :: Char -> [Char]
 number n = [n]
 multiplication :: [Char] -> [Char] -> [Char]
 multiplication a b = a++"*"++b
 addition :: [Char] -> [Char] -> [Char]
 addition a b = "("++a++"+"++b++")"
 subtraction :: [Char] -> [Char] -> [Char]
 subtraction a b = "("++a++"-"++b++")"
 ...

So, for example, for an input:
writeOut multiplication (addition (number '1') (subtraction (number '2') (number '3'))) (number '3')

would give me an output:
(1+(2-3))*3

it is working properly when I delete writeOut function and just leave what is after 'where' keyword, but I really want to 'lock it' under the 'writeOut' function.
You may ask why I am trying to do it, as I want another function that will calculate the expression for me:
writeOut multiplication (addition (number '1') (subtraction (number '2') (number '3'))) (number '3')

Output: (1+(2-3))*3

calc multiplication (addition (number '1') (subtraction (number '2') (number '3'))) (number '3')

Ouput: 0

Just in case you want to see what is working "properly":
number :: Char -> [Char]
number n = [n]
multiplication :: [Char] -> [Char] -> [Char]
multiplication a b = a++"*"++b
addition :: [Char] -> [Char] -> [Char]
addition a b = "("++a++"+"++b++")"
subtraction :: [Char] -> [Char] -> [Char]
subtraction a b = "("++a++"-"++b++")"

A: It appears you are trying to implement a DSL and an evaluator for that DSL. Rather than a set of functions, define a data type, then write an evaluator for that type.
data Expr = Number Int
          | Mult Expr Expr
          | Add Expr Expr
          | Subtract Expr Expr

writeOut :: Expr -> String
writeOut (Number x) = show x
writeOut (Add x y) = "(" ++  writeOut x ++ " + " ++ writeOut y ++ ")"
writeOut (Subtract x y) = "(" ++  writeOut x ++ " - " ++ writeOut y ++ ")"
writeOut (Mult x y) = "(" ++ writeOut x ++ " * " ++ writeOut y ++ ")"

print $ writeOut (Mult (Add (Number 1) (Subtract (Number 2) (Number 3))) (Number 3)

I leave it as an exercise to eliminate the outermost parentheses.
As a bonus assignment, define a different evaluator that evaluate the expression to a single Int, rather than display it:
evaluate :: Expr -> Int
evaluate = undefined

A: You can make use of the type system to prevent people from accessing what is wrapped in a data constructor. For example:
module MyModule(
    Locked
  , number, multiplication, addition, subtraction
  , writeOut
  ) where

data Locked a = Locked a

writeOut :: Locked a -> a
writeOut (Locked a) = a

number :: Char -> Locked [Char]
number n = Locked [n]

multiplication :: Locked [Char] -> Locked [Char] -> Locked [Char]
multiplication (Locked a) (Locked b) = Locked (a++"*"++b)

addition :: Locked [Char] -> Locked [Char] -> Locked [Char]
addition (Locked a) (Locked b) = Locked ("("++a++"+"++b++")")

subtraction :: Locked [Char] -> Locked [Char] -> Locked [Char]
subtraction (Locked a) (Locked b) = Locked ("("++a++"-"++b++")")
The module here thus does not export the Locked data constructor, and thus although you can use number, multiplication, etc. everywhere, you can not access the result wrapped in the Locked data constructor without eventually making use of writeOut.
Another advantage of using Locked, is that people can not use an arbitrary String: indeed, number here only allows to introduce a single character directly, you thus can not concatenate two arbitrary characters. The Locked thus prevents pople from generating something like 13, since number '1' and number '3' can only be combined with addition, subtraction, etc.
But people can still use the functions everywhere, except that it will be quite useless without eventually using writeOut.

A: At the moment, your definitions of number, multiplication, addition, and so on are all functions operating on strings or characters. So, even supposing they were defined at the top level, so you could refer to them in an expression like this:
writeOut multiplication (addition (number '1') (subtraction (number '2') (number '3'))) (number '3')

What this would imply is that writeOut must be able to accept the function multiplication as its first argument, the result of (addition …) as its second, and the result of (number …) as its third, so it would need a type like ([Char] -> [Char] -> [Char]) -> [Char] -> [Char] -> [Char]. Overloading writeOut to work this way and allow any other expression as arguments isn't really possible; if you try to do it using typeclasses, you'll quickly find that it produces a lot of ambiguous types and thus requires a lot of type annotations.
But there are multiple better approaches, depending on what you're really trying to accomplish here. The simplest thing is to move these functions to the top level:
writeOut :: [Char] -> [Char]
writeOut x = x

number :: Char -> [Char]
number n = [n]

multiplication :: [Char] -> [Char] -> [Char]
multiplication a b = a++"*"++b

…

And invoke writeOut like writeOut (multiplication (number '2') (number '3')) with the expression wrapped in parentheses. But here writeOut is completely redundant: it's equivalent to the identity function id, which merely returns its argument unmodified. All the actual work of constructing a string is being done by the other functions.
That raises the essential point: these functions aren't really constructing an expression, they're building a string, and throwing away information about the structure of the expression. If you also want to be able to compute the value of the expression with your calc function, you'll need to generalise this somewhere.
There are two typical ways to do this.
One way is to make a data type for representing expressions, and then your two functions writeOut and calc will consume a value of this type and produce a string or number, respectively:
-- An expression is:
data Expression

  -- A literal number, containing an 'Int' (or whichever type you need);
  = Number Int

  -- Or an operation on some subexpressions.
  | Addition Expression Expression
  | Multiplication Expression Expression
  | Subtraction Expression Expression
  | …

  -- You can add this clause to allow 'Expression' to be displayed
  -- as Haskell code for debugging purposes in GHCi. Generally you
  -- should derive 'Show' instead of making your own instance.
  --
  -- deriving (Show)

writeOut :: Expression -> String
writeOut expression = case expression of
  Number n -> show n
  Addition a b -> concat ["(", writeOut a, " + ", writeOut b, ")"]
  …

calc :: Expression -> Int
calc expression = case expression of
  Number n -> n
  Addition a b -> calc a + calc b
  …

Then you can construct an expression and, separately, transform it into a string, number, or whatever else you need, e.g. in GHCi:
> :type Number
Number :: Int -> Expression

> :type Multiplication
Multiplication :: Expression -> Expression -> Expression

> example = Multiplication (Addition (Number 1) (Subtraction (Number 2) (Number 3))) (Number 3)

> :type example
example :: Expression

> writeOut example
"((1+(2-3))*3)"

> calc example
0

> calc (Plus (Number 1) (Number 2))
3

Notice that you still need parentheses around the argument of writeOut or calc; if you wrote writeOut Plus (Number 1) (Number 2), that would mean calling writeOut with three arguments, Plus, Number 1, and Number 2, which is not what you want.
If you don't want to use the capital constructor names, you can make lowercase constructor functions that are equivalent:
number :: Int -> Expression
number n = Number n
-- Or:
-- number = Number

addition :: Expression -> Expression -> Expression
addition a b = Addition a b
-- Or:
-- addition = Addition

…

The second technique is known as tagless final style. It's slightly more advanced and probably not what you want here, but I include it for completeness. Essentially, instead of a data type, you make a typeclass, representing the set of types that are interpretations of expressions. In your case, those are String, representing the interpretation of an expression as pretty-printed text (writeOut), and Int (or another numeric type like Integer, Rational, or Double), the interpretation of an expression as a value.
You express that by making a typeclass whose methods are the possible terms in your expressions:
-- The class of interpretations of expressions.
class Interpretation a where
  number :: Int -> a
  addition :: a -> a -> a
  subtraction :: a -> a -> a
  multiplication :: a -> a -> a
  …

And then instances for the different interpretation types:
-- Place this at the top of the file if you include
-- the type signatures in the definitions below.
{-# LANGUAGE InstanceSigs #-}

instance Interpretation String where

  number :: Int -> String
  number n = show n

  addition :: String -> String -> String
  addition a b = concat ["(", a, " + ", b, ")"]

  …

instance Interpretation Int where

  number :: Int -> Int
  number n = n

  addition :: Int -> Int -> Int
  addition a b = a + b

  …

Then an expression like multiplication (addition …) (number 3) has an overloaded type, Interpretation a => a, and you can evaluate it at different concrete types:
> example :: Interpretation a => a; example = multiplication (addition (number 1) (subtraction (number 2) (number 3))) (number 3)

> example :: String
"((1+(2-3))*3)"

> example :: Int
0

However, while this is flexible, it also makes it more involved to introduce new operations, and requires some slightly more advanced type system features in order to do things like parsing an expression from a string at runtime.
Therefore I recommend you stick to the data type approach, which is what a Haskeller would generally reach for by default unless they had a specific reason not to.
If you want to confine the construction and interpretation of expressions to these particular functions, what you can do is only export the addition, multiplication, &c. functions from a module, and leave the data type private, then the only way to construct an argument to writeOut & calc will be to call those functions:
module Expr
  ( number
  , addition
  , subtraction
  …

  , writeOut
  , calc
  ) where

-- Expression data type, *not* exported:

data Expression = …

-- Constructor functions, exported:

number :: Int -> Expression
number = Number

…

-- Computations on expressions, also exported:

writeOut :: Expression -> String
writeOut = …

calc :: Expression -> Int
calc = …


text:
Q: capturing Standard Output when executing Powershell C# I trying to execute a simple powershell command in c# and output the result. Powershell v5.1 on Server 2016
PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-DhcpServerInDC");
Collection<PSObject> results = ps.Invoke();
StringBuilder sb = new StringBuilder();
foreach (PSObject obj in results) {
    sb.AppendLine(obj.ToString()); }
txt_adt_updateTextbox.Text = sb.ToString();

But instead of getting a list of DHCP servers and their IP addresses, I get the following.

DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC
  DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC
  DhcpServerInDC DhcpServerInDC DhcpServerInDC DhcpServerInDC
  DhcpServerInDC

A: The nicely formatted list/table you typically see in PowerShell is shown by the host (e.g. console, ISE, etc). In this case you are the host, so you need to do the formatting.
From the documentaion, it looks like you should get back a collection of WMI objects.  Use the technique shown in one of my previous answers to get the data you want:
Dealing with CimObjects with PowerShell inside C#

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiprocessing nested numerical integrals in python I'm working with nested numerical integrals in python where the limits of each layer depends on the next layer out. The overall structure of my code looks like
import numpy as np
import scipy.integrate as si

def func(x1, x2, x3, x4):
    return x1**2 - x2**3+x3*x2 - x4*x3**3

def int1():
    """integrates `int2` over x1"""
    a1, b1 = -1, 3
    def int2(x1):
        """integrates `func` over x2 at given x1."""
        #partial_func1 = lambda x2: func(x1, x2)
        b2 = 1 - np.abs(x1)
        a2 = -np.abs(x1**3)
        def int3(x2):
            a3 = x2
            b3 = -a3
            def int4(x3):
                partial_func = lambda x4: func(x1, x2, x3, x4)
                a4 = 1+np.abs(x3)
                b4 = - a4
                return si.quad(partial_func,a4,b4)[0]
            return si.quad(int4, a3, b3)[0]
        return si.quad(int3, a2, b2)[0]
    return si.quad(int2, a1, b1)[0]
result = int1()  # -22576720.048151683

In the full version of my code, the integral and the limits are complex and it takes several hours to run, which is inconvenient. Each integral seems like it could be easily parallelized though: it seems like I should be able to use multiprocessing to distribute the integration to multiple CPUs and speed up the run time.
Referring to some other posts on stack overflow, I tried the following:
def testfunc(intfunc,fmin,fmax):
    return scint.quad(intfun,fmin,fmax,epsabs=10**-40)[0]

result = pool.map(partial(partial(testfunc, intfunc = int4),fmin = a3),[b3])

But I got an error that the local object can't be pickled.
Another resource I came across was at http://catherineh.github.io/programming/2016/10/04/parallel-integration-for-mere-mortals
But I need a function where I can pass the limits through as inputs as well (hence my use of partials).
Does anyone know how to resolve these issues? I think a solution would be some version of pool.map that could handle multiple inputs would be great, but if there's something wrong with my use of partials, that would be great to find out too.
Thanks in advance and let me know if there's anything here that can be cleared up!

A: This answer probably isn't satisfactory, but hopefully it'll give some insight into what field the question falls.
To reiterate, the original problem is to compute the quadruple integral
integrate(
    integrate(
        integrate(
            integrate(
                f(x1, x2, x3, x4),
                [1+abs(x3), -1-abs(x3)]
                ),
            [x2, -x2]
            ),
         [1-abs(x1), -x1**3]
         ),
    [-3, 1])

Mathematically, one could formulate this as
integrate(f(x1, x2, x3, x4), Omega)

where Omega is a four-dimensional domain defined by the integral limits above. Had the domain been in one, two, or three dimensions, then the answer to your question would be clear:

*

*Discretize your complex domain into lines, triangles, or tetrahedra (those are the simplices in dimensions 1, 2, 3, respectively) (using one of many mesh tools), and then

*use numerical quadrature on each of the lines/triangles/tetrahedra (e.g., from here).
Unfortunately, I'm not aware of any tool that discretizes a four-dimensional domain into 4-simplices, nor of quadrature rules for 4-simplices (except perhaps the vertex and midpoint rules). Both, however, would be possible to create in general; particularly a bunch of quadrature rules should be easy to come up with.
For the sake of completeness, let me mention that there is at least one class of domains for which integration rules exist in any dimension: the hypercube.

A: Update:
After much testing and restructuring, it seems that the best way to take care of this is not to nest the functions or the definitions, but rather to make use of the args parameter in the scipy.integrate.quad function to pass external variables through to inner integrations.
Many thanks to those who commented!


text:
Q: Sinatra haml page is called twice   get '/test' do
     session[:my_session_id] = generate_random_id()
     puts 'begin haml debug'
     haml :"static/haml_page", :locals=>{:session_id => session[:my_session_id]}
  end

I see in a log that a page above is constantly called twice:
begin haml debug
127.0.0.1 - - [02/Nov/2012 00:00:01] "GET / HTTP/1.1" 200 4317 1.5421
127.0.0.1 - - [02/Nov/2012 00:00:01] "GET /js/base/jquery.pjax.002902.js HTTP/1.1" 304 - 0.0234
[2012-11-02 00:00:01] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
127.0.0.1 - - [02/Nov/2012 00:00:01] "GET /css/docs.002902.css HTTP/1.1" 200 165 0.1086
.................................
begin haml debug
127.0.0.1 - - [02/Nov/2012 00:00:04] "GET / HTTP/1.1" 200 4317 1.9288

It makes me have some issues. Why is this happening?

A: I've moved to Puma server insted of Webrick because of similar issues.
Unfortunately I've lost example code with this problem.
In any case, if you have such problems please learn what brouser does:

*

*Developers tool > Network (tab) will show exact sourse of request if it exists

*Try to narrow this issue/bug by reducing code i.e. comment all JavaScripts, change page contents to 'Hello Wold' and observe is problem still happens

*Share your code:)

Sorry for posting here, I don't know how to post this as addition to your qestion.

A: This is a hack, but if you really need to get it to only run the code once:
Create a global boolean variable.  in the route, wrap everything in a conditional on the boolean.  if false, set it true, run your code, and set it false again.


text:
Q: I do not understand a statement about the local truncation error of Runge-Kutta methods
\begin{align}
w_0 &= \alpha
\\
w_{i+1}&=w_i +a_1 f(t_i,w_i) + a_2 f(t_i+\alpha_2,w_i+\delta_2 f(t_i,w_i))
\end{align}
  for each $i =0,1,2,...,N-1$, cannot have local truncation error $O(h^3)$ for any choice of constants $\ a_1,a_2,\alpha_2 $ and $\delta_2 $

my text book do not explain why
and this form had not been seen ever before
usually Runge-Kutta method has the form
$$ \ w_{i+1}=w_i +h(a_1 f(t_i,w_i) + a_2 f(t_i+\alpha_2,w_i+\delta_2 f(t_i,w_i)))$$
it is replaced by Taylor 2 order form, which is defined to 2 order Runge-Kutta method
but first form seemed not correct form and do not understand why this form has local truncation error with not having $O(h^3)$ regardless of choice of $ a_1,a_2,\alpha_2,\delta_2 $

A: Yes, if the task is correctly reproduced, then it is strange, the iteration should be written as
\begin{align}
w_0 &= \alpha
\\
w_{i+1}&=w_i +a_1h f(t_i,w_i) + a_2h f(t_i+\alpha_2h,w_i+\delta_2h f(t_i,w_i))
\end{align}
if $a_1$, $a_2$, $α_2$ and $δ_2$ are really constants independent of $h$. Then $δ_2=α_2$, and if $w(t)$ is the exact solution with $w(t_i)=w_i$
$$
f(t_i+α_2h,w_i+α_2h f(t_i,w_i))=f(t_i+α_2h,w(t_i+α_2h)+O(h^2))=w'(t_i+α_2h)+O(h^2)
$$
so that
\begin{align}
w_{i+1}&=w_i+a_1h w'(t_i) + a_2h w'(t_i+α_2h)+O(h^3)
\\&=w_i+a_1h w'(t_i)+a_2h [w'(t_i)+α_2hw''(t_i)+O(h^2)]+O(h^3)
\\&=w_i+(a_1+a_2)w'(t_i)+a_2α_2h^2w''(t_i)+O(h^3)
\end{align}
Now compare with the quadratic Taylor polynomial for $w(t+h)$ to find the conditions $a_1+a_2=1$ and $a_2α_2=\frac12$ so that $w_{i+1}-w(t_{i+1})=O(h^3)$.


text:
Q: Are the files given permission with chmod +x saved somewhere? I am currently following one python3 course at the time. For easy execution, they suggest running the following code:
chmod +x pythonFileName.py

Doing so, made it possible to run the file using: ./pythonFileName.py and this is of course much easier then navigation the entire folder structure to find my scripts.
I am wondering, are these files copied to any hidden folder? How does this command even work? I mean how does he know the right path? If I delete the script do I need to run another code? Delete the copied file from a hidden folder?

A: chmod +x /path/to/file sets the execute permission on the file itself. It doesn't maintain a separate list of permissions for standard read/write/execute, just sets that to the file.

Are these files copied to any hidden folder?

No, the file remains where it is. The permission is set to the file in place.

How does this command even work?

POSIX file permissions include read/write/execute permissions. Running +x adds the execute permission to all, -x removes it.

How does he know the right path?

You provide the path to the command when you run it. /path/to/file is the path you provided when you run the command.

If I delete the script do I need to run another code?

You can delete the file as usual, with rm or using Finder, without needing to run anything else. If you create a new file (regardless of the name) you will need to chmod +x /path/to/file to give it the execute permission again.

Delete the copied file from a hidden folder?

There's no copying taking place when you run chmod so there's nothing else to delete.


text:
Q: How can I relayout my window to show the softinput keyboard? I know there's statexxx and adjustxxx but neither is my desired behavior.
Suppose I have a ListView (match_parent x match_parent) and a EditText (match_parent * wrap_content) which sits at the bottom of screen. When the soft keyboard appears , I only want to position the EditText somewhere to show the entire input panel while leave the ListView as-is.
That is I want the effect same as in WeChat
How can I do that ?


text:
Q: Spring security UserDetails interace getPassword I have an Spring app that works as i want it to work however i bumped into a behaviour that i do not understand i.e.
in order to mary my app with spring security i had  to extend my  UserRepositoryUserDetails class with my hibenrate User class and implement UserDetails. As mentioned all works well but i noticed that UserDetails interface has a method called  "String getPassword();" which is not imlpemented in my UserRepositoryUserDetails class but the application is still working. Then i implemented that method and noticed that i had to call explicetelly the super class getPassword  in order for that construct to wrok. The base User class also has a method  getPassword() as well as "getUsername()" but what i do not uderstand is why i need to to tell in the getPassword() to use explicetelly the method from the super class i.e. the "User" and i do not need to call the super keyword under the getUsername();
    @Override
    public String getUsername() {
        return getUserName();
    }

    @Override
    public String getPassword() {

        return super.getPassword();
    }

here are the classes in question.
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.syncServer.Model.acount.Users;

final class UserRepositoryUserDetails extends Users implements UserDetails{

    private static final long serialVersionUID = 4032653746283400246L;

    public UserRepositoryUserDetails (Users user) {
         super(user);
     }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return AuthorityUtils.createAuthorityList("ROLE_USER");
    }

    @Override
    public String getUsername() {
        return getUserName();
    }

    @Override
    public String getPassword() {

        return super.getPassword();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return getEnabled();
    }

}

and the second class
@Repository
@Entity
@Table(name = "USERS")
public class Users {

    @Id
    @Type(type = "uuid-binary")
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2", parameters = { @Parameter(name = "uuid_gen_strategy_class", value = "org.hibernate.id.uuid.CustomVersionOneStrategy") })
    @Column(name = "USER_ID")
    private UUID userId;

    @Column(unique = true)
    @DuplicateUser
    private String userName;

    @UserPassword
    private String password;

    @UserPassword
    private String PasswordHashVersion;

    @NotNull
    private Boolean enabled;

    @NotNull
    private String salt;

    private String description;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "USER_ID")
    @ElementCollection(fetch = FetchType.LAZY)
    public Collection<Role> roles;

    public Boolean getEnabled() {
        return enabled;
    }

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "USER_ID")
    @ElementCollection(fetch = FetchType.LAZY)
    public Collection<Quota> quota;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "USER_ID")
    @ElementCollection(fetch = FetchType.LAZY)
    public Collection<UserAttribute> userAttribute;

    public Users() {
    }

    public Users(Users user) {
        this.setUserId(user.userId);
        this.setUserName(user.userName);
        this.setPassword(user.password);
        this.setSalt(user.salt);
        this.setEnabled(user.enabled);
        this.setDescription(user.description);

    }

    public Users(@DuplicateUser @Name String userName,
            @UserPassword String password, Boolean enabled, String description) {

        this.userName = userName;
        this.password = password;
        this.salt = BCrypt.gensalt();
        this.enabled = enabled;
        this.description = description;

    }

    public Users(@DuplicateUser @Name String userName,
            @UserPassword String password, String description, Role role,
            Quota quota) {

        this.userName = userName;
        this.password = password;
        this.roles.add(role);
        this.quota.add(quota);
        this.description = description;
    }

    public UUID getUserId() {
        return userId;
    }

    public void setUserId(UUID userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public Collection<Role> getRoles() {
        return roles;
    }

    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }

    public Collection<Quota> getQuota() {
        return quota;
    }

    public void setQuota(Collection<Quota> quota) {
        this.quota = quota;
    }

    public Collection<UserAttribute> getUserAttribute() {
        return userAttribute;
    }

    public void setUserAttribute(Collection<UserAttribute> userAttribute) {
        this.userAttribute = userAttribute;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

Addition 1:
i removed completely the @Override getPassword  method and  started debuggin and put the breakpoint under getUserName(). The abstract class AbstractAuthenticationToken  has method called getName which calles trough proxy (UserDetails) the getUserName from my base hibernate entity class, so the getUsername is called. One more strange thing is that my class UserRepositoryUserDetails  implements UserDetails and now i do not have any implementation of getPassword() but eclipse is find with it. I am lost :( , In my java lessons i have learned that if a class implements interface it has to implement all of the interface method signatures right?


text:
Q: How can i wait after a button-click for a button-click in a dialog window I have a small userprofile sheet with a textView for example the [email] and to the right a [button] to change the address.
When i click the button a small DialogWindow with an EditText Input opens so the user can apply the value with the positive button.
but there is a annoying effect i dont know how to solve. After the EditTextDialog is created i want to toast the input value. (see the code below)
but my first button click doesnt wait for the positive button click in the dialog of course. so there is immediately 'null' toasted before an input has been entered.
Button btnChangeEmail = (Button) getView().findViewById(R.id.btn_settings_changeemail);
        btnChangeEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             MyDialogBuilder myDialogBuilder = new MyDialogBuilder(getString(R.string.changeemail), getActivity());
                myDialogBuilder.createEditTextInputDialog();
                myDialogBuilder.toastInput();
            }
        });

At the buttonclick i want to store the input string in the object. Actually i want to toast it afterwards or make some other calls like send it to a MySQL-DB. But i need this as flexible as possible so that i can call it makeInputDialog().toastTheInput().andSendItToWeb() and so on. But as already said .. there is no string at all because the first button doesnt wait for the second.
What do i need to change? Thanks in Advance.
This is my dialog Builder class:

public class MyDialogBuilder {

  String caption;
  String input;
  Context mContext;

  public MyDialogBuilder(String caption, Context mContext) {
    this.caption = caption;
    this.mContext = mContext;
  }

  MyDialogBuilder setInputValue(String value) {
    this.input = value;
    return this;
  }

  MyDialogBuilder createEditTextInputDialog() {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View inputDialogView = inflater.inflate(R.layout.dialog_input_edittext, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setView(inputDialogView);

    final EditText etInput = (EditText) inputDialogView.findViewById(R.id.et_inputdialog);
    final TextView tvCaption = (TextView) inputDialogView.findViewById(R.id.tv_inputdialog_caption);

    tvCaption.setText(caption);

    builder.setCancelable(true)
      .setPositiveButton(R.string.apply, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          setInputValue(etInput.getText().toString());
        }
      }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          dialog.cancel();
        }
      });

    AlertDialog alertDialog = builder.create();
    alertDialog.show();

    return this;

  }

  MyDialogBuilder toastInput() {
    Toast.makeText(mContext, input, Toast.LENGTH_SHORT).show();
    return this;
  }

}

A: In a builder pattern you just build the situation, not execute it right away. You should just apply the change and check for it later:
public class MyDialogBuilder {

    String caption;
    String input;
    Context mContext;
    boolean showToast;

    public MyDialogBuilder(String caption, Context mContext) {
        this.caption = caption;
        this.mContext = mContext;
    }

    MyDialogBuilder setInputValue(String value) {
        this.input = value;
        return this;
    }

    MyDialogBuilder createEditTextInputDialog() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View inputDialogView = inflater.inflate(R.layout.dialog_input_edittext, null);

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setView(inputDialogView);

        final EditText etInput = (EditText) inputDialogView.findViewById(R.id.et_inputdialog);
        final TextView tvCaption = (TextView) inputDialogView.findViewById(R.id.tv_inputdialog_caption);

        tvCaption.setText(caption);

        builder.setCancelable(true)
                .setPositiveButton(R.string.apply, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setInputValue(etInput.getText().toString());

                        // Toast here
                        if (showToast) {
                            Toast.makeText(mContext, input, Toast.LENGTH_SHORT).show();
                        }
                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();

        return this;

    }

    MyDialogBuilder toastInput() {
        // Set here to show toast or not
        showToast = true;
        return this;
    }

}

So in toastInput() you make clear that a toast should be shown, and later on you check if that boolean was set to true, if so, show the toast.

A: MyDialogBuilder toastInput() {
    Toast.makeText(mContext, input, Toast.LENGTH_SHORT).show();
    return this;
}

replace above code with below code.
MyDialogBuilder toastInput() {
    if(null != input){
        Toast.makeText(mContext, input, Toast.LENGTH_SHORT).show();
    }
    return this;
}

A: You need to make it that the positive button triggers your toast:
MyDialogBuilder createEditTextInputDialog() {
...
builder.setCancelable(true)
  .setPositiveButton(R.string.apply, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      setInputValue(etInput.getText().toString());
      // check logic to show the toast
      showToast(etInput.getText().toString());
    }
  }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      dialog.cancel();
    }
  });

Then create a method to display the toast:
void showToast(String msg) {
    Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
}

You can incorporate with your existing logic to check if toast should be shown or not, but this ensures that the toast method (or method to check if toast should be shown) is only called when a positive button is clicked.


text:
Q: Duplicate @font-face declaration in css, url fetched twice? I'm overriding a @font-face css declaration:
/* ORIGINAL */
@font-face {
  font-family: 'Font1';
  src: url('/PATH1/font1.eot');
  ...
}

/* MY OVERRIDE */
@font-face {
  font-family: 'Font1';
  src: url('/PATH2/font1.eot');
  ...
}

and i've noticed that browsers try to take both paths '/PATH2/font1.eot' and '/PATH1/font1.eot'.
Is there a way to avoid one of two fetch, leaving only one?
Thanks

A: The @font-face rule defines an external font:

Some text. The quick brown fox jumped over the lazy dog... but it didn't make it up all the way.

To change it, modify the innerHTML property of the element.
Here are the ways to modify the HTML code of an element:
+--------------+------------------------------+
| innerHTML    | HTML within the tags         |
+--------------+------------------------------+
| outerHTML    | HTML, with the tags          |
+--------------+------------------------------+
| appendChild  | add an element to the end    |
+--------------+------------------------------+
| prepend      | prepend element              |
+--------------+------------------------------+

This example uses innerHTML:

Some text. The quick brown fox jumped over the lazy dog... but it didn't make it up all the way.

<button onclick="change()">Change @font-face src</button>

This should change the font src.


text:
Q: (How) can I enable automatic switching between Intel and NVIDIA GPU? I'm using a PC with an integrated Intel and a dedicated NVIDIA GPU. Is there a way to switch between the two graphics adapters automatically - depending upon the need at the moment?
Using the NVIDIA settings application forces me to log out and back in to perform the switch.

I found a similar question, but the answers are not sufficient enough. I installed bumblebee, but I don't want to specify the card each time when I run a program. Is there an automatical solution?

A: Unfortunately as of today automatically switching between the intel and NVIDIA graphics is still not supported on Linux based operating systems. There is some progress to be seen in GNOME 3.22, where it is possible to launch an application with the dedicated graphics adapter, but only when the open source drivers are in use. Maybe this feature will be available for the proprietary drivers in the future. In the meantime, for Ubuntu I recommend to use the default solution nvidia-prime and to remove bumblebee, because this software is not maintained any longer ... the latest version 3.2.1 was released on April, 26th in 2013 -> Bumblebee Version 3.2.1 "Tumbleweed" - Release Notes !
Example of GNOME 3.22 - most probably the version which will ship with Ubuntu GNOME 17.04 :

We will see how this will influence the development of other Ubuntu editions and graphics drivers.

A: There is a script which makes easier to switch between intel and nvidia's graphics cards and besides it fixes screen tearing bug on Intel's. If you are interested in check it out: Graphics-Switcher


text:
Q: Is Titanium appcelerator worth it for developing camera based application on ipad, iphone and android? I want to build a mobile/tablet application whose core feature will be taking pictures with the camera , viewing pictures and receiving notifications. Also I want to target iphone, ipad and android platforms.
Titanium appcelerator piqued my interest because of its cross platform appeal. However I am concerned because I've read mixed reviews on SO and other sites. The things that worry me are:

*

*Subpar android support

*Camera support not fully capable (e.g ios 4.1 HDR capability)

*Camera support buggy

The nightmare scenario for me would be to invest time in titanium only to discover later on that its a major PITA and drop it and go "native"
Please share your thoughts and experiences.

A: We have been using Titanium in one of our projects for around 2 months, and frankly speaking our experience with Titanium is too bad.
As per my opinion, below are some major drawbacks of Titanium:
1) First thing is you will not get debugging support at all (We can understand how debugging require in any of the project and in any of the technologies).
2) Titanium is NOT fully supporting all the features of Android/iPhone; beyond some level it will not give you support.
3) Comparing with Android/iPhone SDK, developers will get very less amount of help from the internet and API library (Titanium provides the API library help file).
These are the general issues that end developers face while dealing with Titanium and I suppose sometimes it will be tedious and frustrating work for them.
If the functionality of your application is somewhat like displaying data from the web (like many news, media type apps) then Titanium is the suitable option; otherwise not.

A: The Android support is not near as good as it is for the iPhone. If you were to just say iPhone I would say you would have luck using Titanium.  However, I think trying to build one code base in Appcelerator and also use in your Android environment may not be the best experience.
That said, IMO doing Android / Java code is much easier than doing Objective C / iPhone work.
So worst case I would consider using Titanium for your iPhone version & do Android in Java.
You can give it a shot doing them both in Titanium, but worst case code the Java version.
I just hate objective C and the 'native' Apple development environment so much.

A: I would recommend against using a cross-platform toolkit when interacting with device hardware is one of the key requirements of your application.  I haven't worked with Titanium before, but I find it hard to believe that they will give you the same level of hardware access that you get with native frameworks.
In particular, iOS 4.0 added a mess of new capabilities regarding the camera, including live video frame processing through AVFoundation, and I find it hard to believe that a third-party framework will keep up as these platforms advance.  To be honest, it's pretty easy to write an application that interacts with the camera on the iPhone nowadays (count the number of them on the App Store as an indicator of this).  I wrote a live camera frame processing application in about six hours the other day.
I can't speak for Android, but I imagine dealing with cameras is fairly trivial using the native APIs there as well.
You're also going to find performance testing and debugging your application to be far easier using the native tools than those supplied through a third party.  In particular, Apple's Instruments is an extremely powerful, yet easy to work with, application for tracking down CPU and memory issues within your application.
There's also the community aspect.  You'll find far, far more people working on Android and Cocoa Touch than on Titanium (just look at the numbers of questions in the various tags on Stack Overflow to see that).  This means many more tutorials and a whole lot more sample code that you can use.
The time you'll spend getting your iPhone and Android build environments set up, and submitting to both stores, will be the same no matter if you go with a native environment or with Titanium.
In the end, even with learning both platforms, I think you'll come out ahead by avoiding a cross-platform solution.  Trust me, I've tried to do cross-platform development before for other projects and ended up with lowest-common-denominator products that took much longer to write.

A: I've developed an Appcelerator-based camera application and was very pleased with it. I think some of the negative reviews come from the fact that it's a bit hard to get set up (more due to Apple's crazy developer registration process).
Once I got started, it was easy to do things like overlays on top of the camera screen. I was really expecting difficulty with that part, but it worked well.
I have spoken with the Appcelerator team in the past, and they are a great group to work with. I've seen them be responsive to other user issues, and I'd trust that if I ran across a real bug, they would address it quickly.

A: A little late, but my two cents...
I honestly believe you can very quickly prototype an application with Titanium Appcelerator and focus on the critical feature sets to determine if it is the appropriate tool for you.
All developers have there opinions and experience(s) which influence there comments; developers have different ways of learning and different levels of productivity... In the end, it comes down to how are you most productive with the tools available to you.
Since you are stating from the start that you want to deliver a solution an multiple platforms, I think it would be a poor decision on your part to not even spend a week or two investigating cross-platform frameworks and then making the decision based on your personal experience.
There is Titanium Appcelerator and there is also PhoneGap, where PhoneGap might help you is that there is the ability to extend/enhance the underlying framework through writing plugins (I wrote one for iphone ) and there is an android one on my blog also... this can fill missing gaps for you when you move across platforms.
Also since the UI in a phone gap solution is HTML5 Webkit based, it can give you a consistent look and feel across you devices if you like. Frameworks like jQTouch and JQuery Mobile are being used for UX with PhoneGap Application

A: I reviewed negative feedback for Titanium Appcelerator but I tottaly agree with Aaron Saunders that if you use PhongeGap Development is support HTML5 which can getting easy to make apps for iPhone, iPad and Android mobile.

A: I chose Titanium for a serious application, although one that does not use the camera.  I think there are a variety of things that could play into your decision...
If your app intends to do "fancy" stuff with the camera, or some real heavy image processing and so on, you're likely better off going native.  If on the other hand, you just want to have it take pictures, and then those will be used as-is, or sent to a server, or what not, then Titanium should work just fine.  Titanium does have some processing and image manipulation things, but as others have said, if you really want to take advantage of the device's hardware, you probably want to go full native.
It should also be noted, and Appcelerator says this as well, that with a Titanium app, you won't just write a single app that works as-is on all devices.  You will need to taylor the UI to each device (or class of device, i.e. iPhone, Android), because they have different UI's, and different standard UI flows and so on.
But, one of the potential advantages to Titanium is if you don't know Objective-C and/or Java, and you do know JavaScript (and in my case, I'm actually using Coffeescript :).  Or, if you would enjoy your work much more writing JS than ObjC/Java.  This was one of the main reasons for me.  I have done some ObjC dev in the past, and don't even mind it, but this project I'm doing is on a very very aggressive schedule, and it was just going to be far more effective for me to use Titanium.  I was able to get set up and build an app extremely quickly, and I am not spending any time having to become more deeply familiar with the programming language I'm using, memory management bits (you can't fully ignore this with Titanium, but essentially they're doing it for you).  Based on the folks I've talked to, and how much time they spend with memory management, Interface Builder issues (this is mostly the ease of forgetting to setup connections or hook various things up, IB is actually a pretty great tool), and so on, I'm quite glad I'm using Titanium.
While I expect to do an Android version at some point, it's not a priority.  But, I'm glad to know that a large chunk of my app code will be re-usable, tested, etc. and that I'll wind up mostly just building/revamping the UI for Android, not rewriting networking code, data management, and so on.  Android support will be much better (supposedly) in Titanium 1.5, but you may want to wait for that release to evaluate Android if that's a priority.
Finally, Titanium does have a "module" system, that allows you to wrap native code, exposing it as a JavaScript interface in Titanium.  We are about to leverage this to integrate a third party library, and at least for what we need, it looks very easy to use, and has given me a little more confidence that if some particular native feature we need access to comes up, that we'd have a decent chance of integrating that while still using Titanium, but I think it would depend on what the particular native functionality was.
Good luck and enjoy building a mobile app, it's pretty fun!

A: Has anyone highlighted the cost off titanium.
I was contacted by them today and if you are more than a one man band you have to sign up for a partnership program else you are held liable for breech of contract if you release the app.
The partnership program is £5000 which is far to much for us as a start up company when it's our first application, we are currently looking for a different option now.


text:
Q: \dots=\bot behaves in mathtools/amsmath differently than in pure LaTeX Consider the following input:
\documentclass{standalone}
\usepackage{mathtools}%%% culprit. Same with amsmath
\begin{document}
The formulas of the form \(\dots=\bot\) and \(\bot=\dots\) can be simplified to \(\neg\mathrm{defined}(\dots)\).
\end{document}

As we all know, the equality is commutative:

In particular, the first ellipsis is vertically centered, whereas the second is on the baseline. Why? Who on earth in his or her sane mind would render them differently depending on the side of the equation? Without mathtools (and without amsmath), both occurrences are lowered. I don't care that much about which variant is used, but I do care than the first two ellipses in the example look the same, since they mean the same thing. Which variant is the typographically more pleasant to read with equality? The documentation of amsmath (amsldoc) does not mention the equality sign, so I would think of \dotsb and \dotso. Which one(s) are to be used in the above context and why?

A: Define \lellipsis as you prefer and use it:
\documentclass{article}
\usepackage{geometry} % just to avoid an overfull box in the example
\usepackage{amsmath}

\newcommand{\lellipsis}{{\cdots}}

\begin{document}

The formulas of the form \(\lellipsis=\bot\) and \(\bot=\lellipsis\)
can be simplified to \(\neg\operatorname{defined}(\lellipsis)\).

\end{document}

The reason for the asymmetry is that, with amsmath, \dots looks for what follows, in order to print the most desirable kind of dots (low or centered) depending on the context. In your case you want to be independent of context and also to make the symbol ordinary, rather than punctuation, hence the additional braces.


text:
Q: Discrete Random Variables - Probability of X occurring                   Misc  Hardware Software
Within Warranty 15.00%   14.00%  29.00%
After Warranty   10.00%  26.00%  6.00%

I've come across a seemingly simplistic question in a textbook (regarding discrete random variables) and I'm wondering if there is more to it than simply reading the appropriate value from the table.
The above table concerns type of complaints made at a computer shop. The question reads:
i) If a complaint has been made, what is the probability the complaint was about Hardware, given that the complaint was filed within the warranty period?
Is the answer really as simple as 14.00%?
If not, can anybody explain or point me in the right direction to solve this?

A: Hint:

*

*You might start by finding the probability that a complaint is filed within the warranty period

*Then you can find the conditional probability the complaint was about Hardware, given that the complaint was filed within the warranty period

*which  is the probability that the complaint was about Hardware and  was filed within the warranty period (the $14\%$ in the table), divided by the probability that the complaint was filed within the warranty period

A: The trick here is modifying our universe, if the question just asked about Hardware AND during warranty, then the table info would be correct, but the problem gives us a clue because we already know the complaint was done during the period of warrante, now our universe gets smaler, befora it was the whole table, but know it is just the first row. To solve this I just do a $\frac{Succes cases}{total cases}$ which in this case would be>
$$P(Hardware|During Waranty)=\frac{0.14}{0.14+0.15+0.29}$$
$$P(Hardware|During Waranty)=\frac{0.14}{0.58}=0.24=24\%$$


text:
Q: Does Google Page Speed takes javascript into account? My page is a list of items with one image per item. The whole list is in the html code, but all the items are hidden by default with "display:none" in the CSS file, and a javascript file permits to display them with pagination. If javascript is disabled then the whole list is displayed (potentially hidding the images with a message saying one should enable javascript to see the images, I have not decided yet).
This way a user with javascript enabled will not load all the images at once.
I read google took page loading speed into account.
My question is : will google think, seeing my big html code with tons of images, "it must be slow to load, I'm gonna give it a bad mark" or will google take into account the javascript file to see that it's in fact not slow at all ? Or maybe will it test the javascript and the noscript versions and calculate the average ?


text:
Q: Rollup config for Sapper default template I am using the Rollup Sapper template: https://github.com/sveltejs/sapper-template-rollup/blob/master/rollup.config.js. It has three properties on the default export of rollup.config.js: client, server, and serviceworker. If I install a plugin, how do I know which of these properties to list the plugin under? If you could point me to an article or something that explains the ins and outs of how Sapper works, that would probably help too.

A: Sapper builds your main app twice (once for the server, once for the client). So in most cases, if you install a plugin that transforms the app in some way, you'll need to use it with both server and client configs.
Beyond that, it's basically common sense — if you're transforming your service worker code in some way, then you'll need to add the plugin to your service worker config.


text:
Q: What's the function of a feedback coil? I have seen many different high voltage circuits that require high voltage. A few of these circuits use transformers, however I only ever notice a primary and secondary coil. When taking apart a transformer or seeing one online, I almost always see a feedback coil, and I have no idea what they do, I can't find any questions on this stack exchange about it.

These are all examples of a feedback coil, is there any general purpose for it, what does it do?

A: Your transformer is out of a microwave oven .The winding that you say is a feedback winding is a low voltage winding that powers the magnetron filament .In your circuit the feedback coil provides positive feedback to sustain oscillation.

A: In the picture you posted, the feedback coil is used to make an oscillator circuit with a transistor to make the circuit oscillate by itself when DC voltage is applied to the circuit.

A: I have no idea where you got feedback coil or what this if from. A feedback coil is normally used to control the transformer driver. Some transformers also have two primary windings. Your transformer appears to have two secondary windings and one primary. For example you can connect them in parallel and get twice the current of one or as in your case connect them in series and get twice the voltage at the current rating of the winding. This holds true of the primary as well. It is common to have dual winding transformers where the windings are in series for 220V and parallel for 110V. The two in series have a stab on connector which would be the connection of the two windings. You can verify this by removing the connector and measuring the winding resistance. You will get two separate readings which would probably be the same. In many rectifier circuits this would be the ground connection with two diodes one on each winding providing the other polarity. There are many rectifier circuits that use a center tapped transformer, in this case the junction point of two windings) many that do not. This holds regardless of the secondary and or primary voltages.  This is a miniature version of how the transformer that powers your home in the USA is built. You can also connect the transformer in reverse and use it as a step up transformer where the secondary becomes the primary (power feed), the voltage ratio stays the same as the winding ratio. example: A 10:1 ratio will give one volt per 10 in. If you reverse it 1 volt in will give 10 out. Just do not exceed the voltage and current ratings.


text:
Q: Loop every five seconds in Javascript I'm trying to write a simple loop in JS (or JQuery) that updates an image every five seconds, for a total of 15 seconds (so three loops), and then quits.
It should go like this:

*

*Wait five seconds

*Execute

*Wait five seconds

*Execute

*Wait five seconds

*Execute

*Quit

But setTimeout only seems to work once.
As a test, I've tried:
function doSetTimeout(i) {
  setTimeout(function() { alert(i); }, 5000);
}

for (var i = 1; i <= 5; ++i)
  doSetTimeout(i);

Does not work: http://jsfiddle.net/ubruksco/
I've also tried:
for(var i = 1; i <= 5; i++) {
    (function(index) {
        setTimeout(function() { alert(index); }, 5000);
    })(i);
}

Does not work: http://jsfiddle.net/Ljr9fq88/

A: Your first example is nearly there. You just need to multiply the time delay by the loop index to get the right delay.
function doSetTimeout(i) {
  setTimeout(function() { alert(i); }, 5000*i);
}

for (var i = 1; i <= 3; ++i)
  doSetTimeout(i);

http://jsfiddle.net/ubruksco/3/

A: The reason is that your settimeout ends all at the same time (after 5 seconds) because your timeout code is based on 5 seconds
for(var i = 1; i <= 5; i++) {
    (function(index) {
        setTimeout(function() { alert(index); }, 5000);
    })(i);
}

What you want to do is change the timeout time based on your index (hence will have different start times.
for(var i = 0; i < 3; i++) {
    (function(index) {
        setTimeout(function() { alert(index); }, index*5000);
    })(i);
}

(Also needs 3 iterations, so edited out the loop for you)

A: var time = 1;

var interval = setInterval(function() {
   if (time <= 3) {
      alert(time);
      time++;
   }
   else {
      clearInterval(interval);
   }
}, 5000);

you can simply create an interval and kill it after the 3rd time

A: You want setInterval() instead
 setInterval(function(){ alert("Do Something"); }, 3000);

A: Make it easy! You do not need loop, you just need three executions.
setTimeout(function() { alert(1); }, 5000);
setTimeout(function() { alert(2); }, 10000);
setTimeout(function() { alert(3); }, 15000);

But, if you really want a loop:
function doSetTimeout(i) {
    setTimeout(function() { alert(i); }, i*5000);
}
for (var i = 1; i <= 3; ++i)
    doSetTimeout(i);

A: Assuming your are using jQuery (to manipulate the DOM),
you can try this:
['img1.jpg', 'img2.jpg', 'img3.jpg'].forEach(function(imgPath, index) {
    // the callback will be executed in 5seconds * (index + 1)
    setTimeout(function() {
       // change image source
       $('img#myImage').attr('src', imgPath);
    }, 5000 * (index + 1));
});

A: With setTimeout:
function doSetTimeout(i) {
    if(i >= 3) return;
    alert(i);
    setTimeout((function () {
        return function () {
            doSetTimeout(i);
        };
    })(i + 1), 5000);
}

doSetTimeout(0);

But you can also use setInterval, maybe more appropriate.

A: You can use setInterval instead and track how much times you have executed function. Than just use clearInterval() to stop execution.

var i = 1;
var interval = setInterval(function() {
  execute();
}, 5000);

$(document).ready(function() {
  execute();
});

function execute() {
  $("#output").append("set
");

  if (i == 3) {
    clearInterval(interval);
  }
  i++;
}

If you want to first wait 5 secs, don't call execute() on domready.


text:
Q: PHP > Array > assign value to text key duplicate the key My code:
$a['page'] = 1;
function change($a) {
$a['page'] = 2;
}

My output:
$a['page'] = 1;
$a['page'] = 2;

Why am I get two keys 'page'?
I was expecting the function changed the value.

A: $a['page'] = 1;

function change($a) {
    return $a['page'] = 2;
}

echo change($a);

A: you could pass $a by reference instead and it would work as expected. It would be slower but not significantly so, given the function.
$a['page'] = 1;

function change(&$a) {
    $a['page'] = 2;
}

change($a);

echo "<pre>";
print_r($a);


text:
Q: terraform: syntax for source_security_group_id I need to use the terraform source_security_group_id indicator to set another security group as a source for the current one. But when I try variations on obvious syntax, like
resource "aws_security_group" "foo-sg" {

    "ingress" = {
    "from_port" = 443
    "to_port" = 443
    "protocol" = -1
    "source_security_group_id" = "sg-9115bae1"
  }
}

... I get an error:

aws_security_group.foo-sg: ingress.0: invalid or unknown key:
  source_security_group_id

Anyone have an example of using this construct?

A: The attribute name for this feature is security_groups, and can be used as follows:
resource "aws_security_group" "foo-sg" {
  ingress {
    from_port = 443
    to_port   = 443
    protocol  = "tcp"

    security_groups = ["sg-9115bae1"]
  }
}

Note too that the special -1 value for protocol, meaning "any protocol", causes the port numbers to be ignored since only UDP and TCP have the concept of port numbers. Setting the protocol to tcp, as shown in the above example, is necessary to allow incoming connections for HTTPS.

A: If above code is not working , please fallow variable method. means define variable and get from outputs
resource "aws_security_group" "foo-sg" {
  ingress {
    from_port = 443
    to_port   = 443
    protocol  = "tcp"

    security_groups = ["${var.ec2_sg}"]
  }
}
##in variable file add this
variable = "ec2_sg" {}

then in main file give the input from another module


text:
Q: Discord JS calling JSON I'm currently working on a discord js bot which will fetch some information from a JSON file on a website. I have been able to get it to work with photos but I have no idea how to get the information I want from this JSON file. I'm sorry if this is really simple but I'm new to JS
The part I need from the JSON file is "name" and then I need it too print out all of the names that are in the file at the time.
This is currently a JSON file that I am testing with, it's a FiveM server player list.
http://145.239.206.148:30120/players.json
If you could please provide me with some information on how to get all of the player names that would be much appreciated.
This is the blank "Fivem" command file.
const Discord = require("discord.js");

module.exports.run = async (bot, message, args) => {

}
module.exports.help = {
    name: "fivem"
}

A: You could parse the JSON file with JSON.parse() and traverse over each of the returned Object's array elements to access the name attributes and values. A JSON Parser would be helpful to visualize the indices of it's structure. Resources : JavaScript JSON Parsing

A: I used an api so I think you could do something like:
https.get('http://145.239.206.148:30120/players.json', response => {
        response.setEncoding('utf8');
        let body = '';
        response.on('data', data => {
            body += data;
        });
        response.on('end', () => {
            body = JSON.parse(body);
            console.log(body) // You obtain  your json as an js object...
        });
    });

It worked for me so...
MrNossiom


text:
Q: Linker error Duplicate Symbol when trying to link libFlurryAds I am working on an iOS game and have admob / iAd / and flurry integrated for serving ads. I am using admob mediation for serving ads from these providers.
The problem is that when I try to test against the simulator I get a lot of linker errors like this . . .
duplicate symbol _utf8_check_string in:
    /Users/omersaeed/Library/Developer/Xcode/DerivedData/EscapeToArae-drmhiearnycapsfamyakifandjod/Build/Intermediates/EscapeToArae.build/Debug-iphonesimulator/EscapeToArae.build/Objects-normal/i386/utf.o
    /Users/omersaeed/projects/gamechefs/cocos2d-x-2.2/projects/e2a/customlibs/Flurry-iOS-4.3.0/FlurryAds/libFlurryAds_4.3.0.a(libExternalSDKs.a-i386-master.o)
All errors are about duplicate symbols and all are related to the libFlurryAds library.
The interesting part is that I can link and run the game perfectly if I run directly on the device.
Removing the Flurry libs solves the problem.
Any idea why the issue pops up when I run on the simulator and not when I run on the device?

A: So eventually figured out that I was using a library called jansson (for JSON parsing) in source form, the same library is apparently included in the libFlurryAds and thus I was getting duplicate symbol errors. I eventually removed jansson and replaced it with another simpler JSON reader.


text:
Q: "ContentType" vs "PublishingAssociatedContentType" difference? What is the difference between "ContentType" vs "PublishingAssociatedContentType" while creating a page layout?

Property Name="ContentType" Value="Page Layout"
  PropertyName="PublishingAssociatedContentType" Value="Custom Content Type"

Technically a page layout should be associated with a content type. If so, why should we need two different content types refereed in the layout pages?

A: The Page Layout has a content type of "Page Layout". This is how SharePoint differentiates them from other things in the gallery, like master pages, design files, and display templates.
A page layout can also be associated with a Publishing Content Type. This is a content type on the Pages library and it tells SharePoint to default to this page layout when rendering a Publishing Page of that type.
So, in your example above, the Content Type is "Page Layout", which is the only valid value this field can have for a Page Layout, and the Associated Content Type means that publishing pages with a content type of "Custom Content Type" will use that layout. The "Custom Content Type" should be a Content Type on the Pages library.


text:
Q: Arranging items from a mongoDB object into a list top to bottom with Angular.js I have a simple todo list app with node.js, angular.js, mongoDB and mongoose as the object modeling. I want to be able to have the newly added item be insert on the top of the list an not the bottom. I thought this was an Angular.js prepending issue, but upon further reading it is because the data is being stored in an object. Is there a way to sort it from top to bottom? Is it a mongoDB issue or Angular? Any help will be greatly appreciated. If you need more code I can provide it. Again thank you.
The HTML

                Vote
                Song
                Edit

                <button class="btn btn-success icon-thumbs-up" alt="Up vote this song if you like it.">Vote</button>
                {{ todo.text }}
                <button class="btn btn-danger fa fa-times" ng-click="deleteTodo(todo._id)" alt="Remove the song if you need to make an edit and then add it back."></button>

API service
// each function returns a promise object
.factory('Todos', function($http) {
    return {
        get : function() {
            return $http.get('/api/todos');
        },
        create : function(todoData) {
            return $http.post('/api/todos', todoData);
        },
        delete : function(id) {
            return $http.delete('/api/todos/' + id);
        }
    }
});

Some of the Angular
// CREATE ==================================================================
    // when submitting the add form, send the text to the node API
    $scope.createTodo = function() {
        $scope.loading = true;

        // validate the formData to make sure that something is there
        // if form is empty, nothing will happen
        if ($scope.formData.text != undefined) {

            // call the create function from our service (returns a promise object)
            Todos.create($scope.formData)

                // if successful creation, call our get function to get all the new todos
                .success(function(data) {
                    $scope.loading = false;
                    $scope.formData = {}; // clear the form so our user is ready to enter another
                    $scope.todos = data; // assign our new list of todos
                });
        }
    };

 // create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {

    // create a todo, information comes from AJAX request from Angular
    Todo.create({
        text : req.body.text,
        done : false
    }, function(err, todo) {
        if (err)
            res.send(err);
    todos.unshift(todo);

        // get and return all the todos after you create another
        Todo.find(function(err, todos) {
            if (err)
                res.send(err)
            res.json(todos);
        });
    });

});

Object model
var mongoose = require('mongoose');

module.exports = mongoose.model('Todo', {
text : String,
done : Boolean
});

A: To check what the order is coming back from Mongo, place
{{todos}}
 in your view html and see if they are sorted how you want.  Then you should know if is Mongo or Angular issue.
For a simple fix you can add default date in mongoose schema:
time: {type: Date, default: Date.now }

Then in Angular view add orderBy clause to the ngRepeat directive to sort this field

This way in your controller you can just worry about get the data itself and view will properly sort whatever is there automatically when it updates.  Also you could give user toggle button to sort by newest or oldest

A: First, I highly recommend discarding the Todo.find in your post method. Instead just return the todo in the callback from server-side Todo.create in your post method.
Second, don't reassign $scope.todos in client-side Todos.create. If you just send back the one object you posted, you'll be able to use todos.unshift(todo) client-side and place the newest todo at the top of the list.
Lastly, you need to add some kind of ordinal to your todo mongoose schema and use a sort to make sure the order is what you prefer when the list of todos is serverd.
Here's your server-side code returning the newly inserted todo.
app.post('/api/todos', function(req, res) {

    // create a todo, information comes from AJAX request from Angular
    Todo.create({
        text : req.body.text,
        done : false
    }, function(err, todo) {
        if (err)
            res.send(err);
    res.json(todo);

});

here's your client-side code inserting the response from the post back into the todos array
    // when submitting the add form, send the text to the node API
    $scope.createTodo = function() {
        $scope.loading = true;
    // validate the formData to make sure that something is there
    // if form is empty, nothing will happen
    if ($scope.formData.text != undefined) {

        // call the create function from our service (returns a promise object)
        Todos.create($scope.formData)

            // if successful creation, call our get function to get all the new todos
            .success(function(data) {
                $scope.loading = false;
                $scope.formData = {}; // clear the form so our user is ready to enter another
                $scope.todos.unshift(data); // assign our new list of todos
            });
    }
};


text:
Q: I have a jQuery function that alters titles in Wordpress and I tried to add a link to the title and it's not behaving right Here's the function:
$('.entry-title').each(function() {
    var dotdotdot = $(this).html().indexOf('…');
    $(this).html('<a href="<?php the_permalink(); ?>">' + $(this).html().substring(0, dotdotdot) + '' + $(this).html().substring(dotdotdot) + '');
});

The original intent was to add a span tag into the text of the title itself and that worked beautifully (thanks @making3). The code <a href="<?php the_permalink(); ?> + ''is what I later added to the original function.
What I am trying to do is wrap a link around the title so it will link to the single post page. The screwy part is these titles are looping through each post on the page backwards and creating multiple empty links for every post. Only the last link has the title in it, but it's not the correct link for that title. So clearly what I did is totally wrong.
Here's my markup:
<article <?php post_class(); ?>>

<?php the_title(); ?>

      <?php the_content(); ?>

Can anybody help?

A: It looks as though you've modified your jQuery code as follows:

I'm sure this looks fine on the page but behind the scenes you are outputting that jQuery code for each post and since it does a .each function it operates on every post in each instance of the code so that results in multiple nested span tags.
Right now your HTML is getting rendered as the following through jQuery:

Crushing on…making a change

(right click an element in chrome and click inspect element to see this for yourself)
This is happening because of the multiple instances of the jQuery code when you only want once instance to operate on all the links.  To fix this put this jQuery code block at the top of the page outside the PHP loop that is generating the posts so it only gets output once.


text:
Q: Is there any nfc devices other than mobile phones? I am developing one application related to Nfc.
I get some information regording nfc through web search.
But i have some questions related to nfc.
1)Is nfc is avilable only in mobiles?
2)If i want to send image through nfc to another nfc device,
i required permistions form other device to send image or not?
3)is it possible to get data from one nfc device to another device automatically?
If any one know this,please send me reply.
Thanks in andvnce.

A:
1)Is nfc is avilable only in mobiles?

In terms of Android, at the moment, yes. NFC may become available on tablets in 2012, but right now, the only NFC-enabled devices are phones.

2)If i want to send image through nfc to another nfc device, i required permistions form other device to send image or not?

That would be up to whoever writes the image receiver application, just as whoever writes a Web site can decide whether to require authentication or not.

3)is it possible to get data from one nfc device to another device automatically?

That would depend upon your definition of "automatically".


text:
Q: Best Approach using Volley Android to Insert SQLITE Database? I'm using Volley in my android application but I'm facing a problem, I have to use volley only for async connections?
Because per example I have an 1800 record database from web service to my application I start my volley and retrieve fine but I'm inserting this records on my SQLite and when I do that my application freezy why?
I thinking volley have async methods to handle this but it freezy when I loop on a volley and insert. My dialogue stops animation and everything.
Before volley I use the Assyntask from android and never freezy my application and I'm using httpost but now I change to volley and I'm facing this issue I will share my code :
  public void volleyJsonObjectRequest(String url) {

        String  REQUEST_TAG = "com.androidtutorialpoint.volleyJsonObjectRequest";
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Sincronizando pedidos..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

        // prepare the Request
        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        // display response

                        Log.d("Response", response.toString());

                        List<HashMap<String,String>> listObjectsServer = new ArrayList<>();

                        try {

                            MDAutomap controller;
                            controller = new MDAutomap(getActivity());

                            JSONArray jsonArrayPedidos = response.getJSONArray("pedidos");
                            if (jsonArrayPedidos != null && jsonArrayPedidos.length() > 0) {

                                HashMap<String, String> pedidos = new HashMap<String, String>();
                                for (int i = 0; i < jsonArrayPedidos.length(); i++) {

                                  JSONObject obj = jsonArrayPedidos.getJSONObject(i);

                                  pedidos.put("nomeusuario", obj.getString("nomeUsuario"));
                                  pedidos.put("id", obj.getString("id"));
                                  pedidos.put("nome", obj.getString("nome"));
                                  pedidos.put("eventoid", obj.getString("eventoid"));
                                  pedidos.put("descricao", obj.getString("descricao"));
                                  pedidos.put("valor", obj.getString("valor"));
                                  pedidos.put("veiculo", obj.getString("veiculo"));
                                  pedidos.put("transactioncode", obj.getString("transactioncode"));
                                  pedidos.put("referencecode", obj.getString("referencecode"));
                                  pedidos.put("status", obj.getString("status"));
                                  pedidos.put("flag", obj.getString("flag"));
                                  pedidos.put("usuario", obj.getString("usuario"));
                                  pedidos.put("created_at", obj.getString("created_at"));
                                  pedidos.put("updated_at", obj.getString("updated_at"));

                                    if (controller.checkPedido(pedidos.get("id"))) {

                                        controller.updatePedido(pedidos);

                                    }else {

                                        controller.inserirPedido(pedidos);

                                    }

                                }

                                if (pDialog != null && pDialog.isShowing()) {
                                    pDialog.dismiss();
                                }

                                //userMsg("Sincronizado com sucesso os pedidos.");

                            }else {

                                if (pDialog != null && pDialog.isShowing()) {
                                    pDialog.dismiss();
                                }

                                //userMsg("Não existe pedidos para sincronizar.");

                            }

                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }

                    }

                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        if (pDialog != null && pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                        userMsg("Não foi possível fazer conexão, por favor tenta novamente.");
                    }
                }
        );

A: Yes it will freeze because it is getting huge data from service and inserting in Db on main UI thread . So i solved that problem by taking a async task inside volley response and it worked in my case
private void hitApiForSyncDropdownsData(final String ApiType) {
    showDialog();
String jsonAsParamstr = makeJsonStr(ApiType);
JsonObjectRequest req = new JsonObjectRequest(wholeUrl, makeJsonFromStrJson(jsonAsParamstr),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getString(Constant.Utils.responseCode).equals("1")) {
                        new ProcessJsonAsync(ApiType).execute(response, null, null);
 //processing response in Async as getting heavy reponse and inserting into DB
                    } else {
                        showShortToast(response.getString(Constant.Utils.responseMessage));
                        dismissDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissDialog();
                }
            }

        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
        showmsgForVolleyIfConnProb(error, context);
    }
});
req = setretryPolicy(req);
AppController.getInstance().addToRequestQueue(req);
}

and that async Code would look like
private class ProcessJsonAsync extends AsyncTask<JSONObject, Void, Integer> {
        String ApiType;

        ProcessJsonAsync(String ApiType) {
            this.ApiType = ApiType;
        }

      protected Integer doInBackground(JSONObject... jsonObjects) {
        ArrayList<DataModel> dataModelArraylist = new ArrayList<>();

        Integer insertedResult = -1;
        try {
            JSONObject response = jsonObjects[0];
            if (response.getString(Constant.Utils.responseCode).equalsIgnoreCase("1")) {
                JSONArray jsonarray = response.getJSONArray(Constant.Utils.responseObject);
                for (int i = 0; i < jsonarray.length(); i++) {
                    JSONObject jsonObj = jsonarray.getJSONObject(i);
                    dataModelArraylist.add(new DataModel(jsonObj.getString("data1"), jsonObj.getString("data2"));
                }

                DataStrucTable dataStrucTable=new DataStructTable();
                insertedResult=dataStrucTable.insertArrayInDb(dataModelArraylist);
    //here it will insert thousands of entries in DB on background thread and will not hang your UI

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return insertedResult;
    }
      @Override
    protected void onPostExecute(Integer integer) {
        Toast.makeText(context, integer == -1 ? "Data couldn't insert in DB" :"Data successfully inserted", Toast.LENGTH_SHORT).show();
    }
    }


text:
Q: Culture issues after installing windows update KB3136000 after installing windows update KB3136000 the WPF application behaves unexpected when changing the CurrentThread cultures.
Executing the following code in WPF (targeting .NET Framework 4.6.1)
public MainWindow()
{
    var defaultCultureInfo = string.Format("Default Culture: Culture: {0}, UICulture: {1}, ThreadID: {2}",
        Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, Thread.CurrentThread.ManagedThreadId);
    var culture = new CultureInfo("hu-HU");
    CultureInfo.DefaultThreadCurrentCulture = culture;
    CultureInfo.DefaultThreadCurrentUICulture = culture;
    var newCultureInfo = string.Format("New Culture (Should be hu-HU): Culture: {0}, UICulture: {1}, ThreadID: {2}",
        Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, Thread.CurrentThread.ManagedThreadId);

    System.Diagnostics.Trace.WriteLine(defaultCultureInfo);
    System.Diagnostics.Trace.WriteLine(newCultureInfo);

    InitializeComponent();
}

gives the following results (German is my OS language):
Default Culture: Culture: de-DE, UICulture: de-DE, ThreadID: 8
New Culture (Should be hu-HU): Culture: de-DE, UICulture: de-DE, ThreadID: 8

Executing the same code when targeting .NET Framework 4.5 gives the following (correct) results:
Default Culture: Culture: de-DE, UICulture: de-DE, ThreadID: 8
New Culture (Should be hu-HU): Culture: hu-HU, UICulture: hu-HU, ThreadID: 8

Executing similar code in Console Application when targeting .NET Framework 4.6.1 gives correct results as well.
This issue seems to occur when changing the WPF application's culture to something different than the operating system's culture after installing KB3136000.
Is there anyone encountering similar issues? Is there a way to report issues to Microsoft without a Microsoft account. The procedure we tried on Connect Microsoft failed after the first step:
"You are not authorized to submit the feedback for this connection."
EDIT:
Starting a new thread also has strange behavior (.NET 4.6.1, WPF). Add the following code to the code above:
var thread = new Thread(new ThreadStart(() =>
    {
        Console.WriteLine("In Thread: Culture: {0}, UICulture: {1}, {2}", Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture, Thread.CurrentThread.ManagedThreadId);
    }));
thread.Start();
thread.Join();
Console.WriteLine("After Thread-Execution: Culture: {0}, UICulture: {1}, {2}", thread.CurrentCulture, thread.CurrentUICulture, thread.ManagedThreadId);

Results:
In Thread: Culture: de-DE, UICulture: de-DE, 10
After Thread-Execution: Culture: hu-HU, UICulture: hu-HU, 10


text:
Q: webservice flow, proxy and soap address I am very new to SOAP webservice. Want to know few things..
1. There is an URL (say, A) by which we can access the WSDL, then what the "soap:address" is used for. I have found a new IP address (say B) as "soap:address location" mentioned in WSDL but this URL is totally different from A. My question is why B address is needed - is this some internal IP address of a machine that resides behind A and completely unaccessible from client. What is the flow?

*

*Since A is not public, so the host have given the access permission to my WAN IP so that I can access A. Now I can access the A url (getting a WSDL content) from simple Java code
URL oracle = new URL(A);
URLConnection yc = oracle.openConnection(proxy);
as I am behind a proxy firewall. But I can access by
URLConnection yc = oracle.openConnection();

From this can I conlude that Java by default tries to connect any URL bypassing machine's default proxy configuraion?

*

*I have generated the client stub from WSDL URL and found that it is annotated with A
@WebServiceClient(name = "BDCDataExchange", targetNamespace = "some url", wsdlLocation = "A"
But when I am running the code it is giving
com.sun.xml.internal.ws.client.ClientTransportException: HTTP transport error: java.net.ConnectException: Connection timed out: connect
at com.sun.xml.internal.ws.transport.http.client.HttpClientTransport.getOutput(Unknown Source)
at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.process(Unknown Source)

As I can access A from my simple java code, does this exception means that I can not access the internal soap:address B?
But the same client code is working if I generate the client using local WSDL path like
wsimport A   //not working while executing, above exception comes
wsimport <a local path where I saved the WSDL file>  //it works when I run


text:
Q: How to sum: $\sum_{n=0}^{\infty} (n^2+2n+1)·(2·\ln(x))^n$ How to sum: $$\sum_{n=0}^{\infty} (n^2+2n+1)·(2·\ln(x))^n$$
I've tried considering $$S_N=1+4(2\ln(x))+9(2\ln(x))^2+...+(N^2+2N+1)(2\ln(x))^N$$
and $$(2\ln(x))·S_N=1(2\ln(x))+4(2\ln(x))^2+...+((N-1)^2+2(N-1)+1)(2\ln(x))^N+(N^2+2N+1)(2\ln(x))^{N+1}$$
So $S_N-(2\ln(x))S_N=1+3(2(ln(x))+5(2(ln(x))+...+$
But is this leading me to something? Is it the correct way to sum that?
Assume the series converges ($x\in(e^{-1/2},e^{1/2})$)

A: $$\sum_{n\ge0}(n^2+2n+1)y^n = \sum_{n\ge0}(n+2)(n+1)y^n-\sum_{n\ge0}(n+1)y^n = \frac{2}{(1-y)^3}-\frac{1}{(1-y)}^2$$
Plug $y=2\ln x$ in the solution.

A: Starting from $\frac{1}{1-u}=\sum_{n=0}^{\infty}u^n$ you get

*

*$\frac{d}{du}\left(\frac{u}{1-u}\right) = \sum_{n=0}^{\infty}(n+1)u^n$

*$\Rightarrow \frac{d}{du}\left(u\frac{d}{du}\left(\frac{u}{1-u}\right)\right) = \boxed{\sum_{n=0}^{\infty}(n+1)^2u^n}$ (This is your sum for $u =2 \ln x$.)

*Differentiating gives:
$$\frac{d}{du}\left(u\frac{d}{du}\left(\frac{u}{1-u}\right)\right) = \frac{1+u}{(1-u)^3} \stackrel{|\ln x| < \frac{1}{2}}{\Rightarrow} \boxed{\sum_{n=0}^{\infty}(n+1)^2(2\ln x)^n = \frac{1+2\ln x}{(1-2\ln x)^3}}$$


text:
Q: tslint: no-object-mutation while building Object with reduce I want to build an object using reduce in this way:
const result = [1, 2].reduce((partialResult, actualValue) => {
    // define someKey and someValue
    partialResult[someKey] = someValue;
    return partialResult
}, {});

However, I'm getting the following tslint error:
Modifying properties of existing object not allowed. (no-object-mutation)

How can I solve this?

A: Either modify the code so that you're not mutating the object, which means you'll have to copy it each time:
const result = [1, 2].reduce((partialResult, actualValue) => {
    return {
      ...partialResult,
      [someKey]: someValue,
    }
}, {});

Or disable the lint rule (either for this specific line if you like the lint rule in general, or globally if you think it's an unnecessary restriction)

A: For example:
const result = [1, 2].reduce(
    (partialResult, actualValue) => Object.assign({}, partialResult, {[someKey]: someValue]}), {});

A: You can use map and Object.fromEntries to create the object all-at-once (as far as your code is concerned) rather than mutating or copying the object:

const someKey = "foo";
const result = Object.fromEntries(
  [1, 2].map(value => [someKey + value, value])
//                     ^^^^^^^^^^^^^^^---- see my comment on the question and
//                                         note below
);
console.log(result);

fromEntries creates an object from an array of entries, where each entry is a [key, value] array.
Note that I've used someKey + value as the key because you haven't said how you get the key, and I assume you're not just using the same key every time, since as I commented here, if you were you'd be replacing the property value every time if you did and end up with an object with a single property, making the entire loop pointless.


text:
Q: Image not bouncing in jQuery I am doing a project of a mock up NPR page and I want to make the logo bounce however it's not doing so.
I'm pretty sure the syntax is right. I just need an extra eye to lead me in the right direction.
Here is my jQuery:
    $(document).ready(function() {

        $(".nprLogo").mouseenter(function() {
            $(this).stop().effect("bounce", 500);

            $(".nprLogo").mouseleave(function() {
                $(this).stop(true, true);

            });
        });
    });

and here is my HTML:

I have it in a table because that was part of the instructions.

A: That's a jquery UI function, you need to include it in addition to jQuery:

As a side note, your
 and 	 are in the wrong order, you need to have 	 first...


text:
Q: Disable input text field which are coming on future month in angular i have static table columns for each month and static table body columns as input text for each month.i am having a problem in creating logic to disable future month input text.
thank in advance
code of my html file
i want to disable input of future month for example november and december

A: in angular you can use the property [disabled] on input field and call a component a method
for sample you can create a method and pass in parameter the monthNumber
<input [disabled]="isFutureMonth(0)"/> // for january
<input [disabled]="isFutureMonth(1)"/> /// for febrary

and in the component's controller we can propose you to :

*

*stored somewhere the current month

*create a method that check if input month is in the future or not
enter code here
export class MyComponent {
 currentMonth:number;

 constructor() {
   this.currentMonth = new Date().getMonth();
 }

 isFutureMonth(monthNumber:number):boolean {
   return (monthNumber > this.currentMonth);
 }

}

A: You need to add additional field in your static table for monthNumber.
For ex: Jan = 1, Feb = 2, Mar = 3.....
After that in you component declare two new variable todaysDate =  todaysDate: Date = new Date(); and currentMonth = currentMonth: any
Then create method to get current month as below
getMonth() {
    this.month = this.todaysDate.getMonth() + 1;
}

Call this method from ngOnInit(), you will get current month.
After this in your HTML file add [disabled] in your input fields
[disabled]="(i.month > currentMonth)"


text:
Q: Testing Backbone with Karma, Grunt, and Jasime >> ReferenceError: Can't find variable: require First off, I saw this post and it gave me more errors (see bottom).
I get these error:

ReferenceError: Can't find variable: require at test/spec/test.js:1
TypeError: 'undefined' is not an object (evaluating 'text.replace') at
      bower_components/underscore/underscore.js:1180  src/js/script.js:12  src/js/script.js:56  src/js/script.js:194
ReferenceError: Can't find variable: require at test/spec/test.js:1

When trying to use Grunt.
Here is my Grunt file:
module.exports = function (grunt) {
jasmine: {
            src: 'src/js/*.js',
            options: {
                specs: 'test/spec/*.js',
                helpers: 'test/spec/*.js',
                vendor: [
                    'bower_components/jquery/jquery.js',
                    'bower_components/underscore/underscore.js',
                    'bower_components/backbone/backbone.js'
                ]
            }
        }
    });

grunt.registerTask('default', ['clean', 'jasmine']);

Here is my Test file:
var chai = require('chai')
var Backbone = require('backbone');
var _ = require('underscore');
describe('Underscore & Backbone to be defined', function() {
    it('should be loaded', function() {
        chai.should.exist(_);
        chai.should.exist(Backbone);
    })
})

I am not using requirejs by the way.

When adding grunt-template-jasmine-requirejs, enter code hereI get these errors:

>> Error: Module name "jquery" has not been loaded yet for context: _. Use require([])
>> http://requirejs.org/docs/errors.html#notloaded at
>> .grunt/grunt-contrib-jasmine/require.js:8 aa
>> .grunt/grunt-contrib-jasmine/require.js:12 v
>> .grunt/grunt-contrib-jasmine/require.js:26 h
>> .grunt/grunt-contrib-jasmine/require.js:31
>> test/spec/test.js:1
>> TypeError: 'undefined' is not an object (evaluating 'text.replace') at
>> bower_components/underscore/underscore.js:1180
>> src/js/script.js:12
>> src/js/script.js:56
>> src/js/script.js:194
>> Error: notloaded: Module name "jquery" has not been loaded yet for
  context: _. Use require([])
>> http://requirejs.org/docs/errors.html#notloaded at
>> _SpecRunner.html:46
>> .grunt/grunt-contrib-jasmine/require.js:12 v
>> .grunt/grunt-contrib-jasmine/require.js:26 h
>> .grunt/grunt-contrib-jasmine/require.js:31
>> test/spec/test.js:1


text:
Q: default paramater value in class python i have two class. first class is RegularPolygon and second is child class inheritance from RegularClass. I want to set default value in number of side = 4. I have try (which is i put comment on this code) but the result is "non-default argument follows default argument python class..."
class RegularPolygon:
    def __init__(self, no_of_sides, side_length):
        self.no_of_sides = no_of_sides
        self.side_length = side_length
    def perimeter(self):
        keliling_poligon = self.no_of_sides * self.side_length
        return keliling_poligon
    def interior_angle(self):
        int_angle = (self.no_of_sides - 2) * 180/self.no_of_sides
        return int_angle
    def exterior_angle(self):
        _=360/self.no_of_sides
        return ext_angle

class Square(RegularPolygon):
    def __init__(self, no_of_sides, side_length):
        super().__init__(no_of_sides, side_length)
        self.no_of_sides = 4
    def area(self):
        area_square = self.side_length**2
        return area_square
    def diagonal(self):
        diagonal_square = self.side_length*(2**0.5)
        return diagonal_square

square_1 = Square(5)

s_perim = square_1.perimeter()
s_area = square_1.area()
angl_int = square_1.interior_angle()
angl_ext = square_1.exterior_angle()
diagonal = square_1.diagonal()

result = (s_perim, s_area, angl_int, angl_ext, diagonal)
print(result)

i want put default value 4 in child class Square
and then produce error
TypeError                                 Traceback (most recent call last)
<ipython-input-6-cdd5b6433650> in <module>
     29         return diagonal_square
     30
---> 31 bujursangkar = Square(5)
     32
     33 keliling = bujursangkar.perimeter()

TypeError: __init__() missing 1 required positional argument: 'side_length'

A: As you have two variables defined def __init__(self, no_of_sides, side_length): you should use square_1 = Square(4,5) instead of square_1 = Square(5).
You can also use the following instead:
class Square(RegularPolygon):
    def __init__(self, side_length, no_of_sides = 4):
        super().__init__(no_of_sides, side_length)
    def area(self):
        # ... code ...

In the latter case you can if you want override the value for no_of_sides  whenever is needed.


text:
Q: How to use Hacker News API in Python? Hacker News has released an API, how do I use it in Python?
I want get all the top posts. I tried using urllib, but I don't think I am doing right.
here's my code:
import urllib2
response = urllib2.urlopen('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')
html = response.read()
print response.read()

It just prints empty
''

I missed a line, had updated my code.

A: As @jonrsharpe, explained read() is only one time operation. So if you print html, you will get list of all ids. And if you go through that list, you have to make each request again to get story of each id.
First you have to convert the received data to python list and go through them all.
base_url =  'https://hacker-news.firebaseio.com/v0/item/{}.json?print=pretty'
top_story_ids = json.loads(html)
for story in top_story_ids:
    response = urllib2.urlopen(base_url.format(story))
    print response.read()

Instead of all this, you could use haxor, it's a Python wrapper for Hacker News API. Following code will fetch you all the ids of top stories :
from hackernews import HackerNews
hn = HackerNews()
top_story_ids = hn.top_stories()
# >>> top_story_ids
# [8432709, 8432616, 8433237, ...]

Then you can go through that loop and print all them, for example:
for story in top_story_ids:
   print hn.get_item(story)

Disclaimer: I wrote haxor.

A: You should
print html

instead of
print response.read()

Why? Because the read is a one-time operation; after you've done it, you can't repeat it:
>>>import ullrib2
>>> response = urllib2.urlopen('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')
>>> response.read()
'[ 8445087, 8444739, 8444603, 8443981, 8444976, 8443902, 8444252, 8444634, 8444931, 8444272, 8444025, 8441939, 8444510, 8444640, 8443830, 8445076, 8443470, 8444785, 8443028, 8444077, 8444832, 8443841, 8443467, 8443309, 8443187, 8443896, 8444971, 8443360, 8444601, 8443287, 8441095, 8441681, 8441055, 8442712, 8444909, 8443621, 8442596, 8443836, 8442266, 8443298, 8445122, 8443096, 8441699, 8442119, 8442965, 8440486, 8442093, 8443393, 8442067, 8444989, 8440985, 8444622, 8438728, 8442555, 8444880, 8442004, 8443185, 8444370, 8436210, 8437671, 8439641, 8443727, 8441702, 8436309, 8441041, 8437367, 8422087, 8441711, 8438063, 8444212, 8439408, 8442049, 8440989, 8439367, 8438515, 8437403, 8435278, 8442486, 8442730, 8428522, 8438904, 8443450, 8432703, 8430412, 8422928, 8443635, 8439267, 8440191, 8439560, 8437230, 8442556, 8439977, 8444140, 8441682, 8443776, 8441209, 8428632, 8441388, 8422599, 8439547 ]\n'
>>> response.read()
''

In your case, though, you've assigned the string from read to the name html, so you can still access it.

Once you have the story IDs, you can access each one via '.../v0/item/{item number}.json?print=pretty':
>>> response = urllib2.urlopen('https://hacker-news.firebaseio.com/v0/item/8445087.json?print=pretty')
>>> print response.read()
{
  "by" : "lalmachado",
  "id" : 8445087,
  "kids" : [ 8445205, 8445195, 8445173, 8445103 ],
  "score" : 21,
  "text" : "",
  "time" : 1413116430,
  "title" : "Show HN: Powerful ASCII art editor designed for the Mac",
  "type" : "story",
  "url" : "http://monodraw.helftone.com/"
}

You should read through the API documentation before continuing. It's also worth getting to grips with the json module.


text:
Q: Is there a list of pragmas supported in Xcode? Is there a list of pragmas supported in Xcode? I only know of #pragma mark. Where would I look to learn about any others?

A: GCC online manual, see here. Depending on your XCode settings, you can use GCC 4.0, 4.2, 4.4 (if present on your system) or even LLVM/GCC 4.2. Please refer to proper compiler version docs for specific information.