New to MATLAB. Getting the error First input argument must be a function handle. While attempting to integrate current function

Question: So this is what I have so far
t=60;

q=integral(e(t)*i(t), t, 0, 2*pi);

function v=e(t)

v=160*sin(t);

end

function c=i(t)

c=2*sin(t-(pi/6));

end

but it is returning the following errors and I have no idea how to fix it. I've looked at other posts referencing the same error and I haven't been able to fix it.
Error using integral (line 82)
First input argument must be a function handle.

Error (line 10)
q=integral(e(t)*i(t), t, 0, 2*pi);

Any help will be greatly appreciated
Comment: Have you read the documentation for the integral command? It has bunch of working examples that you can easily modify to suit your needs. https://www.mathworks.com/help/matlab/ref/integral.html
Answer: You should have something like this:
e_times_i = @(t) e(t) .* i(t)
q=integral(e_times_i, 0, 2*pi);

Indeed, the first argument of integral matlab function handle. You gave value not the function handle.
Comment: Thank you for your response, I'm absolutely horribe with MATLAB, but hoping to get better. I incorporated that into my script file, however it is still returning errors.

Error in [name]>e_times_i (line 23)

y = e(t) * i(t);

Error in [name] (line 12)

q=integral(e_times_i, 0, 2*pi);

@Sunghee Yun
Comment: @crisluengo Thank you for the response, I have been attempting that in varying forms, but end up with a massive list of errors when I attempt to call the function in the integration function. I'm not sure what I'm doing wrong, but would I also need a handle for the functions within e_times_i?
Comment: @alistenberger I corrected my answer. This should work! I tested in octave. Hope this'd help you!
Comment: @alistenberger My Pleasure! *^^* Great to feel helpful. :)


In k-means, why does the sum of distances to the cluster not account for the size of the cluster?

Question: Wikipedia gives one formulation for the k-means problem as:

where we intend to find a set of clusters $S = \{S_1, \ldots, S_k\}$ to minimize this value. However, the equivalent formulation

divides the sum of pairwise distances by the size of the cluster. Intuitively, why does the first formulation (using sum of distances from center) not divide by the size of the cluster as well, while the second one does?
Answer: Intuitively, it is because the second sum has many more summands.
To be precise, we have to show that for all $i=1,\ldots,k$:
$$
\frac{1}{|S_i|}\sum_{x, y\in S_i}\|x - y\|^2 = \sum_{x\in S_i}\|x-\mu_i\|^2.
$$
But, using the identity:
$$
\sum_y\|x - y\|^2 = \|x-\mu_i\|^2 + \sum_{y\ne x}\|\mu_i-y\|^2,
$$
which is just Pythagoras, we get:
$$
\begin{align}
\sum_{x, y\in S_i}\|x - y\|^2 &= \sum_{x}\left[ \|x-\mu_i\|^2 + \sum_{y\ne x}\|\mu_i-y\|^2\right]\\
    &= \sum_x \sum_y\|\mu_i-y\|^2\\
    &= |S_i|\sum_y\|\mu_i-y\|^2,
\end{align}
$$
which is what we wanted to show.


Why does setting a default parameter value make this function a closure?

Question: I'm writing an application where Tags are linkable and there's a need to retrieve the entire chain of linked Tags. Self-reference is not allowed. Running the following code ends up with some very strange results:
class Tag(object):
  def __init__(self, name):
    self.name = name
    self.links = []

  def __repr__(self):
    return "<Tag {0}>".format(self.name)

  def link(self, tag):
    self.links.append(tag)

def tag_chain(tag, known=[]):
  chain = []
  if tag not in known:
    known.append(tag)
  print "Known: {0}".format(known)

  for link in tag.links:
    if link in known:
      continue
    else:
      known.append(link)
    chain.append(link)
    chain.extend(tag_chain(link, known))
  return chain

a = Tag("a")
b = Tag("b")
c = Tag("c")
a.link(b)
b.link(c)
c.link(a)

o = tag_chain(a)
print "Result:", o
print "------------------"
o = tag_chain(a)
print "Result:", o

Results:
Known: [<Tag a>]
Known: [<Tag a>, <Tag b>]
Known: [<Tag a>, <Tag b>, <Tag c>]
Result: [<Tag b>, <Tag c>]
------------------
Known: [<Tag a>, <Tag b>, <Tag c>]
Result: []

So, somehow, I've accidentally created a closure. As far as I can see, known should have gone out of scope and died off once the function call completed.
If I change the definition of chain_tags() to not set a default value, the problem goes away:
...
def tag_chain(tag, known):
...
o = tag_chain(a, [])
print "Result:", o
print "------------------"
o = tag_chain(a, [])
print "Result:", o

Why is this?
Answer: This is a common mistake in Python:
def tag_chain(tag, known=[]):
  # ...

known=[] doesn't mean that if known is unsupplied, make it an empty list; in fact, it binds known to an "anonymous" list.  Each time that known defaults to that list, it is the same list.
The typical pattern to do what you intended here, is:
def tag_chain(tag, known=None):
    if known is None:
        known = []
    # ...

which correctly initializes known to an empty list if it is not provided.
Comment: Thanks for the clear answer. I'm accustomed to Python being much more explicit than this. If anyone knows the rationale behind this decision, I'd be really interested to see it.
Answer: Maybe as an extra eplanation what happens: Default parameters are simply stored on the function object itself (ie tag_chain.func_defaults in Py2 ) and used to extend the argument when needed:
>>> def x(a=['here']):
...     a.append(a[-1]*2)
...
>>> x
<function x at 0x0053DB70>
>>> x.func_defaults
(['here'],)

In this example you can watch the default list grow there:
>>> x()
>>> x.func_defaults
(['here', 'herehere'],)
>>> x()
>>> x.func_defaults
(['here', 'herehere', 'herehereherehere'],)

Modifying default arguments is somewhat like changing class variables.


How did "Mary had a little lamb" become popular blues?

Question: "Mary had a little lamb" had long been a popular choice for blues musicians to jam and solo on stage. Ever since watching the rendition by Buddy Guy and Stevie Ray Vaughan, it also had been one of my favorites to solo blues on.
Just recently I though about this: it makes sense to me that songs with context and lyrics like "Crossroad", "Johnny B. Good", "Sky is crying", "Sweet home Chicago" etc. are blues.
But I do not get why "Mary had a little lamb", supposedly a 19th century nursery rhyme, was taken and rendered by blues musicians.  Does anyone know the history or background of how this transformation is made?
I would assume there is a story behind or else many of its likes such as "London bridge is falling down" or "Twinkle twinkle little star" would also be re-rendered as blues songs (but they don't, at least to my knowledge), and these are certainly more well-known than "Mary had a little lamb".
[EDIT]
According to this source, Mary had a little lamb was the first song recorded on a phonograph by Thomas Edison. That makes it the first song ever recorded and played back on a device.
Comment: Well, just a hunch but looking at the form of blues (AAB), Mary Had a Little Lamb seems to fit that quite well.  Mary had a little lamb, mary had a little lamb, who's fleece was white as snow.
Comment: Just gonna leave this here: [Sesame Street: Mary Had a Little Lamb | Kermit News](https://www.youtube.com/watch?v=RrJnzBFzEEY)
Comment: [This](http://truefire.com/blog/guitar-lessons/blues-genealogy-mary-had-a-little-lamb/) may not exactly answer your question, but I found it an interesting read on the subject. EDIT: [Check this out](http://www.time.com/time/specials/packages/article/0,28804,1999143_1999210_1999211,00.html) as well. :)
Answer: A friend and I have beat this subject to death over the years...
The consensus in our crowd is that Buddy Guy most likely did it
1) as a goof which worked too well to leave off his record or
2) BG was looking for a way to hide what he stole from Freddy King/Earl Hooker :)


Temperature converter program in C is not working . Stops after executing some code (run time error)

Question: I have written a C program which converts temperature from fahrenheit to celcius. It has three functions , input_temp() , input_unit() and calculate() . Idea is simple . input_temp() asks the user to enter the value of temperature . input_unit() asks the user to enter the unit i.e. F for fahrenheit and C for celcius . Calculate() converts the temperature based on the units (celcius to fahrenheit or fahrenheit to celcius) . I am using Code::Blocks as my IDE , But whenever I tried to run this program , Code::Blocks stopes working after asking the unit of numerical temperature . When I tried to run the same code in ideone.com , it says Runtime error . Here is the code:
#include <stdio.h>
#include <stdlib.h>

calculate(float T , char U[]);

int main()
{
    float temp ;
    char unit[5] ;
    float ans ;

    temp = input_temp() ;

    strcpy(unit, input_unit()) ;

    ans = calculate(temp , unit) ;

    printf("Converted temperature is %f ." , ans);

    return 0;
}

int input_temp()
{
    float x ;

    printf("Enter the temperature : ") ;
    scanf("%f" , &x ) ;
    return x ;
}

input_unit()
{
    char Unit[5] ;
    printf("Enter the unit (C or F) : ") ;
    scanf("%s" , Unit) ;
    return Unit ;
}

calculate(float T , char U[])
{
    float convert ;
    if (strcmp(U , 'F') == 0)
    {
        convert = (T-32)*5/9 ;
    }
    else  // if(strcmp(U , 'C') == 0)
    {
        convert = (T*9/5)+32 ;
    }
    return convert ;
}

I believe I made some mistake in Calculate() function (But I am not sure) . Please help me to figure it out . And how to determine Runtime Error?
Comment: Your compiler surely raised some warnings about this code. What are they?
Comment: You haven't added function prototypes of all the functions before the beginning of the main()!!! Edit return type of input_unit() as a `char*`!!! There are several errors.
Answer: strcmp(U , 'F')

is wrong. You need
strcmp(U , "F")

strcmp takes char arrays not chars. 'F' becomes the integer value of char 'F' - for eg. in ASCII it's 70. So strcmp looks for a char array starting at address 70.
Comment: Thanks for your help , working :) . But it is giving only interger values . Eg :- 10 F in digree celcius is -12.000000 , Why it is not giving -12.2222 .
Comment: Because 5/9 will be calculated as a constant at compile time, using integer math. You can do 5.0/9 or use a decimal constant.
Answer: There's no need to store the required units in any more than a char. With some other cleaning up:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

float calculate(float T , char unit);
float input_temp();
char input_unit();

int main()
{
    float temp ;
    char unit;
    float ans ;

    temp = input_temp();
    unit = input_unit();
    ans = calculate(temp ,unit);

    printf("Converted temperature is %f.\n" , ans);
    return 0;
}

float input_temp()
{
    float x ;

    printf("Enter the temperature : ") ;
    scanf("%f" , &x ) ;
    return x ;
}

char input_unit()
{
    char U[5];
    printf("Enter the unit (C or F) : ") ;
    scanf("%s" , U) ;
    if (strcmp(U, "F") == 0) {
        return 'F';
    }
    return 'C' ;
}

float calculate(float T , char U)
{
    float convert ;
    if (U == 'F')
    {
        convert = (T-32)*5./9 ;
    }
    else
    {
        convert = (T*9./5)+32 ;
    }
    return convert ;
}


Using custom root with FiddlerCore

Question: Is it possible to use a custom root CA for FiddlerCore to intercept HTTPS traffic.
What I need is assigning a certificate to be used to to sign all host certificates.
Another solution can be supplying certificate information to FiddlerCore before creating root certificate.
Comment: See [this answer](https://stackoverflow.com/a/52204781/3389585) for an up to date solution.
Answer: FiddlerApplication.Startup(9999, FiddlerCoreStartupFlags.DecryptSSL);
var path = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location) + @"\sslcertificate.pfx";
var secureEndpoint = FiddlerApplication.CreateProxyEndpoint(443, true, new X509Certificate2(path, "password"));

You can create your own certificate using Visual Studio tools, however, I used this free program to create a test one cause I am lazy:
http://www.xenossoftware.com/freetools/certificategenerator/
If the certificate is installed on the machine, I believe you can also do the same thing using the X509Store class.
Here is some code to do this (not tested):
FiddlerApplication.Startup(9999, FiddlerCoreStartupFlags.DecryptSSL);
var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
try
{

    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

    var x509Certificate2 = store.Certificates.Find(X509FindType.FindBySubjectName, "YourSSLCertificateName", true)[0];

    secureEndpoint = FiddlerApplication.CreateProxyEndpoint(443, true, x509Certificate2);

}
finally
{
    store.Close();
}

Comment: FiddlerApplication.CreateProxyEndpoint(443, true, new X509Certificate2(path, "password")); ... do the certificate parameter represents the new signing root certificate that will be used instead of DO_NOT_TRUST_FIDDLER Certificate ??
Answer: FiddlerCore does not currently offer the ability to customize the information contained in its self-signed root. It will generate all end-entity certificates chained to the root named DO_NOT_TRUST_FiddlerRoot.
Can you elaborate on why you seek this capability?
Comment: The text in question is provided by Windows and cannot be changed. To install the root without the text, your application needs to be running as an administrator.
Comment: We're using FiddlerCore to provide proxy support on a commercial tool. When user starts the proxy feature, FiddlerCore tries to install Fiddler generated root certificate and FiddlerRoot text is shown. The aim is customizing this text.
Comment: For actually installing the root, you can do so yourself without calling the FiddlerCore method that does that. However, note that the text of the prompt is from Windows, not Fiddler.

X509Store certStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadWrite);
try { certStore.Add(oRootCert);  // May fail due to user declining Windows' security prompt
}
finally { certStore.Close(); }

There are other ways to install the root, but they require that your application is running as admin.
Comment: It is OK to install a root certificate but the problem is that FiddlerCore won't use that certificate to sign automatically generated per-site certificates.
Comment: Yes, you need to install the root certificate that FiddlerCore itself uses. Installing some other certificate wouldn't be useful.
Comment: Do you have a plan to let customize text or use custom root certificate?
Answer: You can use oDefaultClientCertificate property of FiddlerApplication to specify existing certificate. I used this on my window service application using FiddlerCoreAPI to capture HTTPS traffic.
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
path = path.Replace("file:\\", "");
if (!path.EndsWith(@"\")) path += @"\";
path += "FiddlerRoot.cer";

FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
FiddlerApplication.oDefaultClientCertificate = new X509Certificate(path);
FiddlerApplication.Startup(8888, FiddlerCoreStartupFlags.DecryptSSL);

Comment: `oDefaultClientCertificate` concerns what client certificate is used; the question is about the root certificate used for *server* certificate generation.

Using custom root with FiddlerCore


How to calculate percentile in a pd dataframe?

Question: Trying to calculate the percentile of a value in a pd column but only for x number of values:
Column name = 'Signal'
50
20
30
20
102
22
1
2
43
49
38
173
371
312

Next to each value would like to calculate on a rolling basis the percentile of that value among X numbers preceding that one (inclusive).
Thanks!
Answer: You can use scipy.stats.rankdata() to calculate your data's rank and pd.rolling() to calculate the rank on a rolling basis.
import pandas as pd
import numpy as np
from scipy.stats import rankdata

df = pd.DataFrame({'Signal':[50,20,30,20,102,22,1,2,43,49,38,173,371,312]})

def last_value_rank(arr):
    """
    Calculates the last value's rank.
    Rankings start from 1.
    Duplicates are considered (e.g. [1,3,2,2] ranks are [1,4,2.5,2.5], result = 2.5)
    """
    return rankdata(arr)[-1]

def last_value_rank_normalized(arr):
    return (last_value_rank(arr) - 1) * 100 / (len(arr) - 1)

print(df.join(df['Signal'].rolling(5).agg([last_value_rank, last_value_rank_normalized])))

output:
    Signal  last_value_rank  last_value_rank_normalized
0       50              NaN                         NaN
1       20              NaN                         NaN
2       30              NaN                         NaN
3       20              NaN                         NaN
4      102              5.0                       100.0
5       22              3.0                        50.0
6        1              1.0                         0.0
7        2              2.0                        25.0
8       43              4.0                        75.0
9       49              5.0                       100.0
10      38              3.0                        50.0
11     173              5.0                       100.0
12     371              5.0                       100.0
13     312              4.0                        75.0

Comment: Thank you for this. It seems your suggestion is asking for a specific percentile and obtaining an output.

What if you wanted to see which percentile a given value represented in the array. For example, if we roll based on 5 values, the first result would come at index 4:

[50,20,30,20,102] >> output the percentile of '102' amongst those numbers, then
[20,30,20,102,22] >> output the percentile of '22' amongst those numbers, and so on.. on a rolling basis.

I hope that's clear...
Comment: Thanks for the clarification. Based on your explanation, what you are looking for is the data's **rank**, not the percentile. Consider updating your question with the correct terminology and include the sample you've shown in your comment to help other people who might have the same issue.
Comment: Updated my answer to fit your clarification. Please let me know if I missed something.


How to generate and manage token after spring security authentication

Question: I have an android application where i am using spring security for authentication and authorization purpose at the server end.At first user enters the user name and password and send it via request using Rest Template to the server controller for authentication.I have done the authentication part for this user name password request.Now i have to generate a token for successive request authentication.But i don't know how to do this.Here is what I was thinking of-
a) Have an AES key generated and stored.
b) encrypt the username + timestamp with this AES key (you my have to base64 encode after this step to avoid any special characters). This will be your user token.
c) sign this token with an HMAC key (again store this in keystore).
d) send the token along with the signature (use ; as the delimiter).
e) store the token which you got in step c against the username in the DB.
The token would be send to the client as part of the response.
I don't know how to implement the above method.I have searched all over the web but didn't find anything usefull.
Below is my code that i have used for authentication.
try{
        System.out.println("Request received... ");
        Gson gson = new Gson();
        TestUser userChk=new TestUser();
        userChk=gson.fromJson(coaObj, TestUser.class);
        Authentication authenticationToken = new UsernamePasswordAuthenticationToken(userChk.getUserName(), userChk.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        System.out.println("getAuthorities is "+authentication.getAuthorities()+" getCredentials "+authentication.getCredentials()+" getDetails "+authentication.getDetails()+" getPrincipal "+authentication.getPrincipal());
        return "Authenticated";
    }catch(Exception er){
        System.out.println("Authentication error "+er);
        return "Authentication failure";
    }

Someone please help me to generate the token in this approach and managing this.
Answer: Recently I worked on a project in which we exposed REST APIs for web and mobile apps. You can send cookies after authentication success (to maintain session). It works for mobile apps as well. You will need to extend SimpleUrlAuthenticationSuccessHandler and send cookies in response, you can also set cookie age, if you want the session to persisted for a longer time.
package com.arjun.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.informage.arnav.dto.response.LoginUserResponseDto;
import com.informage.arnav.service.UserService;
import com.informage.arnav.util.ApplicationUtil;

public class AppSimpleUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

     @Autowired
    ApplicationUtil applicationUtil;

    @Autowired
    UserService userService;

    private RequestCache requestCache = new HttpSessionRequestCache();

    public AppSimpleUrlAuthenticationSuccessHandler() {
        super();
        setRedirectStrategy(new NoRedirectStrategy());
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws ServletException,
        IOException {

        super.onAuthenticationSuccess(request, response, authentication);

        AppUserDetails appUserDetails = applicationUtil.getCurrentUser();
        appUserDetails.setSessionId(request.getSession().getId());
        Cookie[] cookies = request.getCookies();
        if (cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie != null) {
                    if (cookie.getName().equals("JSESSIONID")) {
                        String value = cookie.getValue();
                        cookie.setMaxAge(1555200000);
                        cookie.setPath("/");
                        //cookie.setHttpOnly(true);
                        response.addCookie(cookie);
                    }
                }
            }
        }

        LoginUserResponseDto dto = userService.getDtoFromUserName(appUserDetails.getUsername());
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(dto);
        response.getWriter().write(json);
        response.addHeader("Content-Type", "application/json");
        response.getWriter().flush();

    }

}

code for getCurrentUser method is:
public AppUserDetails getCurrentUser() {
    final Object principal = SecurityContextHolder.getContext()
                                                  .getAuthentication()
                                                  .getPrincipal();
    final AppUserDetails appUserDetails;
    if (principal != null && principal instanceof AppUserDetails) {
        appUserDetails = (AppUserDetails) principal;
    } else {
        appUserDetails = null;
    }

    return appUserDetails;
}

Finally you need to configure this in your security.xml file.
<beans:property name="authenticationSuccessHandler"
        ref="mySuccessHandler" />

<beans:bean id="mySuccessHandler"
    class="com.informage.arnav.security.AppSimpleUrlAuthenticationSuccessHandler" />

Comment: i think cookie is not a safe approach.


compilation Error in Task.ContinueWith when passing TaskScheduler.FromCurrentSynchronizationContext as second parameter

Question: private  void CountWithTask_Click(object sender, RoutedEventArgs e)
{
   lblOutput.Content = "file is in processing...";
   var taskInt = CountWords();
   taskInt.ContinueWith(x =>
   {
      MessageBox.Show("process has been done.");
      lblOutput.Content = $"count of words in file are :- {x.Result}";
      },TaskScheduler.FromCurrentSynchronizationContext);
   }
}

in the code snippet where I have return "x.Result",I am getting the compilation error at that point. and the error is image 1
"Task does not contain a definition for 'result' and no extension method 'Result' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly refernce?)"
if I remove that line then it is giving error at TaskScheduler, and the error is
"Argument 2: cannot convert from 'method-group' to Cacellationtoken."
enter image description here
code for the CountWords method:
public async Task<int> CountWords()
        {
            Debug.WriteLine(string.Format($"Thread ID: {Thread.CurrentThread.ManagedThreadId.ToString()}"));
            await Task.Delay(2000);
            int count;
            StreamReader reader = new StreamReader(FileName);
            var str = await reader.ReadToEndAsync();
            count = str.Length;
            reader.Close();

            return count;
        }

Comment: I assume that `CountWords()` returns just `Task`? Try making it `Task` as only the generic version of `Task` has a `Result` property.
Comment: public async Task CountWords()
        {
            Debug.WriteLine(string.Format($"Thread ID: {Thread.CurrentThread.ManagedThreadId.ToString()}"));
            await Task.Delay(2000);
            int count;
            using (StreamReader reader = new StreamReader(FileName))
            {
                var str = await reader.ReadToEndAsync();
                count = str.Length;
            }
            return count;
        }
Comment: this is the CountWords method @Scott.
Answer: I got the issue the issue was very small my mistake and my negligence towards the intelligence. :)
     I am using only "TaskScheduler.FromCurrentSynchronizationContext", which is wrong becuase "FromCurrentSynchronizationContext" is a method and it should be like this "TaskScheduler.FromCurrentSynchronizationContext()".
Proper code would be this :
private  void CountWithTask_Click(object sender, RoutedEventArgs e)
{
   lblOutput.Content = "file is in processing...";
   var taskInt = CountWords();
   taskInt.ContinueWith(x =>
   {
      MessageBox.Show("process has been done.");
      lblOutput.Content = $"count of words in file are :- {x.Result}";
      },TaskScheduler.FromCurrentSynchronizationContext());
   }
}

Thanks for the response @scott.
Thanks Stackoverflow.  :)
Comment: Oh ... what a misleading error message ! I could not figure out for 30 minutes ... Thank you !


Lookup query parameters in Yesod

Question: I just initialized a Yesod project (no database) using yesod init.
My HomeR GET handler looks like this:
getHomeR :: Handler Html
getHomeR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getHomeR" :: Text
    defaultLayout $ do
        aDomId <- newIdent
        setTitle "Welcome To Yesod!"
        $(widgetFile "homepage")

When using yesod devel, I can access the default homepage at http://localhost:3000/.
How can I modify the handler listed above to retrieve (and display) a HTTP GET query parameter like id=abc123 when accessing this URL:
http://localhost:3000/?id=abc123
Note: This question was answered Q&A-style and therefore intentionally doesn't show research effort!
Answer: I'll show two different methods to achieve this. For both, you'll need to add this code to your template, e.g. in homepage.hamlet:
Note that it is not guaranteed there is any id parameter present when accessing the URL, therefore the type resulting from both methods is Maybe Text. See the Shakespearean template docs for a detailed explanation of the template parameters.
Method 1: lookupGetParam
The easiest way you can do this is using lookupGetParam like this:
idValueMaybe <- lookupGetParam "id"

When using the default setting as generated by yesod init, idValueMaybe needs to be defined in both getHomeR and postHomeR if idValueMaybe is used in the template.
Your HomeR GET handler could look like this:
getHomeR :: Handler Html
getHomeR = do
    idValueMaybe <- lookupGetParam "id"
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getHomeR" :: Text
    defaultLayout $ do
        aDomId <- newIdent
        setTitle "Welcome To Yesod!"
        $(widgetFile "homepage")

Method 2: reqGetParams
Instead of looking up the query parameters by name, you can also retrieve a list of query key/value pairs using reqGetParams. This can be advantageous in certain situations, e.g. if you don't know all possible keys in advance. Using the standard lookup function you can easily lookup a certain key in that list.
The relevant part of your code could look like this:
getParameters <- reqGetParams <$> getRequest
let idValueMaybe = lookup "id" getParameters :: Maybe Text

Your getHomeR could look like this:
getHomeR :: Handler Html
getHomeR = do
    getParameters <- reqGetParams <$> getRequest
    let idValueMaybe = lookup "id" getParameters :: Maybe Text
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getHomeR" :: Text
    defaultLayout $ do
        aDomId <- newIdent
        setTitle "Welcome To Yesod!"
        $(widgetFile "homepage")

Comment: how to use the second method with a POST method request?

Lookup query parameters in Yesod


Dojo > ItemFileWriteStore > How to get only those cells with changes (Not every cell in the row)

Question: Using either _saveCustom() or onSet(), I can find out when values have changed in an ItemFileWriteStore, however, in both cases, I get every cell in the row, even though only 1 cell (for example) has changed.
Anyone know of a way to find only those cells that have changed?  Right now, the only thing I can think of is to maintain a separate copy of the data and compare against it.
Answer: I firebugged the notification handling and came up with this, which seems to work:
store.onSet = function(row, cellName, oldValue, newValue){
    if (oldValue !== newValue){
        alert(cellName + " changed  to: " + newValue);
    }
}


Targeting S+ (version 31 and above) requires that an explicit value for android:exported be defined when intent filters are present

Question: I need to upgrade the sdk version to 31 because I tried to use react native vision camera package
In there it is recommend to upgrade to sdk version 31
here is the link https://mrousavy.com/react-native-vision-camera/docs/guides/troubleshooting/#android
This is my current AndroidManifest.html. As per other post from stack overflow post.
I already added "android:exported=true" to the main activity. But the error still here
Targeting S+ (version 31 and above) requires that an explicit value for android:exported be defined when intent filters are present]
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.abc">

        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.VIBRATE"/>
        <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

        <application
            android:name=".MainApplication"
            android:label="@string/app_name"
            android:icon="@mipmap/ic_launcher"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:allowBackup="false"
            android:theme="@style/AppTheme">

        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>

        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@color/white"/>

        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>

                 <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

            <activity
                android:name=".MainActivity"
                android:exported="true"
                android:label="@string/app_name"
                android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
                android:launchMode="singleTask"
                android:windowSoftInputMode="adjustResize">
                <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
                        <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
</manifest>

This is the error log
> Task :app:installDebug FAILED
Installing APK 'app-debug.apk' on 'Pixel_2_API_32(AVD) - 12' for app:debug

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.7/userguide/command_line_interface.html#sec:command_line_warnings
357 actionable tasks: 7 executed, 350 up-to-date
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/03 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/03 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/03 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Unable to install /Users/kerrydss/Desktop/Work/bhg-ecommerce-rn/android/app/build/outputs/apk/debug/app-debug.apk
com.android.ddmlib.InstallException: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED: Failed parse during installPackageLI: /data/app/vmdl227096480.tmp/base.apk (at Binary XML file line #76): ***com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver: Targeting S+ (version 31 and above) requires that an explicit value for android:exported be defined when intent filters are present***
        at com.android.ddmlib.internal.DeviceImpl.installRemotePackage(DeviceImpl.java:1224)

When I try to add android:exported=true to the receiver line receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver above inter-filter the app is successfully built but always quit For inter-filter for firebase push notification the document recommend to use android:export=false. When I use false the app won't build
I start getting this error when I change the SDK version
buildscript {
    ext {
        ext {
        googlePlayServicesVersion = "+" // default: "+"
        firebaseMessagingVersion = "21.1.0" // default: "21.1.0"
       //working version without camera package
       // buildToolsVersion = "29.0.3"
       // minSdkVersion = 21
       // compileSdkVersion = 29
       // targetSdkVersion = 29
       // ndkVersion = "20.1.5948944"

         buildToolsVersion = "30.0.0"
         minSdkVersion = 26
         compileSdkVersion = 31
         targetSdkVersion = 31
         ndkVersion = "20.1.5948944"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.2")
        classpath('com.google.gms:google-services:4.3.1')
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Comment: I have not tried add up `android:exported ` for application. But I do tried to add `android:exported ` to the receiver that wrap  `intent-filter `. The app is built but it always close by itself
Comment: Upgrade android studio, Update gradle versions and set exported= true/false for all activity/service/broadcast receivers.
Comment: I got the same issue. please help me out if you find any solution
Answer: Maybe you are using third party libraries that add some new components with a missing exported property. Click on the tab "Merged Manifest" when you have an xml file open with the manifest: see if there is a component and if it is found, just add it to your manifest with the android:exported="false" or "true" property. All components such as: activity, receivers, service must contain the android:exported field.
Answer: AndroidManifest.xml
<receiver android:name=".NotificationReceiver" android:exported="true">

Comment: Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post.


Playing a C Recorder with classical guitar

Question: The guitar is normally a G tuning instrument but recorders are C or F instruments,Do I need to alter standard guitar tuning to eg C tuning, in order to play with a C Recorder eg Descant or Tenor, or F, to play with a treble recorder? Guitar also sounds an octave lower to what it is tuned to, but I should imagine this causes no issues.
Comment: I'm voting to close this question because the premise is false
Comment: @Tim that's not correct, the answer is the fact that the premise is false, as is demonstrated by your own answer below. If every question consisting of an incorrect premise got closed, all Stack Exchange sites would lose a great many valuable questions.
Comment: @CarlWitthoft Why would that be a cause to close a question?
Comment: @Nacht - if the premise is false, there actually won't be a tangible question, thus no direct answer.
Comment: @Nacht & Tim: In this case, the question contained a very answerable core, "should I do anything funny when using these two instruments together," and the answers are conceivably helpful to others. But one could imagine a question so mistaken that the only answer is fairly useless: "Why didn't Beethoven finish his 8th symphony?" "Uh... he did. I guess you're thinking about Schubert."
Comment: @Nacht - so, how can a question posed using false premises (we have several on this site, lately) be of use to anyone except the OP, who gets told that the question is invalid rather than valuable?
Comment: @Tim a question asked on false premises isn't invalid; it just elicits an answer that is unexpected by the asker.  But if one person in however many billions of internet users asked this question, surely others will search for [c recorder guitar tuning](https://duckduckgo.com/?q=c+recorder+guitar+tuning), for which search this question and its answers are currently being returned to me as the first result.  (And if you thought the question was invalid, why did you answer it?)
Comment: @phoog - answered in the hope it would explain why it was invalid (in my opinion). There are inaccuracies quoted in the question, I tried to address those. Several folk seem to be of the same opinion, judging by uvs!
Answer: 'Guitars are normally G tuning' - no, they're not. They play quite happily in any key, unless open tuned. They're chromatic instruments.
So, play your C, or F (or any other transposing or fixed key instrument, e.g. C harmonica) and play the appropriate chords for it on guitar. If necessary, use a capo on guitar to get chord shapes that are easier/better sounding, but that's about it!
Comment: Guitars play quite happily in any key. Guitar*ists*, however, may complain vociferously.
Comment: The recorder transposes poorly. The guitar only transposes poorly when open string notes are involved, and in some of those cases, a device called a *capo* can transpose them anyway.  E.g. a melody in C on a C recorder will not nicely transpose to C#; almost every fingering will require tricky partial holing or lower holes to be covered. The guitarist just moves the hand half step to a higher fret and plays the same scale pattern.
Comment: @leftaroundabout - with guitar (and bass), one can play exactly the same fingering in numerous keys (every key) using the same pattern, and even the same shapes for chords, as I'm sure you know. So transposition is a doddle. Whereas on recorder (and just about every other instrument), different fingerings are necessary for each different key. That's the nub of this.
Comment: @WayneConrad - just tell him he's in A#. He'll be a s happy as a pig in $#it..!!!
Comment: "Guitars ... play quite happily in any key" - yes, and so do recorders, though it's not quite as easy to transpose as on guitar.
Comment: @leftaroundabout On a recorder some keys are easier than others. On guitar they're more or less the same.
Comment: @ojs recorder is actually surprisingly key-agnostic, moreso than e.g. cello. Only the very lowest notes are really more awkward to play as sharps/flats than naturals. This is _quite_ like guitar, where also the lowest position / open strings have a strong preference to certain keys but the higher positions don't. The difference, as I already said, is that _transposing_ is much more difficult, and especially transposing to a weird key is not something a recorder player will have experience with. So it's difficult for the mind even though it doesn't really get more difficult for the fingers.
Comment: To echo what @avid said, a lot depends on the background and training of the guitarist.  A guitarist who is comfortable playing in informal jams may be heavily biased towards the sharp keys.  Call a tune in Bb and some guitarists will be very unhappy with you.
Answer: You can play a guitar in any key. You can play a recorder (whether C or F) in any key (although beginners are happiest in keys with few sharps or flats). There's no need to retune or transpose.
A guitar sounds an octave lower than it is notated. If you really need a unison with a recorder you might need to play an octave higher, otherwise it's no problem.
Answer: Some instruments, mostly brass, are transposing, which means that the notes written for them won't correspond with the sounding notes: trumpets are commonly b-flat trumpets, which means that when you play a written c', a b-flat sounds.
Both recorders and guitars are not transposing (give or take an octave for guitars and some recorders). So even when we say that a treble/alto recorder is in F, it's not considered a transposing instrument, because we still name the notes by what sounds, not by the fingering.
Comment: Seems we got off-piste with comments on my question - considering playing in *any* key. So, as far as 'transposing' instruments, you're right, except for the octaves, which won't affect the considerations of this question.
Answer: No. The tuning refers to what sounds come out of your instrument when you hit the open strings or respectively close every whole on the recorder. Also not sure what makes you think the guitar is tuned in g, the standard tuning is usually e a d g b e (from low e to high e).
You can still play lots of keys on both instruments by using different fingerings, both are chromatic instruments so you can hit every note in a given scale and aren't limited to one. That might be more difficult for the more exotic but generally you're flexible with that.
Also with regards to transposing instruments, that's about the notes in sheet music vs the notes that come out of your instrument. So some instruments transpose their notes to be better readable in sheet but when they play a different note comes out so you have to account for that. But the standard guitar plays an octave lower than notated while the soprano recorder plays an octave higher than notated. So essentially you avoid complicated ledger lines that way but essentially still play the same note just lower or higher.
Same goes for the alto just that you don't start with c but with f.
Answer: Your premise is false as both guitar and recorder are by and large chromatic instruments capable of being played in any key.  Both recorder and guitar are written at pitch with a possible octave offset (guitar is played an octave lower than written, soprano recorder an octave higher than written, alto recorder either at pitch or an octave higher; its fingering starts with an F though as opposed to the soprano and tenor recorder starting with a C).
Apart from the pitches themselves, there also is intonation.  Guitar is a uniformly fretted instrument; consequently it is usually tuned using equal temperament.  While the bulk of the open strings fit a G chord, tuning them to pure intervals (like when using flageolet tuning tecnniques without modification) tends to make numerous chords work rather badly.  So the usual tuning is one of equal temperament, as opposed to unfretted string instruments (like the violin) which are usually tuned in pure fifths, and in playing practice avoid the use of open strings other than for double stops.
Due to the fretting, guitar intonation is basically fixed.  This can cause problems in connection with the very pure and straight tones of recorders: professional recorder players have some leeway in intonation as well as vibrato techniques; young players tend to produce fixed pitches.  A recorder can be tuned to very little degree by adjusting the mouth piece but that comes at the cost of impacting the integrity of its overall intonation.
So while there are no transposition issues, the pleasantness of the guitar/recorder combination depends on the guitar being well-tuned to the occasion and the recorder player being skilled enough to fine-tune intonation on the fly.
As more instruments (or just environmental noise) is added, the intonation problem becomes less obvious.


Para que serve o Mathf.abs

Question: estou programando no unity e vejo muitas pessoas usando isso, e as vezes ate uso nos meus scripts mas não entendo exatamente oque ele faz "retorna", por favor me explica?
Comment: Valor absoluto (ou módulo) de um número. https://docs.unity3d.com/ScriptReference/Mathf.Abs.html
Answer: Retorna o valor absoluto.
O valor absoluto de um Decimal é seu valor numérico sem seu sinal
como no exemplo na documentação do Unity
<code>    Debug.Log(Mathf.Abs(-10.5f));// prints 10.5
    Debug.Log(Mathf.Abs(-10));// prints 10
</code>

Para que serve o Mathf.abs


How can I check if a Prolog rules was already fired?

Question: I need to check if a rule was already "fired" before to fire it again. I mean before asserting a new fact I need to know if the same fact was already asserted in the previous loop iteration.
I tried to use a list but I think they aren't so "friendly" for my problem. What else can I use to do this?
Comment: Upon successful application of a rule you can record it using `assert` and check whether the rule has been asserted before. This is under assumption that you need to apply every rule only once (as opposed to e.g. applying it only once for every possible input). Some more refined bookkeeping is needed but I cannot show it in the comment.
Comment: I don't understand why this question is on hold, it's perfectly clear to me. You could write a meta-interpreter which checks, but this is unlikely to be within reach if you're a newbie. Still, it's the approach I would be inclined to try. [This link](http://www.complang.tuwien.ac.at/ulrich/prolog_misc/acomip.html) has a discussion of some simple meta-interpreters, including one that can detect redundant rules. Give it a shot, it may be exactly what you need.
Comment: One question: you don't mean "before asserting a new fact", you mean "before entering a clause," right?
Comment: @TonyH: you could try `..., (fact -> true ; assert(fact)), ...`, as Alexander already suggested. Of course, be aware those assertions are **not** undone if your program (as usual in Prolog) need to backtrack. This fact could make you to reconsider 'friendness' of lists...
Comment: Thank you all for the response. I'm sorry for the misunderstood.. I'm trying to specify better what I need:
I insert into the system the fact, at the end of the input data the fact are processed to get a solution, and this works fine.
But I need to check if exists another solution (different OR partially different from the first one). To do so I need to know which rules are already fired (in previous loop) to fire a different rule (if exists).
How can I do this?
Comment: @TonyH - you might consider the failure-driven loop that would fail after generating a solution and force Prolog to backtrack and explore other possibilities: `failure_driven_loop(Info):- generate( Info,Term), fail. failure_driven_loop(Info).` (example is from Paul Brna's book: http://homepages.inf.ed.ac.uk/pbrna/prologbook/node95.html). Solutions found can be recorded with `assert`. As CapelliC has pointed out, assertions are not undone if your program backtracks, so your solutions will be preserved.
Answer: I'm rephrasing my comment above as an answer to elaborate a bit more on it.
You might consider the failure-driven loop that would fail after generating a solution and force Prolog to backtrack and explore other possibilities:
failure_driven_loop(Info):- generate(Info,Term), fail.
failure_driven_loop(Info).

(example is from Paul Brna's book). In this example Term records a solution and generate/2 generates solutions for the given Info. The second clause is needed to make the loop succeed when all solutions have been exhausted.
Once a solution has been generated, the first clause fails and the execution backtracks, i.e., Prolog will try to find a different proof for generate(Info,Term), which will commonly involve different clauses either for generate/2 itself or for one of the predicates directly or indirectly invoked by generate/2. If you would like to ensure that once generate/2 has used one of its clauses it should not try and reuse the same clause, you should add cuts, i.e., instead of
generate(Info,Term) :- solve_somehow(Info,Term).
generate(Info,Term) :- solve_in_some_other_way(Info,Term).

you should write
generate(Info,Term) :- solve_somehow(Info,Term), !.
generate(Info,Term) :- solve_in_some_other_way(Info,Term), !.

Solutions found by generate/2 can be recorded with assert. As @CapelliC has pointed out, assertions are not undone if your program backtracks, so the failure driven loop preserves your solutions:
:- dynamic solution/1.

failure_driven_loop(Info):- generate(Info,Term), assert(solution(Term)), fail.
failure_driven_loop(Info).


Pass a list to a function to act as multiple arguments

Question: In a function that expects a list of items, how can I pass a Python list item without getting an error?
my_list = ['red', 'blue', 'orange']
function_that_needs_strings('red', 'blue', 'orange') # works!
function_that_needs_strings(my_list) # breaks!

Surely there must be a way to expand the list, and pass the function 'red','blue','orange' on the hoof? I think this is called 'unpacking'.
Answer: function_that_needs_strings(*my_list) # works!

You can read all about it here: Unpacking Argument Lists - The Python Tutorial
Answer: Yes, you can use the *args (splat) syntax:
function_that_needs_strings(*my_list)

where my_list can be any iterable; Python will loop over the given object and use each element as a separate argument to the function.
See the call expression documentation.
There is a keyword-parameter equivalent as well, using two stars:
kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)

and there is equivalent syntax for specifying catch-all arguments in a function signature:
def func(*args, **kw):
    # args now holds positional arguments, kw keyword arguments

Answer: Since Python 3.5 you can unpack unlimited amount of lists.
PEP 448 - Additional Unpacking Generalizations
So this will work:
a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)

Comment: @answerSeeker not efficient, but `function_that_needs_strings(*(a+b))`
Comment: how can I do the same with python 2.7 or 3.4?
Comment: wow, can't believe You couldn't before that.
Comment: @answerSeeker more efficient: `function_that_needs_strings(*itertools.chain(a, b))`


Montagem de mapa estilo site bomnegocio.com

Question: Bom, eu gostaria de saber como que se faz pra criar um mapa estilo o do site bomnegocio.com. Eu não sei se naquele mapa existe uma única imagem ou várias imagens agrupadas.
Alguém poderia me da uma luz de como se faz aquele efeito?
Comment: Se está se referindo ao mapa da página inicial, ele é feito com SVG, olhe o código fonte e verá.
Comment: Tem um plugin de edição e criação de SVG, muito bom! http://raphaeljs.com/
Answer: Criar um mapa interativo SVG é simples porém trabalhoso.
Primeiramente deve-se criar o arquivo SVG, É necessário criar os estado separadamente, para isso vou demonstrar utilizando o editor de imagens GIMP:
Abra o GIMP e importe uma imagem do mapa do Brasil

Redimensione a imagem para o tamanho desejado, no exemplo o tamanho é 600px X 590px.
Selecione o primeiro estado, no exemplo selecionei o Acre, mais é indiferente.
Usando a ferramenta de seleção varinha mágica, selecione o estado.

Após selecionado, clique no menu Selecionar > Para vetor

Habilite a janela vetores, clicando no menu Janelas > Diálogos de encaixe > Vetores. Clique com o botão direito no vetor e exportar para vetor:

Salve e abra o arquivo, usando o notepad++, você encontrará o código:
<svg xmlns="http://www.w3.org/2000/svg"
     width="600" height="590"
     viewBox="0 0 432 428">
  <path id="seleçao" ...

Altere o id do path para id desejado do estado, exemplo:
<svg xmlns="http://www.w3.org/2000/svg"
     width="600" height="590"
     viewBox="0 0 432 428">
  <path id="acre" ...

Repita o processo para cada estado, porém nos próximos você somente utilizará o código path gerado. Dessa forma será possível gerar o código SVG do desenho e trabalhar com CSS e jQuery e manipular o mapa da forma que desejar.
No exemplo, criei uma div com id="mapa" e coloquei o código dentro desta div:

  <svg xmlns="http://www.w3.org/2000/svg" width="600" height="590" viewBox="0 0 432 428">
    <path id="acre" data-name="Acre"
        fill="none" stroke="black" stroke-width="1"
        d="M 40.00,152.22
           C 40.00 ..." />
    <text x="15" y="160">AC</text>

    <path id="amazonas" data-name="Amazonas"
        fill="none" stroke="black" stroke-width="1"
        d="M 107.4 ..." />
    <text x="95" y="105">AM</text>
  </svg>

No CSS
#mapa svg path {
    stroke:#200772; /*cor da borda do estado*/
    fill:#4671D5; /*cor do estado*/
    cursor:pointer;
}

#mapa svg path:hover {
    fill:#be2f33;
    stroke:#be2f33;
}

Veja no exemplo simples online, com apenas dois estados JSFiddle, pois conforme mencionei é trabalhoso :)
Obs: Este é um exemplo simples de como criar, pode-se trabalhar para adicionar os textos, siglas e o que mais desejar.
Comment: @abfurlan se eu pudesse votar com up mais de uma vez eu faria! Me ajudou muito!
Comment: Depois de tudo pronto, como eu faço para linkar pagina por pagina de cada estado?
Comment: @Lucas você pode colocar a tag ``, ou pode abrir a página que deseja com jQuery, http://jsfiddle.net/E573B/38/, no exemplo o estado do Acre abre com jQuery e o do Amazonas com tag ``
Comment: Revivendo! é possível realizar o mesmo "serviço" só que com imagens "desenhas" ou seja, imagens que tenha ilustrações reais e não cor solida como o exemplo!


What should I consider when I see a loose hair in a violin bow?

Question: This drawing should do:

These are the hairs of a brand new bow. Straight, clean, etc.
I noticed this:

As you can see, it seems like a certain hair is a bit loose.

Is this bad? (I.e., does it affect performance, produced sound, etc.)
Should I try to remove/cut it? Or perhaps I should change the whole hair set in the bow?
Answer: A loose hair won't vibrate the string in any useful way, and it may catch at unwanted moments.
Remove it, just as you would a broken hair.
Comment: So I just cut it off from both sides with, say, scissors or is there a more technical way to do it? XD
Comment: I use a very sharp knife.
Comment: Simply remove it!
Comment: I just pull it and snap it off. Usually the ends come out cleanly. Edit: But after reading some of the answers I realize it's not a great thing to do. Will cut from now on.
Answer: The guy who rehairs my bows once advised me that I shouldn't completely pluck out the hair, but to leave a little bit on both ends. This is so that the other hairs don't become loose and fall out. He said it's not generally a problem since most people don't break ridiculous amounts of hair, but it makes it easier to rehair your bow and is best for your bow in the long run.  Also, I've found that wrapping the hair around the tip of the bow then pulling effectively leaves a little at the end.
Answer: If you just have one or two, remove it. The best approach is to cut it at the loose bit, then pull the hair away from the rest of the bow and cut it carefully at both ends, right up against the frog and the tip.
You can do this many times before the bow needs restrung.
Remember, using rosin diligently reduces breakages, thus increasing the lifespan of your bow.
Comment: Is the rosin thing true? My intuition is that the bow is more slippy and thus less likely to snag with zero rosin (though you clearly wouldn't want to play it that way as it sounds awful)
Answer: I have always been told to cut broken hairs off a bow (such as with scissors) rather than pull them out, as that will make the bow hair last longer before you need it replaced (that way the rest of the hair is less likely to fall out). I play at an advanced level and was recently told I should have my bow rehaired at least once a year. I doubt you need to rehair it that often (I'm studying violin in school so I play it a lot) but it is something to consider, but make sure you go to someone good because I went to a very mainstream violin shop and he did a terrible job and many of my bow hairs looked like that. Now I only go to people that my peers or teachers go to and have good experiences with. If your whole bow's hair was a mess like mine was you would have to have someone else just completely redo it.
I have not heard the thing about rosin so I don't know anything about that.


Fixing outliers and normalizing a vector using R

Question: I am trying to do factor analysis on a few variables and one particular variable (given in the example below) is covering/ explaining all the variance due to some outliers. I am not sure what else I can do apart from removing this variable from factor analysis. But doing so will lose a lot of information. Hence, I am trying to fix this variable by fixing outliers and then normalizing it.
Initially, the histogram of this vector looks like this -

vec <- c(-10172.83, -8745.45, -8745.45, -7344.71, -4700.3, -3588, -1293.15,
-1006.84, -995.62, -791.5, -634.49, -607.19, -591.17, -402.27,
-397.21, -355.54, -301.01, -295.31, -272.22, -233.65, -168.68,
-148.08, -132.47, -129.05, -115.94, -89.63, -89.63, -85.59, -83.79,
-83.61, -83.61, -83.59, -81.05, -79.73, -76.99, -72.72, -71.02,
-71.02, -70.2, -69.4, -67.56, -64.92, -62.8, -62.61, -60.09,
-58.97, -58.97, -58.48, -55.39, -50.54, -50.54, -43.43, -43.39,
-43.3, -42.85, -42.35, -40.46, -38.9, -37.9, -36.01, -35.41,
-35.22, -34.92, -34.61, -34.23, -32.33, -30.96, -30.35, -30.16,
-29.89, -29.8, -29.16, -28.81, -28.17, -27.56, -27.47, -26.49,
-26.05, -24.4, -23.9, -22.87, -21.92, -20.07, -19.92, -19.62,
-19.31, -18.8, -18.8, -18.38, -17.17, -17.17, -17.06, -16.74,
-16.25, -16.2, -15.84, -15.75, -15.24, -14.78, -14.71, -14.48,
-14.06, -13.88, -13.88, -13.4, -12.93, -12.89, -12.19, -11.98,
-11.83, -11.75, -11.25, -11.23, -11.14, -10.87, -10.72, -10.68,
-10.59, -10.59, -10.58, -10.56, -10.17, -10.15, -9.49, -9.45,
-9.2, -9.13, -8.97, -8.73, -8.66, -8.49, -8.21, -8.1, -8.1, -8.02,
-7.97, -7.95, -7.95, -7.93, -7.83, -7.61, -7.27, -7.23, -6.94,
-6.85, -6.84, -6.7, -6.38, -6.32, -6.21, -6.2, -6.02, -6.01,
-5.98, -5.91, -5.87, -5.87, -5.86, -5.86, -5.86, -5.85, -5.82,
-5.74, -5.66, -5.61, -5.56, -5.56, -5.51, -5.42, -5.31, -5.26,
-5.26, -5.18, -5.17, -4.98, -4.98, -4.74, -4.71, -4.71, -4.7,
-4.7, -4.68, -4.57, -4.56, -4.51, -4.5, -4.5, -4.48, -4.48, -4.46,
-4.36, -4.35, -4.2, -4.16, -4.08, -4.08, -4.07, -4.07, -4.05,
-4.05, -4.01, -3.96, -3.85, -3.85, -3.79, -3.64, -3.51, -3.49,
-3.48, -3.4, -3.39, -3.39, -3.38, -3.37, -3.34, -3.33, -3.33,
-3.32, -3.26, -3.26, -3.25, -3.24, -3.24, -3.21, -3.21, -3.19,
-3.19, -3.19, -3.18, -3.17, -3.16, -3.16, -3.14, -3.13, -3.09,
-3.09, -3.03, -3.01, -2.96, -2.96, -2.91, -2.89, -2.89, -2.88,
-2.84, -2.68, -2.62, -2.62, -2.6, -2.6, -2.6, -2.6, -2.57, -2.55,
-2.54, -2.46, -2.45, -2.42, -2.42, -2.4, -2.38, -2.37, -2.35,
-2.34, -2.28, -2.28, -2.28, -2.28, -2.26, -2.22, -2.22, -2.21,
-2.2, -2.2, -2.2, -2.2, -2.19, -2.16, -2.15, -2.1, -2.08, -2.03,
-1.98, -1.93, -1.92, -1.91, -1.91, -1.9, -1.89, -1.89, -1.89,
-1.88, -1.88, -1.88, -1.87, -1.87, -1.86, -1.86, -1.85, -1.84,
-1.83, -1.83, -1.82, -1.8, -1.79, -1.78, -1.76, -1.76, -1.74,
-1.74, -1.73, -1.73, -1.72, -1.69, -1.63, -1.62, -1.62, -1.6,
-1.6, -1.59, -1.59, -1.57, -1.56, -1.56, -1.55, -1.55, -1.54,
-1.54, -1.53, -1.51, -1.48, -1.48, -1.47, -1.47, -1.46, -1.44,
-1.44, -1.44, -1.43, -1.42, -1.4, -1.39, -1.39, -1.37, -1.34,
-1.34, -1.34, -1.32, -1.31, -1.3, -1.3, -1.28, -1.26, -1.26,
-1.24, -1.22, -1.22, -1.21, -1.19, -1.19, -1.18, -1.15, -1.13,
-1.12, -1.12, -1.11, -1.11, -1.1, -1.1, -1.09, -1.09, -1.09,
-1.09, -1.09, -1.08, -1.08, -1.08, -1.07, -1.07, -1.06, -1.05,
-1.04, -1.03, -1.03, -1.03, -1.02, -1.02, -1.01, -1.01, -1, -1,
-0.99, -0.99, -0.99, -0.99, -0.99, -0.99, -0.98, -0.98, -0.97,
-0.97, -0.96, -0.96, -0.96, -0.95, -0.95, -0.94, -0.94, -0.94,
-0.93, -0.93, -0.92, -0.92, -0.92, -0.91, -0.91, -0.91, -0.9,
-0.9, -0.9, -0.9, -0.89, -0.88, -0.88, -0.87, -0.86, -0.85, -0.85,
-0.85, -0.84, -0.84, -0.84, -0.83, -0.82, -0.81, -0.81, -0.81,
-0.81, -0.81, -0.81, -0.8, -0.79, -0.79, -0.79, -0.79, -0.78,
-0.78, -0.77, -0.76, -0.76, -0.76, -0.76, -0.75, -0.75, -0.74,
-0.73, -0.72, -0.71, -0.71, -0.71, -0.71, -0.7, -0.7, -0.7, -0.7,
-0.69, -0.69, -0.68, -0.68, -0.68, -0.67, -0.67, -0.67, -0.66,
-0.66, -0.66, -0.66, -0.65, -0.65, -0.65, -0.65, -0.65, -0.64,
-0.64, -0.64, -0.63, -0.63, -0.63, -0.63, -0.63, -0.63, -0.62,
-0.62, -0.61, -0.61, -0.61, -0.61, -0.6, -0.6, -0.6, -0.6, -0.6,
-0.6, -0.6, -0.58, -0.58, -0.58, -0.58, -0.58, -0.57, -0.57,
-0.57, -0.57, -0.57, -0.57, -0.56, -0.56, -0.56, -0.56, -0.56,
-0.55, -0.55, -0.55, -0.55, -0.55, -0.55, -0.55, -0.55, -0.55,
-0.54, -0.54, -0.53, -0.53, -0.53, -0.53, -0.53, -0.53, -0.52,
-0.52, -0.52, -0.52, -0.52, -0.51, -0.51, -0.51, -0.51, -0.51,
-0.51, -0.51, -0.5, -0.5, -0.5, -0.5, -0.5, -0.49, -0.49, -0.49,
-0.49, -0.49, -0.49, -0.48, -0.48, -0.48, -0.48, -0.48, -0.48,
-0.48, -0.48, -0.48, -0.47, -0.47, -0.47, -0.47, -0.47, -0.47,
-0.46, -0.46, -0.46, -0.46, -0.45, -0.45, -0.45, -0.45, -0.45,
-0.45, -0.45, -0.44, -0.44, -0.44, -0.44, -0.44, -0.44, -0.44,
-0.44, -0.44, -0.43, -0.43, -0.43, -0.43, -0.43, -0.43, -0.43,
-0.43, -0.42, -0.42, -0.42, -0.42, -0.42, -0.42, -0.42, -0.42,
-0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41,
-0.4, -0.4, -0.4, -0.4, -0.4, -0.4, -0.4, -0.4, -0.39, -0.39,
-0.39, -0.39, -0.39, -0.39, -0.39, -0.39, -0.38, -0.38, -0.38,
-0.38, -0.38, -0.38, -0.38, -0.38, -0.37, -0.37, -0.37, -0.37,
-0.37, -0.37, -0.37, -0.37, -0.36, -0.36, -0.36, -0.36, -0.36,
-0.36, -0.36, -0.36, -0.35, -0.35, -0.35, -0.35, -0.35, -0.35,
-0.35, -0.35, -0.34, -0.34, -0.34, -0.34, -0.34, -0.34, -0.34,
-0.34, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33,
-0.33, -0.33, -0.32, -0.32, -0.32, -0.32, -0.32, -0.32, -0.32,
-0.32, -0.32, -0.32, -0.31, -0.31, -0.31, -0.31, -0.31, -0.31,
-0.31, -0.3, -0.3, -0.3, -0.3, -0.3, -0.3, -0.3, -0.3, -0.3,
-0.3, -0.3, -0.3, -0.3, -0.3, -0.29, -0.29, -0.29, -0.29, -0.29,
-0.29, -0.29, -0.29, -0.29, -0.29, -0.29, -0.29, -0.29, -0.29,
-0.29, -0.29, -0.29, -0.28, -0.28, -0.28, -0.28, -0.28, -0.28,
-0.28, -0.28, -0.28, -0.28, -0.28, -0.28, -0.27, -0.27, -0.27,
-0.27, -0.27, -0.26, -0.26, -0.26, -0.26, -0.26, -0.26, -0.26,
-0.26, -0.26, -0.26, -0.26, -0.26, -0.25, -0.25, -0.25, -0.25,
-0.25, -0.25, -0.25, -0.25, -0.25, -0.25, -0.25, -0.25, -0.24,
-0.24, -0.24, -0.24, -0.24, -0.24, -0.24, -0.24, -0.24, -0.24,
-0.24, -0.24, -0.24, -0.24, -0.24, -0.24, -0.24, -0.24, -0.24,
-0.23, -0.23, -0.23, -0.23, -0.23, -0.23, -0.23, -0.23, -0.23,
-0.23, -0.22, -0.22, -0.22, -0.22, -0.22, -0.22, -0.22, -0.21,
-0.21, -0.21, -0.21, -0.21, -0.21, -0.21, -0.21, -0.21, -0.21,
-0.21, -0.2, -0.2, -0.2, -0.2, -0.2, -0.2, -0.2, -0.2, -0.2,
-0.2, -0.2, -0.2, -0.2, -0.2, -0.2, -0.19, -0.19, -0.19, -0.19,
-0.19, -0.19, -0.19, -0.19, -0.19, -0.19, -0.19, -0.19, -0.19,
-0.19, -0.19, -0.19, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18,
-0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18,
-0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.17, -0.17, -0.17,
-0.17, -0.17, -0.17, -0.17, -0.17, -0.17, -0.17, -0.17, -0.17,
-0.17, -0.17, -0.17, -0.17, -0.16, -0.16, -0.16, -0.16, -0.16,
-0.16, -0.16, -0.16, -0.16, -0.16, -0.16, -0.16, -0.15, -0.15,
-0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15,
-0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15,
-0.15, -0.15, -0.15, -0.14, -0.14, -0.14, -0.14, -0.14, -0.14,
-0.14, -0.14, -0.14, -0.14, -0.14, -0.14, -0.14, -0.14, -0.14,
-0.14, -0.14, -0.14, -0.14, -0.14, -0.13, -0.13, -0.13, -0.13,
-0.13, -0.13, -0.13, -0.13, -0.13, -0.13, -0.13, -0.13, -0.13,
-0.13, -0.13, -0.12, -0.12, -0.12, -0.12, -0.12, -0.12, -0.12,
-0.12, -0.12, -0.12, -0.12, -0.12, -0.12, -0.12, -0.12, -0.12,
-0.12, -0.12, -0.12, -0.12, -0.11, -0.11, -0.11, -0.11, -0.11,
-0.11, -0.11, -0.11, -0.11, -0.11, -0.11, -0.11, -0.11, -0.11,
-0.11, -0.11, -0.11, -0.11, -0.11, -0.11, -0.11, -0.11, -0.11,
-0.11, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1,
-0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1,
-0.1, -0.1, -0.1, -0.09, -0.09, -0.09, -0.09, -0.09, -0.09, -0.09,
-0.09, -0.09, -0.09, -0.09, -0.09, -0.09, -0.09, -0.09, -0.09,
-0.09, -0.09, -0.09, -0.09, -0.09, -0.09, -0.09, -0.08, -0.08,
-0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.08,
-0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.08,
-0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.08, -0.07,
-0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07,
-0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.07,
-0.07, -0.07, -0.07, -0.07, -0.07, -0.07, -0.06, -0.06, -0.06,
-0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06,
-0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06,
-0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06,
-0.06, -0.06, -0.06, -0.06, -0.06, -0.05, -0.05, -0.05, -0.05,
-0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05,
-0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05,
-0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.05,
-0.05, -0.05, -0.05, -0.05, -0.05, -0.05, -0.04, -0.04, -0.04,
-0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04,
-0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04,
-0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04,
-0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04,
-0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.04, -0.03,
-0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03,
-0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03,
-0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03,
-0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03, -0.03,
-0.03, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02,
-0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02,
-0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02,
-0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02,
-0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.02, -0.01,
-0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01,
-0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01,
-0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01, -0.01,
0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,
0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,
0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,
0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,
0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.02, 0.02, 0.02, 0.02, 0.02,
0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02,
0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02,
0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02,
0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02,
0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02,
0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02,
0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02,
0.02, 0.02, 0.02, 0.02, 0.02, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03,
0.03, 0.03, 0.03, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04,
0.04, 0.04, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06,
0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06,
0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06,
0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06,
0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06,
0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06,
0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06,
0.06, 0.06, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07,
0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.07, 0.08,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08,
0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.08, 0.09, 0.09, 0.09, 0.09,
0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09,
0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09,
0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09,
0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09,
0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09,
0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09,
0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09,
0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.09, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,
0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,
0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,
0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,
0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,
0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11,
0.11, 0.11, 0.11, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,
0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,
0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,
0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12,
0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.13, 0.13, 0.13, 0.13,
0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,
0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,
0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,
0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,
0.13, 0.13, 0.13, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14,
0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14,
0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.14,
0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.15, 0.15, 0.15, 0.15, 0.15,
0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15,
0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15,
0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15,
0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15,
0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16,
0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16,
0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16, 0.16,
0.16, 0.16, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17,
0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.17,
0.17, 0.17, 0.17, 0.17, 0.17, 0.17, 0.18, 0.18, 0.18, 0.18, 0.18,
0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18,
0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18,
0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19,
0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19,
0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19, 0.19,
0.19, 0.19, 0.19, 0.19, 0.19, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2,
0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2,
0.2, 0.2, 0.2, 0.2, 0.2, 0.21, 0.21, 0.21, 0.21, 0.21, 0.21,
0.21, 0.21, 0.21, 0.21, 0.21, 0.21, 0.21, 0.21, 0.21, 0.21, 0.21,
0.21, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22,
0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22,
0.22, 0.22, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23,
0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.23,
0.23, 0.23, 0.23, 0.23, 0.23, 0.23, 0.24, 0.24, 0.24, 0.24, 0.24,
0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24,
0.24, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.26,
0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26,
0.26, 0.26, 0.27, 0.27, 0.27, 0.27, 0.27, 0.27, 0.27, 0.27, 0.28,
0.28, 0.28, 0.28, 0.28, 0.28, 0.28, 0.29, 0.29, 0.29, 0.29, 0.29,
0.29, 0.29, 0.29, 0.29, 0.29, 0.29, 0.29, 0.3, 0.3, 0.3, 0.3,
0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.31, 0.31,
0.31, 0.31, 0.31, 0.31, 0.31, 0.31, 0.31, 0.31, 0.31, 0.32, 0.32,
0.32, 0.32, 0.32, 0.32, 0.32, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33,
0.33, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.35, 0.35,
0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.36, 0.36, 0.36, 0.36, 0.36,
0.36, 0.36, 0.36, 0.37, 0.37, 0.37, 0.37, 0.37, 0.37, 0.38, 0.38,
0.39, 0.39, 0.39, 0.39, 0.39, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.41,
0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.42, 0.42, 0.42, 0.42,
0.42, 0.42, 0.42, 0.42, 0.43, 0.43, 0.43, 0.43, 0.44, 0.44, 0.44,
0.44, 0.45, 0.45, 0.45, 0.45, 0.46, 0.46, 0.46, 0.47, 0.47, 0.47,
0.48, 0.48, 0.48, 0.48, 0.48, 0.49, 0.49, 0.49, 0.5, 0.51, 0.51,
0.51, 0.52, 0.52, 0.53, 0.53, 0.54, 0.55, 0.57, 0.57, 0.57, 0.58,
0.58, 0.58, 0.6, 0.6, 0.61, 0.62, 0.64, 0.65, 0.65, 0.67, 0.67,
0.67, 0.74, 0.76, 0.77, 0.83, 0.83, 0.83, 0.84, 0.89, 0.89, 0.89,
0.94, 0.95, 0.96, 0.96, 1, 1.07, 1.07, 1.12, 1.12, 1.26, 1.26,
1.26, 1.27, 1.43, 1.55, 1.59, 1.59, 2.01, 2.05, 2.4, 2.45, 2.52,
3.12, 4.38, 10.97, 10.97, 11.84, 14.57, 19.12, 52.07, 145.74,
145.74)

To remove outliers, I used the update_outliers  function (given below) which removes the negative and positive outliers using quantiles. However, the problem with this method is that it overdoes outlier fixing as can be seen in the image below (see the red circles).
update_outliers <- function(x, na.rm = TRUE, ...) {
  qnt <- quantile(x, probs=c(.05, .95), na.rm = na.rm, ...)
  H <- 1.5 * IQR(x, na.rm = na.rm)
  y <- x
  y[x < (qnt[1] )] <- qnt[1]
  y[x > (qnt[2] )] <- qnt[2]
  y
}

new_vec = update_outliers(vec)
hist(new_vec)

Question -
How can I fix the outliers so that outlier fixing is not overdone as above and the data gets normalized? I want a bell-shaped histogram (as shown by the blue line in the image below) without any spikes on both ends.
Most importantly, during normalization, the negative values should not turn positive and vice versa.
My approach might be totally wrong as I am trying to fit data to a model instead of the fitting model to the data. I am open to any ideas to solve this problem in a better way.
Comment: I had no trouble using the logarithm.  The idea is to create an auxiliary binary variable determined by the signs of your net margins along with the log of the size of the net margin.  This yields a pair of variables that ought to work nicely in a factor analysis. But whether this is suitable for your intended analysis depends on many aspects of that analysis; and there are plenty of other approaches to the problem.
Comment: The explicit purpose of the function is to replace values that are (according to the function) "too large" or "too small" with a fixed value. Since this is what the function does, It's hard to understand what the question could possibly mean -- don't use that function if it's not achieving your goal.
Comment: Instead of "removing the variable" you can remove the outlying observation, which loses less information, see my first comment. However robust approaches are usually better (unless there's evidence that the outlier is indeed wrong).
Comment: If you want to force the vector of observations to have a distribution close to normal, you can use inverse normal scores transformation. There are a few different varieties such as Elfving, Blom, van der Waerden, Tukey, and rankit methods. This will not preserve the sign of the original values as you request, and may not be meaningful for your purpose. With the caveat that I wrote the function, in R you can use, `library(rcompanion); vec2 = blom(vec); hist(vec2)`
Comment: There are all kinds of ways to deal with this, depending on what `vec` represents and how you conceive of its role in your analysis.  (it's a question of "feature engineering.") But do you really have to supply 4006 values to explain your problem??  Let's have a minimal reproducible example, please.
Comment: There seem to be very extreme outliers and some that are treated as outliers but aren't that extreme (and may not actually mislead your analysis). Are there good subject matter reasons to think that the very extreme ones must be wrong? Removing outliers is fine if there is a strong reason to believe these are actually wrong (or at least for some reason so systematically different from the others that they shouldn't be analysed together).
Comment: Outliers are usually appropriately dealt with using robust techniques, see https://www.stat.fi/isi99/proceedings/arkisto/varasto/filz0165.pdf , https://rdrr.io/cran/robustfa/man/FaCov.html
Comment: @Whuber - I have recreated the example. As part of factor analysis, I am trying to figure out the companies at risk of bankruptcy. The vector above shows the net margin of about 3000 companies. It is not uncommon for net margin to spike in a positive or negative direction due to asset sell-off or merger activity. Due to the extreme values in this vector, all the variance is explained by this variable in factor analysis/ feature engineering. I cannot use the log as many values are negative. I cannot remove the extreme values as it will be lost crucial information in data.
Answer: Techniques of Exploratory Data Analysis (EDA) can help with this feature engineering problem.  I want to emphasize how just a couple of well-chosen plots tell us, forcibly, how we ought to proceed.
The histogram (unavoidably) hides important details, so let's begin with an N-letter summary of the batch of $2930$ data found in the array vec:
         M      H      E     D       C       B       A      Z       Y     X      *
Upper 0.02  0.100  0.190  0.30   0.430   0.650    1.10    2.4    11.0    24    150
Mid   0.02 -0.095 -0.455 -2.15  -8.285 -29.175  -64.45 -298.8  -944.5 -3738  -4925
Lower 0.02 -0.290 -1.100 -4.60 -17.000 -59.000 -130.00 -600.0 -1900.0 -7500 -10000

These letter statistics M, H, E, etc, designate upper and lower $1/2,$ $1/4,$ $1/8,$ etc. quantiles.  (These letters started out as mnemonics: "M" = median, "H" = "hinge" (Tukey's term for the shoulders of a boxplot), "E" = "eighth," and thence ascending through the alphabet.) The final column "*" gives the extremes.  The middle row labeled "Mid" computes the values midway between corresponding letter statistics; for example, the E-mid is $-0.455 = (0.190 + -1.100)/2.$
A glance at the large, systematic decreases in the Mid row shows us how negatively skewed the data are.  (After all, in any symmetric batch of data the mid-values will all be approximately equal.)
The temptation is to transform the data, but how?  If all values were positive, a diagnostic plot would provide an indication.  This is a plot of the spreads (the distances between corresponding letter statistics) against the mid-values on logarithmic axes.  Often the points on this plot trend almost linearly and, if so, the slope of the trend indicates how to transform the data to make their distribution more nearly symmetric.
Although taking logarithms is impossible due to the negative mid values, the consistent signs of those mid-values suggest looking at their sizes (absolute values) alone.  (The initial value of $+0.02$ is essentially zero and oughtn't to be a problem.  Fortunately, none of the data values are exactly zero.)
Here is the resulting plot.

It is extraordinary: usually the points do not line up so nicely, but here the linearity is almost perfect.  When data are positive and the slope is $p,$ a Box-Cox transformation of power $1-p$ is indicated.  Because $1-p = 1-0.95 = 0.05$ is essentially $0,$ and the Box-Cox transformation of power $0$ is the logarithm,

the data tell us we should be expressing them in terms of the logarithms of their absolute values.

Because taking the absolute value loses one bit of information -- the signs of the data -- we ought to retain the signs as a separate variable in the analysis.  Although there's no guarantee this will be effective, it's worth a try.

(Red is positive and blue is negative.)
The histograms show the positive and negative parts of the data have similar distributional shapes but different scales and locations.  For some analyses it might help to standardize the logs of the positive and negative parts separately to make them more comparable; but for a factor analysis or PCA the differing spreads and locations of the two parts of the data might help reveal the patterns or behaviors the analysis is looking to discover.
Reference: John Tukey (1977), EDA.  Addison-Wesley.

Appendix: R code for N-letter summaries
# Compute the letter statistics for `vec`.
q <- (1/2)^seq_len(floor(log2(length(vec)))-1)
stats <- c(min(vec), quantile(vec, c(rev(q), 1 - q[-1])), max(vec))

# Display them along with the mid-letter statistics.
k <- length(q) + 1
N.letter <- signif(rbind(stats[-seq_len(k-1)], rev(stats[seq_len(k)])), 2)
tletters <- c("M", "H", rev(LETTERS[1:5]), rev(LETTERS[-(1:8)]))[seq_along(q)]
colnames(N.letter) <- c(tletters, "*")
N.letter <- rbind(Upper = N.letter[1,], Mid = colMeans(N.letter), Lower = N.letter[2,])
(N.letter)

Comment: Probably.  But I found it easier and faster just to compute it directly rather than hunt down a package.  I'll add the code to this answer.  As you can see, it's just a couple of lines of (simple) code.  I have included additional code to format and print the results nicely.
Comment: @COOL Thanks!  My eye slipped and read the `E` column, so I'll just change "H" to "E" :-).
Comment: Thanks, whuber, is there a package in R to see N-letter summary?
Comment: There is a small typo: The H-mid is: $-0.095=(0.100+-0.290)/2$.
Answer: If you want to force the vector of observations to have a distribution close to normal, you can use inverse normal scores transformation.  There are a few different varieties such as Elfving, Blom, van der Waerden, Tukey, and rankit methods.
I don't know that this transformation will be meaningful for your purpose.
And this will not preserve the sign of the original values as you request.
With the caveat that I wrote the function, in R you can use,
library(rcompanion)

vec2 = blom(vec)

hist(vec2)

If it's necessary to preserve the sign of the original data, it may be possible to combine this approach with the creation of a second dichotomous variable which captures the sign of the original data, as suggested in a comment by @whuber, in which a log transformation was used.
So, perhaps, with this approach:
vecAbs = abs(vec)

vecSign = sign(vec)

vecNormAbs = blom(vecAbs)

hist(vecNormAbs)

qqnorm(vecNormAbs)
qqline(vecNormAbs, col="red")

table(vecSign)


Is there a way to add bulk media upload in the modal dialog when using ckeditor and entity embed?

Question: I was a heavy D7 developer and I skipped 8. Now I'm trying to build some sites in 9. Just wrapping my head around what's in core and contrib to get what I need. I was wondering what methods people are using (if any) for the possibility of doing bulk media uploads in the modal dialog in ckeditor using entity embed?
Answer: Gotta love the downvotes for a basic question. I sure missed you, Drupal community.
I'll answer my own question then.
https://www.drupal.org/project/file_browser

This module provides a default Entity Browser that lets you browse and select your files in a nice-looking, mobile-ready Masonry based interface, and upload files using the Dropzonejs module.


How Scala compiler deals with potential multiple assignments of values

Question: val-variables in Scala should have the following properties, ensured during compilation, not later in runtime:

the immutable variable can not be used (a in "read") before being assigned to (bound).
the immutable variable can not be assigned again after being assigned once.

According to tutorials and docs it is not required to assign the val immediately at the declaration point as long as type is specified.

http://www.tutorialspoint.com/scala/scala_variables.htm
http://www.scala-lang.org/files/archive/spec/2.11/04-basic-declarations-and-definitions.html#value-declarations-and-definitions

But this seems to create a loophole
def fn1(x: Int, y: Int): Int = {
  val const2 : Int

  const2 = 0
  if (x < 10) const2 = x
  if (y > 10) const2 = y

  const2
}

def fn2(x: Int, y: Int): Int = {
  val const2 : Int
  var i: Int

  for( i <- x to y ){
    const2 = 0
  }

  const2
}

In these both examples it seems impossible to the compiler to predict whether the assignment would be singular or not. So the compiler does not have standing to prohibit this code from being compiled, but it equally does not have grounds to warrant the singular-assignment nature of val-variables in every execution path possible at runtime.
Whatever compiler would do, compile the code or throw an error instead, it might end on the wrong side. So what should it do, specifications-wise ?
PS. a minor question with documentation: the chapter 4.1 has says
PatDef       ::=  Pattern2 {',' Pattern2}
Why is it "Pattern2" repeated and having the same numeric index?
Should it perhaps be merely Pattern {',' Pattern} instead or perhaps Pattern1 {',' Pattern2} ?
Comment: The given examples will not compile in Scala.
Comment: Pattern2 is defined in paragraph 8.1
Answer: This is illegal:
val const2 : Int
const2 = 0

vals cannot be reassigned after declaration, period.
Comment: @Arioch'The You can only have undefined declared members in a class but the thing is that the compiler will then force you to declare the class as abstract.
Comment: "Assignment outside of the declaration" isn't described in chapter 4 because, well, it isn't a declaration or a definition. It's defined in 6.15 and assignment to a value _isn't_ defined, so it isn't legal.
Comment: If you add in class membership you can declare undefined members. But even then I don't think we can create a scenario as provided by OP.
Comment: @SarveshKumarSingh You can declare them, but you cannot reassign them after declaration.
Comment: but what would be the value of `const2` without the assignment which is done in the second line? Can you quote specs that assignment outside of the declaration is prohibited even once ?
Comment: @SarveshKumarSingh makes sense. But this seems to be missing from official Scala specifications, isn't it ?
Comment: Guess this question is for scala development team... Does they have dedicated documentation writers maillist/forum, or do specs questions belong to general devel ?


What is frequency in time series in general and in my examples?

Question:
I have 2 years day-wise data of stock price.
What frequency should I take in this case for next 1 year day-wise prediction?

I have one day minute-wise data.
What frequency should I take for next day forecast minute-wise?

Actually I want to know what is the frequency w.r.t. time series and prediction?

I have given you a scenario :
I have 2 years day-wise data of stock price. What frequency should I take in this case for next 1 year day-wise prediction?
I.e., I want to convert my raw data of stock price for last two years (daily basis) and I want to convert this into a time series for an ARIMA model. I want to know what value for the frequency argument I should give inside ts() of the R software, and how it is decided.
Is it clear now?
Comment: What are you mean say "frequency"? Timeframe? 1 hour, 1 day, 1 week, 1 month?
Comment: yes, you need to clarify
Comment: 0
down vote
accept

I have given tou a scenario : I have 2 years day wise data of stock price.what frequency I should take in this case for next 1 year day wise prediction. ie i want to convert my raw data of stock price for last two years(daily basis) and I want to convert this into a time series for ARIMA model.I want to know what value for frequency argument I should give inside ts() of R s/w. And how it is decided . Is it clear now?
Answer: I assume that you have raised this question in context of frequency argument while modeling the time series using some tool, say R.
The interpretation of frequency for time series packages is generally 'the number of observations in a series if you consider the natural time interval of measurement'. For example, if you measure value of some variable once in a month, and you have data for multiple years, you can use value of 12 for frequency.
But things get tricky where there could be multiple levels of seasonality. For example, if you measure number of visitors to a web page every hour, there will be seasonality by hour as well as by day.
Bottom line is, very hard to tell you one single number purely based on information that you have given. You can study Rob J. Hyndman's blog post "Seasonal periods" for more details.
Comment: Yes, This is related to Time series in R.
Answer: In most time series analysis, there are two frequencies of interest. One is the sampling frequency $f_s.$ This is defined as how often you take a sample: once a year, once a day, one a minute, once every nanosecond, etc. The other frequency of importance is the frequency of whatever the phenomenon is that you're trying to capture. This could be extremely high frequency, on the order of GHz, for radio frequency investigations, or it could be more on the order of Hz for temperature-based phenomena. Let us call this phenomenon frequency $f_p.$ Now the Nyquist criterion says that you must sample at least twice the frequency of your phenomenon: $f_s>2f_p.$ However, in practice, I recommend $10$ times the frequency: $f_s=10f_p.$ You will generally get better results that way - much less likely to get aliasing, for example.
In summary:

Ask yourself how fast the phenomenon you want to capture is occurring. This is the frequency $f_p.$
Set your sampling frequency equal to $f_s=10f_p.$

In terms of your example, the frequency you need to enter into your R code is undoubtedly $f_s,$ but hopefully this explanation will show you how to come up with that frequency.
Answer: I also struggle with this very same definition.
This is what I understand from all the info pick around different sources.
The frequency is the number of observation in which you notice the next batch of the very same number of observation might interpret as next season(tipical phenomena picked up in the series will repeating over)
When you plot a series set to freq=10, you will notice the x-axis division contains the same number of observation as the value of the param freq.
Though you have to be able to visually tell what is the sazonality of your ts in order set the freq properly


How many solutions does the equation $x_1 + x_2 + x_3 = 14$ have, where $x_1$ , $x_2$ , $x_3$ are non-negative integers.

Question: I actually got this part and I got $16$ choose $2$, which would be $120$. The part I didn't get which wouldn't fit into the title was in how many of these solutions is $x_1 \geq 1$, $x_2 \geq 2$,and $x_3 \geq 3$? I'm not very good at combinatorics so I don't really know. I think the way to approach it would be saying how many solutions where $x < 1 +$ solutions where $x < 2 +$ solutions where $x < 3$ and subtract that from $120$, but I don't know how to do that.
Answer: Your solution to determining how many solutions the equation $$x_1 + x_2 + x_3 = 14 \tag{1}$$ has in the nonnegative integers is correct.  To determine how many solutions equation 1 if $x_1 \geq 1$, $x_2 \geq 2$, and $x_3 \geq 3$, let
\begin{align*}
y_1 & = x_1 - 1\\
y_2 & = x_2 - 2\\
y_3 & = x_3 - 3
\end{align*}
Then $y_1, y_2, y_3$ are nonnegative integers.  Substituting $y_1 + 1$ for $x_1$, $y_2 + 2$ for $x_2$, and $y_3 + 3$ for $x_3$ in equation 1 yields
\begin{align*}
y_1 + 1 + y_2 + 2 + y_3 + 3 & = 14\\
y_1 + y_2 + y_3 & = 8
\end{align*}
which is an equation in the nonnegative integers with $$\binom{8 + 2}{2} = \binom{10}{2} = 45$$ solutions.
Answer: This is pretty easy to calculate through Wolfram Alpha: Here is an example of an input that will solve this for you. The answer provided is not entirely true though, because of your constraints. We must exclude the solution $12+1+1$, which does not have $x_2 \geq 2$. We thus subtract $1$ from the provided result of 16 to get a final answer of $\color{red}{15}$. For clarification I have provided a list of the solutions here. If you want further info check out this page, although the topic of integer partitions is fairly complicated. If you have further questions I can try to help point you in the right direction, although I am not the best source of info on this topic; if you desire to learn more I recommend creating a new question specifically geared towards this.
$$
11 + 2 + 1 = 14\\
10 + 3 + 1 = 14\\
10 + 2 + 2 = 14\\
9 + 4 + 1 = 14\\
9 + 3 + 2 = 14\\
8 + 5 + 1 = 14\\
8 + 4 + 2 = 14\\
8 + 3 + 3 = 14\\
7 + 6 + 1 = 14\\
7 + 5 + 2 = 14\\
7 + 4 + 3 = 14\\
6 + 6 + 2 = 14\\
6 + 5 + 3 = 14\\
6 + 4 + 4 = 14\\
5 + 5 + 4 = 14$$
Note: In the event you also desire for the condition $x_1 \neq x_2 \neq x_3$ to hold it appears we get $10$ solutions