Ctrl + Alt + F1 blank screen in IBM server model x3650

Question: I have 3 IBM sever, model x3650. I have installed the Debian squeeze OS. After successful OS installation , if I press Ctrl+Alt+F1 I am getting blank screen only. But If I gives username and password it is accepting. After successful login, I have created the file. Then I have pressed Ctrl+Alt +F7 it gives GUI mode. There I am able to see the file which I created in "Ctrl + Alt + F1" mode.
I wants to know , why I am not able to see the screen in Ctrl+Alt+F1. I have installed same OS in same model, 3 servers. All the three servers I am facing the same problem.
How to resolve this issue?
Answer:
Did you try to boot to text only mode ? It is usually called "recovery mode" in Grub.
Check if you use framebuffer and try to disable it if possible (good link about it: http://kb.digium.com/articles/FAQ/How-to-disable-the-Linux-frame-buffer-if-it-s-causing-problems?retURL=%2Fapex%2FknowledgeProduct&popup=false)

sorry, can't post comments, quite new to this service


How do I add a clearing DIV to the bottom of a region?

Question: In the eternal mission to care about Internet Explorer, I have a template region which needs a clearing <div<, since I think that ":after" and "overflow:hidden" tricks don't work so well in IE. (I'm currently not able to test this as I'm on a Mac without a virtual machine.)
Is there any region preprocess trick, or anything equally clean, in order of adding a clearing
? I'd prefer not to use Javascript, or add an entire block for this purpose, if it is possible.
Answer: I would find a common class for your region(s), and add in the clearfix rules.  With kosher HTML and CSS, I don't recall the last time this didn't work in IE for me.
Answer: Drupal already has built in clearfix classes you can use. For Drupal 7, use clearfix. For Drupal 6, I believe it is clear-block.
Comment: Both of those are slightly outdated versions.  The link in my answer has the most recent incarnation.


Shared pointer initializer list constructor and changes to it's type constructor

Question: Consider the following snippet:
#include <memory>
#include <typeinfo>
#include <iostream>

class Widget {
};

int main() {
    auto shared_ptr_to_widget = std::shared_ptr<Widget>({});
    std::cout << "type of shared_ptr_to_widget: " << typeid(shared_ptr_to_widget).name() << std::endl;
    auto maybe_a_widget = *shared_ptr_to_widget;
    std::cout << "type of maybe_a_widget: " << typeid(maybe_a_widget).name() << std::endl;
}

This will output:
> type of shared_ptr_to_widget: St10shared_ptrI6WidgetE
> type of maybe_a_widget: 6Widget

However, if I replace the Widget class with:
class Widget {
public:
    Widget(): a{1}{}
    int a;
};

Then it seg faults at the following line:
auto maybe_a_widget = *shared_ptr_to_widget;

I understand if I actually wanted to make a shared pointer to an instance of an object I should use
std::make_shared<Widget>()

and this would actually call the constructor of Widget and everything would be fine and dandy. But I'd really like to understand what is going on here and why the behaviour changes based on the constructor of the Widget class.
I've tried looking at the constructors for shared_ptr http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr but I get a bit lost. I imagine it's my lack of understanding in what is actually happening when using an empty initializer list as a parameter to shared_ptr<>().
Answer: Your code has undefined behaviour, since *shared_ptr_to_widget dereferences a null pointer, since you only default-constructed shared_ptr_to_widget, which results in an empty shared pointer that doesn't own anything.
At the point where the program execution has undefined behaviour, the C++ standard imposes no constraints on the behaviour of a conforming implementation, so anything can happen. You are observing a particular instance of "anything".
To create a pointer that owns a widget, say either
auto shared_ptr_to_widget = std::shared_ptr<Widget>(new Widget);  // bad

or
auto shared_ptr_to_widget = std::make_shared<Widget>();  // good

Comment: How does the compiler make it past that stage in the first implementation of Widget? It should be a null pointer to to a class of type Widget in both scenarios?
Comment: @BrockHargreaves: I don't know, ask your compiler (i.e. look at the machine code)! There's generally very little value in debating the particulars of undefined behaviour. Anything can happen, and which flavour of "anything" you're seeing is basically irrelevant. If pressed I'd say that because the original widget is trival and empty, no code need to be generated to initialize it (all values of the type are equal), and so the absence of a value went unnoticed.
Comment: Yeah, it's no surprise that if you also output the use count of the shared pointer it is zero. I wish it would seg fault in both scenarios though. Thanks for your answer.
Comment: When you say "you only default-constructed `shared_ptr_to_widget`", do  you mean that (1) in `auto shared_ptr_to_widget = std::shared_ptr({});` this is a direct initialization calling the constructor explicitly with 1 parameter, which is an empty list, (2) then the empty list `{}` is a value initialization which triggered a default initialization?


using syslog-ng to parse snmptrapd - not keeping up

Question: (centos 7.x)
I have syslog-ng setup to parse snmptrapd messages so I can format them for later digestion. The issue is that syslog-ng only outputs the n-1 message. IE if there are 10 lines in snmptrapd.log syslog-ng only outputs 9 lines. If I send a new message to snmptrapd (message #11) then syslog-ng will output the 10th message.
syslog-ng.conf:
@version:3.27
@include "scl.conf"
log {
  source {
    snmptrap(filename("/var/log/snmptrapd.log"));
  };
  destination {
    file("/var/log/syslog-ng.log");
  };
};

snmptrapd.conf:
authCommunity log,execute,net public
authCommunity log,execute,net localtrap
format2 %.4y-%.2m-%.2l %.2h:%.2j:%.2k %B [%b]:\n%v\n
outputOption s

I've tried adding an additional newline to the end of format2 but it doesn't help. (snmptrapd.log does get the additional line though)
Answer: Currently, the snmptrap() source is implemented as a file source that parses the output of snmptrapd. snmptrapd logs are multi-line, the end of the given message is detected based on the prefix of the upcoming message, hence the unexpected behavior. These are ugly implementation details (limitations) of this plugin, it might eventually be replaced with a proper SNMP trap source.
As a workaround, you can set multi-line-timeout(10) to process the last message with a 10-second delay.


Finding the derivative with functions inside, such as $g(x) = \dfrac{3x-1}{f(x)}$

Question: With a question such as:
$$g(x) = \dfrac{3x-1}{f(x)}$$
How does one approach finding the derivative, could the Chain Rule be used?
The book, gives the answer as:
$g'(x) =\dfrac {3f(x)-(3x+1)f'(x) }{ (f(x))^2}$
Though I don't understand how to get to it.
Comment: Yeah. That seems pretty fine.
Comment: Sorry I meant to ask, how do you find the solution.
Comment: What do you need to find exactly? Solution to what?
Comment: How to find the derivative of g(x), for example, how to use the Chain Rule to get the solution. Edit: cleared up the post
Answer: You have $g(x)=\dfrac{3x-1}{f(x)}$, treat $3x-1=p(x)$, just another function.
Now the derivative of $\dfrac{p(x)}{f(x)}= \dfrac{p'(x)f(x)-f'(x)p(x)}{(f(x))^2}$ which is nothing but $g'(x)$. And yeah, this is Quotient rule as Michalis says.
Comment: Just a small addition: The rule is called quotient rule: http://en.wikipedia.org/wiki/Quotient_rule
It follows from the product and chain rule.
Answer: is not a CHAIN RULE is just the derivative of a quotient
$$ \frac{d}{dx}\frac{f(x)}{g(x)}= \frac{f'(x)g(x)-g'(x)f(x)}{g(x)^{2}}$$


Text mining software (beyond R)

Question: I am looking for software for teaching text mining to business students. Unfortunately, I cannot consider programming languages like R. Does anyone have experience with other text mining software? Can you recommend it? (or not!)
Ideally, software that is easy to learn for non-technical people, not overly expensive (not necessarily free), which can be used to convey the concepts of text mining clearly (rather than getting bogged down in software details).
Thanks!
Comment: @Macro: I am looking for software suggestions that are based on personal experience, and ideally experience teaching with it in a non-technical context such a business schools.
Comment: OK. I don't have personal experience with WordSmith but a consulting group (affiliated with a university) I used to work for taught a text mining workshop to non-statisticians that used it. Many of the workshop participants were from the business school.
Comment: I've seen a flyer for a text mining workshop that used something called WordSmith: http://www.lexically.net/wordsmith/
Comment: SAS also offers a text mining solution which is pretty good and user friendly. http://www.sas.com/en_us/software/analytics/text-miner.html
Answer: NLTK is free and reasonably easy to use, though it does require installing Python.  It comes with a wide range of text data sets.  There's an O'Reilly book for it, which is a help for students.
WEKA is general machine learning software with a nice interface.  There's some text classification datasets for it, though not the range of text mining datasets there is for NLTK. There's a book for WEKA too.
Comment: (+1) Thanks for providing links and reasons for your recommendations.  Welcome to our community!
Answer: Take a look at Rapidminer. Good documentation and a good community where people can discuss various questions. Works both on Mac and Windows.
http://rapid-i.com
Comment: You can search for RapidMiner text mining examples at MyExperiment:
http://www.myexperiment.org/workflows
Answer: DMelt is a free software package for computation, visualization and data mining. It is designed to work with large data ("big data") and perform statistical analysis and data mining. It is similar to R, but is integrated with a number of programming languages (such as Python)
Comment: And text mining?

Text mining software (beyond R)


Monotonous function or monotonic function

Question: I am from a non-English speaking country. Should we say monotonous function or monotonic function?
Comment: *Monotonic*, definitely. *Monotone* is also fine. *Monotonous* in everyday usage means *boring*.
Comment: So I guess nobody will be interested in monotonous functions. ;-)
Comment: In Italian the difference is even worse. The difference is between the correct [*monotòne*](http://www.treccani.it/vocabolario/monotono_res-91131e7b-0026-11de-9d89-0016357eee51/) and [*monòtone*](http://www.treccani.it/vocabolario/monotono/).  (0 letters difference, just the accent).
Comment: Just for completeness, see: http://math.stackexchange.com/questions/365717/is-monotonous-ever-used-as-a-synonym-for-monotonic-in-math Apparently, the difference between monotonous and monotonic in some languages is minimal, and we see it often misused as "monotonous" here.
Answer: "Monotonic" or "monotone", but not "monotonous" (boring).
Answer: That would be monotonic function. Monotonic is always used in relation to the function you are talking about.
http://mathworld.wolfram.com/MonotonicFunction.html
Monotonic describes something this is unchanged or altered, such as the function in maths whereas Monotonous describes something lacking in variety and is usually used in reference to tone.
Comment: "Monotone" is also acceptable (though not mentioned in the question).
Answer: monotonic  for sure is to be used.  Monotonic functions are those functions which are either increasing or decreasing. They are such that for each specific value of  x   there is a unique  y(value of function) which does not repeat for any other x.


How to programmatically get list of users and groups that have access to a file or folder in SharePoint

Question: I am trying to find a way to get the list of AD users and AD Groups that have access to a folder or file that has broken inheritance.  I don't need to know how to find the inheritance broken, I have gotten that part but I am having issues finding each user or group that has access.  I do not want to see what users are within the AD group, I just want to see the name of the group that is accessing the folder.  The use case behind this is that we do not want secured folders shared to single users.  All of this must be controlled by AD groups only (site owners do not have access to add users to a secure folder).  Also need to find out if there are any files within the folder that do not inherit from the folder and are also shared to individual users instead of AD groups (hope this makes sense).   Here is what I have so far and it works to a point, but for some reason it is returning users that have access to the site elsewhere and also users who have limited access that I have to clean up later.
Here's the code I have written so far that sort of works.  It takes in the item object of the file or folder and a reference to a string. It scans the access and then builds a list of users separated by semicolon and returns true if one of the spuser objects is a user and not a group:
<code>/// <summary>
    /// Provides list of users\groups that have access to a List Item.
    /// </summary>
    /// <param name="spListItem">Item to check access of</param>
    /// <returns>semi colon delimited list of users\groups with access in a referenced list and boolean value indicating if a direct user exists</returns>
    public bool GetListItemUserAccess(SPListItem spListItem, ref string accountsWithAccess)
    {
        //string accountsWithAccess = string.Empty;
        bool IsFirstIteration = true;
        bool domainUserExits = false;
        SPRoleAssignmentCollection spItemRoles = spListItem.RoleAssignments;
        SPRoleDefinitionCollection rolesInWeb = spListItem.Web.RoleDefinitions;

        foreach(SPRoleAssignment spRole in spItemRoles)
        {

            SPPrincipal spPrincipal = spRole.Member;

            //cast as SPGroup or SPUser to determine if is a SPGroup or User
            if((spPrincipal as SPGroup) != null)
            {
                SPGroup spGroup = spPrincipal as SPGroup;
                SPUserCollection usersInGroup = spGroup.Users;

                //report on each user in group
                foreach(SPUser spUser in usersInGroup)
                {
                    //check to see if it is a user group
                    if(!spUser.IsDomainGroup)
                    {
                        domainUserExits = true;
                    }

                    //add to list for report.
                    if(IsFirstIteration)
                    {
                        IsFirstIteration = false;
                    }
                    else
                    {
                        accountsWithAccess += ";";
                    }

                    //depending on the account type sometimes the Login name has the credentials and sometimes it has
                    //a UID
                    if (spUser.LoginName.ToLower().Contains("<company name>"))
                    {
                        accountsWithAccess += this.ParseUserIDFromClaim(spUser.LoginName);
                    }
                    else
                    {
                        accountsWithAccess += this.ParseUserIDFromClaim(spUser.Name);
                    }
                }
            }
            else if((spPrincipal as SPUser) != null)
            {
                //check to see if the user has limited access only (we don't report on this as this occurs when user has access to something in site)
                  if(!spListItem.DoesUserHavePermissions(spPrincipal as SPUser, SPBasePermissions.ViewListItems))
                {
                    continue;
                }

                //check to see if it is a user group
                if (!(spPrincipal as SPUser).IsDomainGroup)
                {
                    domainUserExits = true;
                }

                //add to list for report.
                if(IsFirstIteration)
                {
                    IsFirstIteration = false;
                }
                else
                {
                    accountsWithAccess += ";";
                }

                //depending on the account type sometimes the Login name has the credentials and sometimes it has
                //a UID
                if (spPrincipal.LoginName.ToLower().Contains("<company name>"))
                {
                    accountsWithAccess += this.ParseUserIDFromClaim(spPrincipal.LoginName);
                }
                else
                {
                    accountsWithAccess += this.ParseUserIDFromClaim(spPrincipal.Name);
                }
            }
        }
        return domainUserExits;
    }
</code>
Comment: Could you clarify a bit more, not sure what piece of the puzzle your missing. This code is a real mess as well, likely why there's no answers as it takes a long time to read and is overly nested. Would be worth having a developer refactor this.
Comment: Yah, I know the code is a mess at the moment.  I am still debugging the issue with it and I haven't had a chance to refactor it yet.  However, the issue I am having is that it is returning users that have access to the site, but not directly to the list item itself.  For example, I have instances where users with limited Access to the site are showing up in the RoleAssignments.  Everything I have seen so far indicates that while I am currently messy at it, I am on the right track for getting the data, so not sure why the extra accounts are coming through.
Answer: So the problem is that the code is returning both the users or groups that have access to the folder, but it is also returning back other users that have limited access to the item because they have access elsewhere within the site.
I finally corrected the issue by inserting the following code:
<code>if (spRole.RoleDefinitionBindings.Count > 1 || !spRole.RoleDefinitionBindings.Xml.ToString().Contains("Limited Access"))

{
  //Process accounts
}
</code>
What this is doing is if the user has more than one roles bound to them for the list item or the one they have is not Limited Access, it will process the account.  Otherwise, it is one of these "phantom accesses" that don't actually have direct access granted to the list item


Definition of sort Seq

Question: I would like to know what is the definition of sort Seq. I couldn't find its definition in the Z3 SMT 2.0 Guide. I realized Seq is already defined because I tried to define a sort named Seq. Are there some assertions associated to Seq?
Thanks!!
Maxi
Answer: Yes, Seq, RegEx (regular expressions) and FP (floating point) are "reserved" in Z3 4.0. They were not implemented yet, but they will be available in future releases. For example, Z3 will have builtin functions such as: seq-last, seq-concat, seq-length and many others. In Z3 4.0, these sorts and functions are just "stubs", and behave like uninterpreted sorts and functions. That is why we don't have any documentations for them.

Definition of sort Seq


How much larger is the $\sigma$-algebra than the algebra in Caratheodory extension?

Question: Given a 'measure' $\lambda$ on an algebra $\mathcal{A}$ of sets, Caratheodory gives a way to extend this $\lambda$ to a $\sigma$-algebra.
The idea is we define an outer measure (on all subsets) $\lambda^*$ by \begin{equation}\lambda^*(E)=\operatorname{inf} \Sigma\lambda(A_j),\end{equation}
where the $\operatorname{inf}$ is taken over all countable coverings of $E$ using sets in $\mathcal{A}$. Then one shows that the collection of subsets satisfying the Caratheodory condition \begin{equation}\lambda^*(E)=\lambda^*(E\cap A)+\lambda^*(E\backslash A)\end{equation} for all $E$ forms a $\sigma$-algebra, say $\mathcal{A}^*$, and $\lambda^*$ restricted to this $\mathcal{A}^*$ is actually a measure.
So my question is, how much larger is this $\mathcal{A}^*$ than $\mathcal{A}$? We know $\mathcal{A}^*$ contains $\sigma(\mathcal{A})$, the $\sigma$-algebra generated by $\mathcal{A}$, and it contains all the null sets. But can it be even larger than this?
In case of the Lebesgue measure, we start with the algebra of all 'boxes' then ended up of the Lebesgue measurable sets, which are in turn union of sets from $\sigma$(boxes) and null sets. So the difference of $\mathcal{A}^*$ and $\sigma(\mathcal{A})$ is exactly the null sets.
But can $\mathcal{A}^*$ be significantly larger than $\sigma(\mathcal{A})$?
Thanks!
Answer: Let $\Omega$ be an uncountable set and $\cal A$ the finite-cofinite field on $\Omega$ (all sets which are either finite or their complement is finite)
and $\lambda:{\cal A}\to[0,+\infty]$ counting measure.
Then $\lambda^*$ is counting measure and hence countably additive on all subsets of
$\Omega$ which implies that ${\cal A}^*$ is the full power set of $\Omega$.
But $\sigma({\cal A})$ is the countable-cocountable sigma field on $\Omega$ which is significantly smaller than the power set of $\Omega$.
Answer: Systematic Approach:

(Comment for questions!)


How to omit 0 in a whole number Date string

Question: I have successfully changed the format of a date string from yyyy-MM-dd to MM/dd. Now the problem is that if the month and day values are less than 10 each, the format should be for example 2/7 and not 02/07. How do I do this?
Here's my code:
    public static String cahngeFormat(String dateTime) {
        Date date = null;
        String str = dateTime;
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = formatter.parse(str);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.HOUR, 2);
            formatter = new SimpleDateFormat("MM/dd");
            str = formatter.format(calendar.getTime());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

Comment: have you solved your issue or not?
Answer: Change the format from "MM/dd" to "M/d" to allow single-digit output instead.
formatter = new SimpleDateFormat("M/d");

Comment: I was looking if there were other solutions, turned out this is similar to what I'm doing now. So I'll check this for the solution. Thanks.
Answer: DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(System.currentTimeMillis());
                    String timer = formatter.format(calendar.getTime());
                    formatter.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
                    txtTimerCount.setText(formatter.format(timePassed));

i hope this is useful to you.


Java: using properties with N values for 1 key

Question: Good morning, i'm making a program for backup.
In the config file i need specify N source directories and theyr destination directories, like this:
source="source dir", "destination drive1", "destination drive2"
source="source dir2", "destination drive", "destination drive2"

but in properties i can have only one value for a key, so i use different keys for source1, source2 etc.
there is a workaround for this?
ps what is the correct way to split the above string
"source dir", "destination drive1", "destination drive2"
if i split with " it's easy, but if i have something like
"i feel ""good"" because i'm a java programmer", "i feel "very bad" because i'm a java programmer"

i can't use string.split("""") because the " in "good" will split the string.
thank you very much
Comment: u can have HashMap>..
Answer: For splitting by " symbol :
String[] split = s.split("\"");

And if you want to have " sign in String you need to wtite \" instead ".
Answer: You could save it to a JSON file if you want. A full example to save and read in JSON.Simple Example – Read And Write JSON.
In another way, you need escape the double quotes on save. See https://stackoverflow.com/a/10452463/870248
Answer: I see three solutions.
Many Keys, One Value

source1a="source"
source1b="destination one"
source1c="destination two"
source2a="source"
source2b="destination one"
source2c="destination three"

One Key, One Value

source1=source,destination one,destination two
source2=source,destination one,destination two

For this, use String.split(",") to parse the values.
XML
Because properties are so 20th century.
<configills>
  <blam hoot="source">
    <destination value="destination one"/>
    <destination value="destination two"/>
  </blam>
  <blam hoot="source2">
    <destination value="destination one"/>
    <destination value="destination two"/>
  </blam>
</configills>

Comment: If I was doing a simple xml design; SAX seems fine.  For something more complicated check out JAXB.  Also, Spring has great JAXB support (and Castor and JiBX as well as others).


Line breaks with theme settings textarea

Question: I'm using the following to get a form field in the theme settings page
<code>function theme_form_system_theme_settings_alter(&$form, $form_state) {
   $form['foo_example'] = array(
   '#type'          => 'textarea',
   '#title'         => t('Widget'),
   '#default_value' => theme_get_setting('foo_example'),
   '#description'   => t("Place this text in the widget spot on your site."),
 );
}
</code>
The problem is when I output the result in my theme file with this:
<code>$foo_example = theme_get_setting('foo_example');
print render($foo_example);
</code>
It doesn't respect the line break and puts it all in one p tag. I'd like it to respect the line break and put each line in a p tag if possible.
Answer: Try to use "text_format" type.
<code> $form['foo_example'] = array(
   '#type'          => 'text_format',
   '#title'         => t('Widget'),
   '#default_value' => theme_get_setting('foo_example'),
   '#description'   => t("Place this text in the widget spot on your site."),
   '#format' => null, //I think "null" saves the default text format of your website. If you want to see your changes you must put a dynamic value.
 );
}
</code>
NOTA BENE: the values saved by this type of textarea, is an array with "value" and "format" keys:
<code>$var_saved = array(
'value'=> 'something',
'format' => 'full_html', //could be filtered_html, plain_text or any custom text format you've created.
);

//in your field definition
'#default_value' => $var_saved['value'],
'#format' => $var_saved['format'],
</code>
I didn't test it for your case, but choosing the right format, will normally output the text with respect of the rules chosen for that format type.
If I understood well your problem...


Fix error on postfix (Build to smtp server)

Question: I setup postfix as
command_directory = /usr/local/sbin
config_directory = /usr/local/etc/postfix
daemon_directory = /usr/local/libexec/postfix
data_directory = /var/db/postfix
debug_peer_level = 2
html_directory = /usr/local/share/doc/postfix
inet_interfaces = all
mail_owner = postfix
mailq_path = /usr/local/bin/mailq
manpage_directory = /usr/local/man
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain,
mydomain = abc.com.au
myhostname = cdb.au
myorigin = $mydomain
newaliases_path = /usr/local/bin/newaliases
queue_directory = /var/spool/postfix
readme_directory = /usr/local/share/doc/postfix
sample_directory = /usr/local/etc/postfix
sendmail_path = /usr/local/sbin/sendmail
setgid_group = maildrop
unknown_local_recipient_reject_code = 550

Then , i add user to system. When sent mail on microsoft outlook,I get error
THis is log in /var/log/maillog.

hostname aaaaa verification failed: hostname nor servname provided, or
  not known Nov  1 16:59:47 cdb postfix/smtpd[14405]: connect from
  unknown[22.214.171.124]
Comment: Try to refrain from telling people to "Help me." We're not paid support technicians.
Comment: Please include the output of `postconf -n` and relevant mail logs, at minimum showing the path of an entire message through the postfix system.
Answer: This is no error. This is a notification.
It tells you that your DNS resolution is broken for your hostname "aaaa". Either you have no PTR for IP 22.214.171.124 or the PTR of 126.96.36.199 does not match the hostname "aaaa". Fix it and the notification will go away.
Answer: You got mydomain and myhostname mixed up. It should be this:
mydomain = com.au
myhostname = abc.cdb.au


In D7, Where can you go to get a list of Access Arguments to be used with user_access()?

Question: Where can I find a list of Access Arguments to be used with user_access() ? I went to the permissions page and I'm not sure what I can copy and paste from there to be used as an argument for user_access(). So far I only know two: 'access dashboard' and 'access content'
I want to find out how can we get a list of these arguments.
Answer: You can get a list of arguments for the site by running this in the terminal:
drush sqlq "select distinct(permission) from role_permission \G"

Make sure you clear cache after making permission adjustments. As my changes weren't showing.
Comment: Correct me if I'm wrong, isn't the question what is the machine name for all possible permissions? Wouldn't this be better `drush sqlq "select distinct(permission) from role_permission \G"`
Comment: That's right. I'm not sure how to use distinct. That just shows all the UNIQUE results without duplicates right?
Comment: yes. Another way to write it would be `select distinct permission from role_permission`. In mysql `distinct()` returns all unique rows found in the resultset. it's a nice way to kill your performance. :D but here it's a great solution.


Axiom of choice for n-elements sets

Question: Assume that $C_n$ represents axiom of choice for sets that contain $n$ elements. Prove that if $n$ is a factor of $m$, we can conclude $C_n$ from $C_m$.
Here, I don't know what axiom of choice for n-elements set is. I know the first and second form of axiom of choice but I don't know how it is related to this problem and how to solve it.
Comment: I'd have written that as "... axiom of choice for families of sets that contain $n$ elements" for clarity. The alternative interpretation, "... axiom of choice for families that contain $n$ sets" is not as intriguing since choosing among a finite number of sets does not require any special axiom, but follows from induction on $n$.
Answer: The Axiom of Choice is

Given a set $X$ consisting of non-empty sets, there is a function $f: X\to\bigcup X$ such that $f(x)\in x$ for all $x\in X$.

Where would it make sense to change the axiom to consider only sets of size $n$? I'm no mind reader, so I cannot say for absolute certain what the problem author meant. But I would be very surprised if $C_n$ was anything other than this:

Given a set $X_n$ consisting of sets of size $n$, there is a function $f:X_n\to\bigcup X_n$ such that $f(x)\in x$ for all $x\in X_n$.

As for how to solve the problem (assuming this is what is meant), assume $n$ is a factor of $m$, and assume $C_m$. Take a set $X_n$ consisting of sets of size $n$. Now we want to apply $C_m$ on some set $X_m$ comprising sets of size $m$. How can we make sets of size $m$ if what we have are sets of size $n$? Products seem like the obvious choice. And so we apply $C_m$ to $$X_m=\left\{x\times\{1,2,\ldots,\frac mn\}\mid x\in X_n\right\}$$If we take the resulting function $X_m\mapsto \bigcup X_m$, it is not very difficult to construct the choice function $X_n\to \bigcup X_n$ that we want from that, by considering the composition
$$
X_n\to X_m\to\bigcup X_m\to\bigcup X_n
$$
where the first map takes $x$ to $x\times \{1,2,\ldots,\frac mn\}$, and the last map is projection onto the first component.
Comment: In particular, restricting the cardinality of $X$ itself just yields special cases of finite choice, which is provable in ZF.
Comment: @mudri That would be the only other option that even makes semantic sense, and it would not make for a good exercise. Besides, I don't think there is any natural way to show $C_m\implies C_n$ from $n\mid m$ in that case.

Axiom of choice for n-elements sets


Ocultar seta de navegação - Ionic

Question: Boa Tarde
Estou com um problema e preciso saber como ocultar a setinha de voltar (navegação) em algumas paginas específicas, alguem tem alguma solução.
Desde já obrigado
Comment: Como você está navegando entre as páginas?
Answer: acho que existem duas forma de ocultar o botão de back no Ionic uma delas é utilizando NavController quando você quiser ir para uma página sem back button utilize:
<code>this.navCtrl.setRoot(IrparaPaginaSemBackButton);
</code>
Outra forma é propio html da página tipo:
<code>   <ion-navbar hideBackButton>
    <ion-title>Perfil</ion-title>
</ion-navbar>
</code>
Onde a opção hideBackButton irá ocultar o botão automático do Ionic

Ocultar seta de navegação - Ionic


DIJKSTRA EM JAVA

Question: Olá.
Estou implementando um grafo e como algoritmo de menor caminho, estou utilizando o DIJKSTRA.
O grafo indica a relação de gêneros e seus respectivos subgêneros.
O grafo é direcional, não ponderado e possui vértices isolados.
Segue código abaixo:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class TratamentoArquivo {

    public static void main(String[] args) throws IOException {
        String fileName = "C:\\Users\\MATEUS\\Documents\\R\\dados\\generosFinal.csv"; //LOCAL ONDE ESTÁ O ARQUIVO
        BufferedReader in = new BufferedReader(new FileReader(fileName));
        StringBuffer sb = new StringBuffer((int) new File(fileName).length());

        String linha = in.readLine();

        while (linha != null) {
            sb.append(linha + "\n");
            linha = in.readLine();
        }

        in.close();
        String text = sb.toString();
        ArrayList<String> generos = new ArrayList<String>();

        int n = 1228;

        String lines[] = text.split("\n");

        for (int i = 0; i < n; i++) {
            lines[i] = lines[i].replace("{", "");
            lines[i] = lines[i].replace("}", "");

            String temp[] = lines[i].split(";");
            String current = temp[0];
            generos.add(temp[0]);
            lines[i] = lines[i].replace(temp[0], generos.indexOf(current) + "");

            if (temp[1].contains(",")) {
                String temp2[] = temp[1].split(",");
                for (int j = 0; j < temp2.length; j++) {

                    if (!generos.contains(temp2[j])) {
                        generos.add(temp2[j]);
                    }

                    lines[i] = lines[i].replace(temp2[j], generos.indexOf(temp2[j]) + "");
                }
            } else {
                if (!generos.contains(temp[1]) && !temp[1].equals("NULL")) {
                    generos.add(temp[1]);
                    lines[i] = lines[i].replace(temp[1], generos.indexOf(temp[1]) + "");
                } else if (!temp[1].equals("NULL")) {
                    lines[i] = lines[i].replace(temp[1], generos.indexOf(temp[1]) + "");
                }
            }
        }

        System.out.println("Total: " + generos.size());
        int adj[][] = new int[generos.size()][generos.size()];
        for (int i = 0; i < n; i++) {
            System.out.println(lines[i]);
        }

        for (int i = 0; i < n; i++) {
            String temp[] = lines[i].split(";");

            if (temp[1].contains(",")) {
                String temp2[] = temp[1].split(",");
                for (int j = 0; j < temp2.length; j++) {
                    adj[Integer.parseInt(temp[0])][Integer.parseInt(temp2[j])] = 1;

                }
            } else {
                if (!temp[1].equals("NULL")) {
                    adj[Integer.parseInt(temp[0])][Integer.parseInt(temp[1])] = 1;
                }
            }
        }

        //Inicializando o Dijkstra
        //Tentativa 2 DIJKSTRA
        int v = adj.length;
        boolean visitados[] = new boolean[v];
        int distancias[] = new int[v];
        distancias[0] = 0;

        for (int i = 1; i < v; i++) {
            distancias[i] = Integer.MAX_VALUE;

        }

        for (int i = 0; i < v - 1; i++) {
            //Encontrando vertice com menor distância
            int verticeMinimo = encontrarVerticeMinimo(distancias, visitados);
            //System.out.println(verticeMinimo);
            visitados[verticeMinimo] = true;
            //Explorando Vizinhos
            for (int j = 0; j < v; j++) {
                if ((distancias[j] > (distancias[verticeMinimo] + adj[verticeMinimo][j])) && adj[verticeMinimo][j] == 1) {
                    distancias[j] = adj[verticeMinimo][j] + distancias[verticeMinimo];
                }
            }

        }

        //Impressão
        for (int i = 0; i < v; i++) {
            System.out.println(i + " " + distancias[i]);
        }

    }

    public static int encontrarVerticeMinimo(int distancias[], boolean visitados[]) {

        int verticeMinimo = -1;
        for (int i = 0; i < distancias.length; i++) {
            if (!visitados[i] && (verticeMinimo == -1 || distancias[i] < distancias[verticeMinimo])) {
                verticeMinimo = i;
            }
        }
        return verticeMinimo;
    }
}

Apesar de ter seguido vários tutorias e estudado o algoritmo, o vetor de distâncias está sendo alimentado apenas com resultados infinitos (com excessão do primeiro vértice).
Fiz diversas modificações no código com o objetivo de solucionar esse problema, a única coisa que foi alterada no resultado é que, para os vértices não isolados (ou seja, que possuem um subgênero), o valor "infinito" foi negativado.
Link do arquivo com as informações de gêneros e subgêneros.
Answer: Consegui resolver meu problema utilizando uma forma "diferente" do algoritmo dijkstra, com a seguinte função:
public static int[] dijkstra2(int adj[][], int origem) {

        int tamanho = adj.length;
        boolean visitados[] = new boolean[tamanho];
        int distancias[] = new int[tamanho];

        for (int i = 0; i < tamanho; i++) {
            distancias[i] = Integer.MAX_VALUE;
        }
        distancias[origem] = 0;

        for (int i = 0; i < tamanho - 1; i++) {
            int menorVertice = encontrarVerticeMinimo(distancias, visitados);
            visitados[menorVertice] = true;
            for (int j = 0; j < tamanho; j++) {
                if (adj[menorVertice][j] != 0 && !visitados[j] && distancias[menorVertice] != Integer.MAX_VALUE) {
                    int novaDistancia = distancias[menorVertice] + adj[menorVertice][j];
                    if (novaDistancia < distancias[j]) {
                        distancias[j] = novaDistancia;
                    }
                }
            }
        }

        return distancias;
    }

O método chamado encontrarMenorVertice é o seguinte:
public static int encontrarVerticeMinimo(int distancias[], boolean visitados[]) {

        int verticeMinimo = -1;
        for (int i = 0; i < distancias.length; i++) {
            if (!visitados[i] && (verticeMinimo == -1 || distancias[i] < distancias[verticeMinimo])) {
                verticeMinimo = i;
            }
        }
        return verticeMinimo;
    }

A solução foi utilizar cada vértice como origem em cada execução do algoritmo.

DIJKSTRA EM JAVA


What is the minimum value of $x$ for which this "reciprocal pronic" series, $\sum_{n=1}^\infty \frac{1}{n^x(n+1)^x}$, converges?

Question: If we define a function as:
$$P(x)=\sum_{n=1}^\infty \frac{1}{n^x(n+1)^x}$$
For $x=1$, we have a standard telescoping series that sums to $1$.  For $x=2$, the series sums to $\frac{\pi^2}{3}-3$.  For $x=3$, the series sums to $10-\pi^2$, ... and so on.

My question is, what is the minimum value for which x allows this "Reciprocal Pronic" series to converge.  I think it is something above $x>0.5$ but I cannot prove this.
Comment: Think integral test. Your numerator is a constant,  so your denominator should be of degree more than 1. (Why?)
Comment: Note the binomial series $(1+n^{-1})^{-s}=\sum_{k\ge 0} {-s \choose k} n^{-k}$ means $$\sum_{n\ge 1} n^{-s}(n+1)^{-s} = \sum_{n\ge 1} n^{-2s}\sum_{k\ge 0} {-s \choose k} n^{-k}=\sum_{k\ge 0} {-s \choose k} \sum_{n\ge 1}n^{-2s-k}=\sum_{k\ge 0} {-s \choose k} \zeta(2s+k)$$ which gives the analytic continuation to the whole complex plane, with simple poles at $s=(1-2m)/2,m\ge 0$.
Comment: I am aware that convergence is possible for values 0.5<x<1.
Comment: Very clever - thanks
Answer: Hint Use inequalities to write bounds for the summand that involve simpler expressions: $$\frac{1}{(n + 1)^{2x}} \leq \frac{1}{n^x (n + 1)^x} \leq \frac{1}{n^{2x}}.$$
It follows from doing so that there is no minimal $x$ for which the series converges, but one can instead for the infimum of the set of $x$ for which it does.
Comment: That is helpful but not conclusive.  This only places an upper limit which I suspect is the correct limit but I want to go further.
Comment: @user714524 The inequalities bound the summand both above and below---essentially by $p$-series, which suggests using the $p$-series Test and the Comparison Test.
Comment: Actually it places both an upper and lower limit


How can I predict the next number give prior history of known sequences?

Question: I have a simple problem where I want to present a user with a list of possible choices for the next step in a workflow process. The issue is as follows: A particular user of a software program uses certain workflows, by which I mean a certain set of commands in sequence. Each command has a unique numeric value. The numeric values in any one sequence have no relation to each other. That is, this isn't an attempt to detect the next number in some formulaic sequence.
As the user is using commands to perform tasks, I want to predict which command, or commands, the user is most likely to use next. I could build out a tree-like structure where each node is a command (numeric) identifier and walk the tree and present the next set of nodes at a branching node as a good guess. But I am looking for more of a mathematical approach.
Here's the easiest example. The user starts our program. The first command is almost always either a file open command or create a new file command.
Here's another example. The user starts our program and creates a new file. The user creates a shape and then executes a command to create a hole in the shape (this is a mechanical design/engineering application). After creating a hole the user is most likely to either run a thread command or a counter-bore command to modify/attribute the hole. I would like to capture the command sequence data over time and start presenting the user with a palette of command choices that changes dynamically. That is, I want an "intelligent toolbar" user interface that modifies itself as the user is working with the system.
What should I consider? For example, is this something a Markov chain can be used to do?
Comment: There is a huge literature in Computer Science on user interface design. Your users might be better served if you looked into that literature or asked your question on a Computer Science forum rather than on MSE. (If I was responding to your question on such a forum, I might strongly advise you to find out what your users want before presenting them with what you think they want: unpredictable context-sensitive behaviour in a user-interface can be massively distracting and give a big increase in the workload for the user.)
Comment: Users don't often know what they want until we show it to them. I've been programming for 35 years and am very familiar with UX. We have plenty of tips, prompts and suggestion interface elements as the user works through their design. This includes MRU and MFU command UI elements (context menus) and I want to extend this by adding a bit of AI that can use the telemetric data we collect as we observe how a user is using the product to predict what the user will do next based on previous history. The aim is to improve the UX by reducing the number of clicks it takes to get to the next command.
Answer: You MIGHT be able to implement this with a Markov chain model. However, it is likely that aside from the obvious chance fluctuations, you will also need to consider more than one instruction back, which may make an effective model quite large.
Comment: +1. "quite large": not really, in my opinion. You can have a history of up to 3 or even 4, since the number of commands is going to be 'small' compared to other things Markov models are used for, like English text. Training the model might be hard, however.
Answer: This might be a good candidate for a Machine Learning approach:  constructing a decision tree to predict the next command based on the previous commands.
Comment: Besides Markov, I think at least other one approach to take is to build a graph and base decisions on an analysis of the graph. I'm guessing that web browser search key-ins use that approach - as you type a phrase, the controls drop a list of suggestions based on previous history of like searches. Google probably has one huge graph system. Thanks for the answers!


Finding a generator for $\mathbb{Z}_{2}\times \mathbb{Z}_{3}$

Question: I'm reading an example of how to find a generator of $\mathbb{Z}_{2}\times \mathbb{Z}_{3}$, which are written additively. The book then tries to see if (1,1) is a generator and says that since the operations are additive so is the direct product of $\mathbb{Z}_{2}\times \mathbb{Z}_{3}$.
the book then shows
(1,1)=(1,1)
2(1,1)=(1,1)+(1,1)=(0,2)
3(1,1)=(1,1)+(1,1)+(1,1)=(1,0)
4(1,1)=3(1,1)+(1,1)=(1,0)+(1,1)=(0,1)
and so on. My question is how is the above computation calculated? Thank you for your help.
Comment: In the first coordinate, numbers add like in $\mathbb{Z}/2 \mathbb{Z}$. In the second, they add like in $Z / 3Z$. That is the meaning of the direct product.
Answer: Look for example
$$4(1,1)=(4\pmod2,\,4\pmod3)=(0\pmod2,\,1\pmod 3)=(0,1)$$
where the rightmost last expression is just a short handed one that should be clear when each coordinate is taken the correspondent modulo.
Comment: thank you makes perfect sense


Bash: How do I create a variable containing a list of arguments with multi-word tokens?

Question: I want to create a variable which is essentially a list of arguments to pass to a command or function.  The pattern below with arg_string works well for foo, bar, and baz, but not for "multi word token", which I would like the command to see as a single argument.
#!/bin/bash
function func() {
  for arg in "$@"
  do
    echo ${arg}
  done
}

arg_string="foo bar baz \"multi word token\""
arg_string="foo bar baz multi\ word\ token"
arg_string="foo bar baz 'multi word token'"
func ${arg_string}

Here is the output:
foo
bar
baz
'multi
word
token'

When I want:
foo
bar
baz
multi word token

Answer: Just stick an eval before the function call:
 eval func ${arg_string}


Evaluation of Integral $\int_{0}^1 \frac{\arctan x }{1+x} dx$

Question: How do you compute $$\int_{0}^1 \frac{\arctan x }{1+x} dx$$
Comment: The answer is pi times ln2 over 8, no clue how they got that...
Comment: have you tried integration by part? Then you need to do $\int_0^1 \dfrac{\ln(1+x)}{1+x^2}dx$
Answer: Using integration by parts
$$\int_0^1 \frac{\arctan x}{1+x} dx  = \arctan(x) \ln(1+x)|_0^1 - \int_0^1 \frac{\ln (1+x)}{1+x^2}dx$$
The former part is $\displaystyle \frac{\pi}{
4} \ln 2 $ and the latter part is $\displaystyle \frac{\pi}{8} \ln  2$ which is answered here.
Comment: :notice :$\int_{0}^1 \frac{\arctan x }{1+x} dx$
Comment: woops!! sorry .. I'll fix it .. thank you!!
Comment: Denominator of the given integral is linear (typo?), but your explanation makes sense, that link did it !! ThanX
Comment: yeah i made typo earlier ... you are welcome :)
Answer: $$
\begin{align}
\int_0^1\frac{\arctan(x)}{1+x}\,\mathrm{d}x
&=\int_0^{\pi/4}\frac{\theta}{1+\tan(\theta)}\,\sec^2(\theta)\,\mathrm{d}\theta\tag{1}\\[6pt]
&=\int_0^{\pi/4}\frac{\theta\,\mathrm{d}\theta}{\cos(\theta)\,(\cos(\theta)+\sin(\theta))}\tag{2}\\[6pt]
&=\int_0^{\pi/4}\frac{(\frac\pi4-\theta)\,\mathrm{d}\theta}{\cos(\theta)\,(\cos(\theta)+\sin(\theta))}\tag{3}\\[6pt]
&=\frac\pi8\int_0^{\pi/4}\frac{\mathrm{d}\theta}{\cos(\theta)\,(\cos(\theta)+\sin(\theta))}\tag{4}\\[6pt]
&=\frac\pi8\int_0^{\pi/4}\frac{\sec^2(\theta)}{1+\tan(\theta)}\,\mathrm{d}\theta\tag{5}\\[6pt]
&=\frac\pi8\int_0^1\frac1{1+x}\mathrm{d}x\tag{6}\\[6pt]
&=\frac\pi8\Big[\log(1+x)\Big]_0^1\tag{7}\\[12pt]
&=\frac\pi8\log(2)\tag{8}
\end{align}
$$
$(1):$ $x=\tan(\theta)$
$(3):$ $\theta\mapsto\frac\pi4-\theta$
$(4):$ since $(2)=(3)$ we have $(3)=\frac{(2)+(3)}{2}$
$(6):$ $x=\tan(\theta)$


Como abrir um link em uma nova aba aspx

Question: Estou tentando abrir uma nova pagina em uma aba diferente, através aspx, eu consegui um código na internet que faz isso, porem, ele só funciona com clicks.
segue o código
LinkButton1.Attributes.Add("onclick", "window.open('../conheca-os-alimentos-aprovacao.aspx');return false;");

Alguém pode me ajudar!
Comment: Amigo, eu não manjo nada de asp.net, porem seguindo a lógica do que postou, tente fazer o seguinte:

LinkButton1.Attributes.Add("href", "http://google.com.br");
LinkButton1.Attributes.Add("target", "_blank");
Answer: Na página ".aspx", sbstitiua os itens que tem acrescentando o "_target", isto na página, como segue:
  <asp:LinkButton runat="Server" ....  target="_blank"></asp:LinkButton>

Comment: ???????????????
Answer: Faça como o Luiz Vichiatto indicou ou...
Adicione o seguinte código:
LinkButton1.Attributes.Add("target", "_blank");

Deve ficar assim:
LinkButton1.Attributes.Add("target", "_blank");
LinkButton1.Attributes.Add("onclick", "window.open('../conheca-os-alimentos-aprovacao.aspx');return false;");

Answer: Tente usar o código abaixo direto no LinkButton. Quando você especificou que só funciona com clicks, o que gostaria de fazer, então? Deseja que alguma regra de negócio interna da página abra uma nova aba? Poderia especificar melhor a pergunta?
Obs: Abrir nova aba ou nova janela sem a ação do usuário (sem o click) é considerado pop-up e bloqueado pelo navegador na maioria dos casos.
  <asp:LinkButton runat="server" Text="teste" ID="lnkTeste" OnClientClick="window.open('http://www.google.com');" target="_blank"></asp:LinkButton>

Answer: Tem duas maneiras práticas para abrir uma nova aba .aspx!

Utilizando um script dentro C#
Response.Write("");

Utilizando um atributo no elemento button
OnClientClick ="window.open('CAMINHO.aspx', '_blank'); return false;"/>"

Como abrir um link em uma nova aba aspx


Limit of $b_n$ when $b_n=\frac{a_n}{n}$ and $\lim\limits_{n\to\infty}(a_{n+1}-a_n)=l$

Question: I have the following problem.
I have to find the limit of $b_n = \frac{a_n}{n}$, where $\lim\limits_{n\to\infty}(a_{n+1}-a_n)=l$
My approach:
I express $a_n$ in terms of $b_n$, i.e.
$a_n=nb_n$ and $a_{n+1}=(n+1)b_n$
We look at the difference: $a_{n+1}-a_n=(n+1)b_{n+1}-nb_n$
Assuming that $b_n$ converges to a real number m, we see that:
$l=(n+1)m-nm$, from where I conclude that $m=l$.
What I'm left with is proving that $b_n$ is convergent which I'm not sure how to do.
Thanks in advance!
Comment: The problem is a direct corollary of Cesaro-Stolz Theorem
Comment: The answer section does not make sense. Take for instance $a_n = n$ so that $l = 1$, and $b_n = 1 \ne e$.
Comment: Still, Is my solution correct?
Comment: I've added an edit changing the question to proof verification type.
Comment: You still have to prove that $(b_n)_n$ is convergent.
Comment: the first line of your approach should say "[...] and $a_{n+1}=(n+1)b_{n+1}$".
Comment: Your solution has serious problems. The equation $l=(n+1)m-nm$ does not make sense here.
Answer: As @ParamanandSingh suggested, from Stolz–Cesàro theorem
$$a_{n+1}-a_n=\frac{a_{n+1}-a_n}{(n+1)-n} \rightarrow l, n \rightarrow \infty$$
where $\{n\}_{n \in \mathbb{N}}$ is monotone and divergent, then
$$\frac{a_n}{n} \rightarrow l, n \rightarrow \infty$$


Problemas com JSON no servidor

Question: Olá
Estou com problemas com o JSON quando subo ele pro servidor..
Exemplo de uns dos meus código que usam JSON:
        $("input[name=people]").keyup(function(){
            if($(this).val() != ''){
                $.ajax({
                    url: "<?php echo site_url('/StockController/searchPeople')?>",
                    type: "POST",
                    cache: false,
                    data: {name_people: $(this).val()},
                    success: function(data){
                        $('#loadPeople').html("");
                        var obj = JSON.parse(data);
                        if(obj.length>0){
                            try{
                                var items=[];
                                $.each(obj, function(i,val){
                                    items.push($("<option  id="+ val.id_people +">"+ val.name +"</option>"));
                                });
                                $('#loadPeople').append.apply($('#loadPeople'), items);
                            }catch(e) {
                                alert('Ocorreu algum erro ao carregar os Fornecedores!');
                            }
                        }else{
                            $('#loadPeople').html($('').text("Nenhum Fornecedor encontrado!"));
                        }
                    },
                    error: function(data){
                        alert("Ocorreu algum erro ao carregar os Fornecedores");
                    }
                });
            }else{
                $('#loadPeople').html(" ");
            }
        });

No servidor local ele roda tranquilo, mas quando subo pra um online o codigo para de funcionar, e retorna o seguinte erro no console:

Uncaught SyntaxError: Unexpected token  in JSON at position 0

Alguém sabe o que pode estar acontecendo?
Comment: você tem como postar o que sai no seu console.log() para o JSON que deseja manipular?
Comment: [{"id_product":"142","name_product":"Carregador de Celular Gen\u00e9rico","unit_price":"10.00"},{"id_product":"143","name_product":"Arroz Itatibaia","unit_price":"4.00"},{"id_product":"145","name_product":"Feij\u00e3o","unit_price":"10.99"},{"id_product":"146","name_product":"pao","unit_price":"12.00"}]
Comment: Este console.log() é do servidor ou do localhost?
Answer: Tente trocar de:
url: "<?php echo site_url('/StockController/searchPeople')?>",

para:
url: "<?php echo base_url('StockController/searchPeople')?>",

Se não funcionar poste o método searchPeople();
Answer: O problema do seu servidor pode ser uma restrição de acesso à saída JSON.
No php, você pode fazer isso para liberar a requisição:
header("Access-Control-Allow-Origin: *");

Embora a forma mais adequada e segura de fazer isso seja, passando somente domínios que possuem permissão válida para a requisição:
$request = $_SERVER['SERVER_NAME'];
if (in_array($request, array('siteA.com.br', 'siteB.com.br'))) {
    header("Access-Control-Allow-Origin: $request");
}

Problemas com JSON no servidor


How to get address from current location from setMyLocationEnabled(true);

Question: In my project I used Google Maps Activity and to get the user's current location I used setMyLocationEnabled(this); method to get the location. And when I tried to fetch the latitude and longitude from that location it throws a error says null object reference.
I looked for many videos in YouTube and examined many questions in stack overflow and blogs but I can't find the proper code to be done to do that. Some use deprecated methods and some go way beyond the topic.
So all I want is to do the reverse geo coding to get the address from my location and also add a marker at that point.
Help me guide what to do and how to obtain that I'm stuck with that from past 4 days.
Comment: Stacktrace just throws a messages like attempt to income Virtual method on a null object reference.
Comment: You should post the stacktrace.
Answer: Reverse Geocoding is what you are looking for. Geocoder class can be used
Look at this Android: Reverse geocoding - getFromLocation
It will give you idea of using reverse geocoding
Answer: You can use getFromLocation from Geocoder.
Sample code.
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
    List<Address> addressList = geocoder.getFromLocation(
            latitude, longitude, 1);
    if (addressList != null && addressList.size() > 0) {
        Address address = addressList.get(0);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
            sb.append(address.getAddressLine(i)).append("\n");
        }
        sb.append(address.getLocality()).append("\n");
        sb.append(address.getPostalCode()).append("\n");
        sb.append(address.getCountryName());
        String result = sb.toString();
    }
} catch (IOException e) {
    Log.e(TAG, "Unable connect to Geocoder", e);
}

Comment: Thanks for the help but the code hasn't worked it gives me a error saying null pointer exception.


Conflict with click and hover animation Jquery

Question: I have a little problem with my jQuery code.
Here is my code :
$("#bloc-search").click(function(){
        $(this).toggleClass("bloc-search-highlight");
        //var jObj = $( this );
});

if ( $("#formulaire-search").is(':visible')){

    $('.search').attr('src', '/img/search-blanc.png');

} else {

    $("#bloc-search").hover(
        function(){
           $('.search').attr('src', '/img/search-blanc.png');
        }, function(){
           $('.search').attr('src', '/img/search-blue.png');
    });

}

It works almost perfectly, but my problem is when my #formulaire-search is visible the hover function is still working and i don't know why because in my if i don't have the hover function.
I also tried with the hasClass instead of visible no way...
An idea ?
Thank you for your help ;-)
Answer: You could try this:
if ( $("#formulaire-search").is(':visible')){
  $("#bloc-search").unbind('mouseenter mouseleave');
  ... other stuff ...
} else {
  $("#bloc-search").bind('mouseenter mouseleave'); // to be sure
  ... other stuff ...
}

You might have to rebind it then when you need hover functionality
UPDATE
This works as it should - using mouseenter and mouseleave works well and can also work natively just as easy
if ( $("#formulaire-search").is(':visible')){

    $('.search').attr('src', '/img/search-blanc.png');

} else {

    // do what you want here - only works when #formulaire-search not visible
    $("#bloc-search").on('mouseenter', function(){
           $(this).addClass('goTeal');
    });

    $("#bloc-search").on('mouseleave', function(){
           $(this).removeClass('goTeal');
    });

}

Here's a fiddle to look at
Comment: Thank you for your answer but it still not working.  Even with your idea :

`if ( $("#formulaire-search").is(':visible')){
 $("#bloc-search").unbind('mouseenter mouseleave');
    $('.search').attr('src', '/img/search-blanc.png');
} else {
 $("#bloc-search").bind('mouseenter mouseleave');
    $("#bloc-search").hover(
        function(){
           $('.search').attr('src', '/img/search-blanc.png');
        }, function(){
           $('.search').attr('src', '/img/search-blue.png');
    });
}`
Comment: Hi Darren, i tried with your update (mouseenter, mouseleave) and it's still not working. I don't know why the mouseenter and the mouseleave are still active whereas the div is visible :-(
Comment: Did you look at the fiddle I made? that works as it should so if yours is not then I suspect something else is causing it to fail - are there ant console errors?
Comment: I checked your fiddle and on different computer and browser there is no animation. I have no errors in the console.


What is this vague accusation of RRD data loss about?

Question: I want to use CollectD to gather some statistics (about storage) and have Graphite display them nicely.  Apparently this can be done either by

having CollectD store the data as RRD files and pointing Graphite at
those, or
using a CollectD plugin to push the data to Graphite's Carbon API, which will store the data in a Whisper database (which is similar to RRD but not compatible).

I think I want to go with RRDs, but I found this statement in the Whisper docs that concerns me:

In many cases (depending on configuration) if an update is made to an
  RRD series but is not followed up by another update soon, the original
  update will be lost.

Hmmm.  That's a bit scary, but the accusation is so vague that I don't know what to make of it.  What is the configuration they are talking about, and the situation in which it causes data loss?
My situation is that the metrics data I am gathering will be available in chunks -- periodically I will go get the latest data and make as many entries into the database as there are new samples available.  So, for example, I might grab some data and update the database with the values from 3 minutes ago, 2 minutes ago, and 1 minute ago, one right after the other.  In fact, I might have dozens of new samples to put in the database at once.  Does using RRD this way have anything to do with the Whisper accusation?
NOTE: I do not need to back-fill data; I will always be adding newer data than what has already been stored.
Answer: One scenario I see this happening would be if you have an AVERAGE RRA setup, and have the xxf value set to a low percentage.  When the data is compressed over time, you could receive an unknown value and 'loose' all the data that was averaged.  If you are using a RRD for what it was designed for, and have it setup with the proper type and settings, I wouldn't think you will run into a problem.
I would recommend taking an in depth look at the RRD documentation found HERE to answer questions about how RRD's and RRA's handle the data, and the different storage techniques that are available to you.


$Y$ is a ( closed) proper subspace of a real NLS $X$ such that $dist (x,Y)=1$ for some $x \in X$ with $||x||=1$ ; is $Y$ finite dimensional?

Question: Let $Y$ be a finite dimensional proper subspace of a real NLS $X$ , we know that we can find $x\in X$ ( depending on $Y$) , such that $||x||=1$ and $dist (x,Y):=\{||x-y||:y\in Y\}=1$ . I would like to ask the converse ; i.e.,
let $Y$ be a proper subspace ( also assume $Y$ is closed if  necessary)  of a real NLS $X$ such that $\exists x \in X$ such that $||x||=1$ and $dist (x,Y)=1$ , then is $Y$ finite dimensional ?
Answer: No. What you want holds for every closed proper subspace of a Hilbert space.
Simply take any $x \in Y^\perp $ with $\|x\|=1$.


Focus engine tvOS

Question: I have searched on google and found a couple of example for tvOS focus engine. does this tvOS feature work on iPhone or iPad?
Can a user interact with touch instead of apple remote on iPhone or iPad?
Answer:
The tvOS focus engine only works for tvOS devices, like the Apple TV, and the feature does not work for iPhones or iPads.
Yes, the user interacts using touch on iPhone and iPad (iOS devices) instead of the Apple remote.

From the App Programming Guide for tvOS

On iOS devices, a user interacts directly with the touchscreen. On Apple TV, a remote is used to control the interface indirectly.

Focus engine tvOS


How can you get a Country and Western sound with just a guitar and vocal?

Question: A glimmer of a song idea I have feels like it might fit a C&W style. But I have no idea how that would be achieved and I'm not really a big C&W fan.
Is it a musical thing with the instruments, or a vocal melody thing, or both?
I'd be writing/playing just me and an acoustic guitar so no vocal harmonies, cow-bells, etc - just chords and a vocal.
Comment: Related question: [Country music elements](https://music.stackexchange.com/questions/30364/country-music-elements).
Answer: As a songwriter who writes Country songs and records the demos as a guitar/vocal, this question is right up my alley.
Country music is characterized by both the subject matter of the lyrics as well as the instrumentation, style of play, and vocal style.   Although modern country songs topping the country billboard charts today have incorporated many elements of pop and rock with both instrumentation and arrangements.
To add a little extra beyond the basic question - for the edification of other readers -
the most common instrumentation associated with more traditional country music is acoustic guitar, Fender Telecaster electric, pedal steel, drums and often a banjo or fiddle for the more blue grassy end of the country spectrum.
Chord progressions in traditional country are usually pretty simple with few if any augmented or diminished chords.  In fact there is a running joke among musicians in my area that all you need to play any country song is a G a C and a D chord (although sometimes I get fancy and through in an Em for good measure).
From a subject matter point of view, Country  seeks to speak to the hopes, dreams, triumphs  and tribulations of the common man in plain straightforward conversation like language that is easy to understand.  Country lyrics don't often contain deep metaphors with hidden meanings or clever plays on words.
But enough about country music in general.  Let's talk about your specific question.  So you have written some lyrics that fit within the permissible confines of what defines "Country music" and you have a chord progression and melody in mind.  Now you want to record a simple Guitar/Vocal demo and have it "sound country".
First I would recommend an acoustic guitar if there is only one guitar in your recording. If using electric - use as clean a signal as you can get.
To give your guitar playing more of a country feel, you can employ any of several techniques. I find that the easiest to use is a bass strum bass strum pattern with a simple bass walk or hammer-on between chords.  I call it an alternating bass pattern and play it with a pick. In it's basic form the strumming pattern is Bass down/up Bass down/up in 4/4 time.
If you want to get a little more complex and have the skills to pull it off, Travis Picking – a fingerpicking technique made popular by Merle Travis, will lend a country flavor to any guitar arrangement.  There is a great lesson here Travis Picking Lesson  that has examples with tab, standard notation and sound files that you can adjust the playback speed making the examples easy to learn regardless of your preferred  learning style. This is different than "Chicken Pickin" another country style that features many muted plucked notes (often using both pick and fingers) but Chicken Pickin won't work as well in a solo guitar arrangement with no other instrumentation.
As far as vocal style for country, to be completely convincing, you almost need a country accent.  If you don't have one, please don't try to fake one.  Real country folk might think you are making fun of them ;).
But you can countrify the vocals by adding a little twang here and drawl there.  Draw out some of the phrases and try scooping out some phrases by dipping the pitch of the sung note/s and raising it back up.  Don't try to sound too proper in your enunciation or diction.
You really should listen to some country music from singers like Garth Brooks, Allen Jackson, Merle Haggard, Keith Whitley, Dwight Yoakum, Tim McGraw, Hank Williams and Brad Paisley (just to name a few) -  to get a feel for the singing style.  You can find good examples on YouTube.
As you listen to some country – especially the older traditional country, you will sometimes hear what I call a country hiccup that sounds like you were singing a note and accidentally hit a turkey call and made a little yelp.  That's one technique you can try to throw in occasionally if you can get it down with practice.
Try to use some nasal accents every now and then to add more country flavor. To get in touch with your nasal voice, try holding your nose while singing and try to get the sound to come more through your nose than mouth.  If you connect well with the nasal voice you will feel your nose vibrating when you sing while pinching your nostrils shut.  In more technical terms this is more like singing through your facial mask.
This video of The Possum (George Jones)George Jones Bartender's Blues YouTube  is a good example of the country vocal sound with some nasal twang and vocal scoops.
Here is another video showing a guitar vocal with a distinct country flavor. Garth Brooks Cover YouTube
If trying to sound country just doesn't come natural to you and it sounds too contrived, and you insist on capturing your idea with true country authenticity, consider hiring a demo singer who sings country.  You can listen to them on line and many will actually collaborate via the internet where you can e-mail them the music and they add the vocals and send it back.  Here is an article about how to hire a demo singer for your country song. Hire a Country Demo Singer    The cost for this is fairly reasonable.
Listen to some examples of country singers and just do your best to emulate them.  If you want to record the guitar and vocal yourself just for fun, don't worry about who you might offend or if you sound authentic - and just have fun with it. You can always say it's just a spoof.  Good luck.
Answer: Scoop between two and three of any chord, both with your guitar and with your voice. Don't over do it, but it is the fundamental Country element. The rest should follow.
On the guitar, if you are playing a G chord, it is the hammer on you perform on the fifth string from the open A to the B. Transpose that relationship, and you are fine.
That scooping motion works for the vocals, too, let me emphasize: just don't overdo it. Listen to Buck Owens or Ernest Tubb. You will get the idea.
I have been asked to explain scooping. It is most commonly heard as a criticism of poor singing. It occurs when the singer is not sure of the note, and glissandos up to it from a note below.
But a fault in one context can be a shining feature in another. If Buck Owens had not scooped his singing, you would not know it was him, and he might have missed out on some million selling records.
Answer: Listen to others who play country and western. How could you do it any other way if you aren't familiar with the genre. Pick out an artist like Waylon Jennings, Willie Nelson, or Johnny Cash. Listen to there vocal technique and mock it. Copy the boom-chuck rhythm of the acoustic guitars. Again just copy what they do and eventually you will get a feel for it.


What exactly does $\frac{\mathrm{d}y}{\mathrm{d}x}$ calculate in implicit differentiation? (details given)

Question: Does it calculate the derivative of the given equation?
Because in implicit differentiation we don't have $y= equation$ so I don't know what we are differentiating using the $\frac{\mathrm{d}y}{\mathrm{d}x}$
Do we consider/assume the given equation lets say $x^2+y^2=36$ as $y$ when we say calculate $\frac{\mathrm{d}y}{\mathrm{d}x}$?
Does it mean we just have to differentiate the given equation and $\frac{\mathrm{d}y}{\mathrm{d}x}$ is its derivative or the gradient function?
This question might seem redundant but I swear nobody asks this question, its a really dumb thing that I don't know or can't seem to understand.
Comment: What's actually going on is: *by magic*, the abstract equation $x^2+y^2=36$ has a local solution, when $|x|\neq6$, $f$. $f$ is a *differentiable function* and it will be true that, for $x$ in the domain of $f$ (which maybe is quite small, who knows) we have $x^2+f(x)^2=36$. More can be said; for solutions $(x,y)$ to the equation that are nearby the initial condition, it must be the case that $y=f(x)$. So what we are doing is differentiating the *local parametrisation* of the solution set. Such a mysterious function $f$, or "$y(x)$" if you like, exists and that's what we are differentiating.
Comment: It's not a really dumb thing. Implicit differentiation is rarely explained correctly at pre-university level. One day maybe you'll study the implicit function theorem and hopefully what's going on will really, truly make sense. It didn't for me, until I studied the theorem and its proof
Comment: It will essentially calculate the usual derivative of $y$ with respect to $x$ (slopes of tangents to the curve), where **we view $y$ as a function of $x$** in the given curve. For example, if $x^2+y^2=36$, then implicit differentiation gives $2x+2y\frac{dy}{dx}=0\Rightarrow\frac{dy}{dx}=-\frac{x}{y}$. Now if you have a point on the curve, you can plug it into this to obtain the *slope of the tangent to the curve there*. For example at the point $(0,6)$, the slope of the tangent to the curve is $-\frac{0}{6}=0$, i.e. a horizontal tangent (which makes perfect sense if you graph this circle!).
Comment: In terms of an application that requires implicit differentiation, are you looking for the physical meaning of it?
Comment: nope, just what $\frac{d}{dx}$ (y) is in the equation $x^2+y^2=36$ is it its derivative? i am just confused because in explicit it is stated that y = something something so when dy/dx is used i know that it means to differentiate the equation but here i get confused as it is not stated *explicitly*
Comment: so it's a different imaginary function altogether?
Comment: In this case we can say quite explicitly, $f(x)=\sqrt{36-x^2}$ or $f(x)=-\sqrt{36-x^2}$. Most of the time though we cannot write down a clear formula for $f$. However, we can still prove it exists. But *because we don't know what $f$ really looks like*, we need to use *implicit* differentiation to study $f$ (rather than *explicit* differentiation, which is what you do to formulas by applying rules like $d/dx [ x^5 ] = 5x^4$)
Answer: An equation of the form $f(x,y)=0$ describes a set of points in the plane $\mathbb R^2.$ Usually (but not always) this set consists of some curves. At a point on such a curve, we can, unless the tangent is vertical, find a neighborhood in which there are no distinct points with the same value of $y$. The curve segment in that neighborhood is the graph of some function $y=g(x).$ What we calculate with implicit differentiation is the derivative of that function: $\frac{dy}{dx}=g'(x).$
Here's a quadrifolium, the solution to $(x^{2}+y^{2})^{3}=a^{2}(x^{2}-y^{2})^{2}.$ It isn't the graph of any function $x\mapsto y$ globally, but locally, for example inside the red circle, it can be written as $y=g(x).$ (We might not be able to find an explicit expression for $g(x)$ though.) That part of the graph is smooth and using implicit differentiation we can find $g'(x).$
Comment: I understand some part of this, thank you very much. Do you recommend looking into some materials or videos
 to understand it better? @md2perpe
Comment: @ATS. Unfortunately I don't have any specific recommendations. You can look around on YouTube. There are videos about _implicit differentiation_.
Answer: It's the same thing it always means, the slope of the tangent line to the curve that is the graph of the equation.
"Implicit" differentiation just has to do with how you differentiate the expressions. The meaning of the derivative is the same.
You need to be careful about how you say it -- you aren't taking the derivative of the equation, you're differentiating the expressions on each side of the equation.
For example, you can rewrite the equation $y=f(x)$ as $\frac{f(x)}{y}=1$ and use implicit differentiation to find $dy/dx$:
$$\require{cancel}\frac{f(x)}{y}=1$$ $$\frac{d}{dx}\Bigg(\frac{f(x)}{y}\Bigg) = \frac{d}{dx}\Bigg(1\Bigg)$$
$$\frac{y\cdot\frac{d}{dx}[f(x)] - f(x)\cdot\frac{d}{dx}[y]}{y^2} = 0$$
$$\frac{y\cdot f'(x) - f(x)\cdot\frac{dy}{dx}}{y^2}= 0$$
$$y\cdot f'(x) - f(x)\cdot\frac{dy}{dx}= 0$$
$$\frac{dy}{dx}= \frac{\cancel{y}\cdot f'(x)}{\cancel{f(x)}}=f'(x)$$
Comment: The derivative is always determined locally. In the case of implicit differentiation, you are differentiatiing an implicitly defined function. The meaning **is** the same. It is the slope of the tangent line.
Comment: "the meaning of the derivative is the same" - $y$ is not a given function, so, the meaning isn't really the same. We are secretly also saying "there is a local parametrisation of the pairs $(x,y)$ and .... and ... and *that's* the thing we're differentiating". So "$y$" has to be understood in a more subtle way, if you want to view it as a function.
Comment: so $dy/dx$ is an equation or fraction really that we get after implicitly differentiating an equation and we can know the slopes of the tangents formed at those points by putting in the value
Answer: Is just the slope of the tangent line. It's closely tied to the gradient.
Suppose $f(x,y)=0$, e.g. $f(x,y)=x^2+y^2 -R^2 =0$.
Then $\nabla f = 2x \hat{i} + 2y \hat{j}$
Let $d\vec{s} =dx \hat{i} + dy\hat{i}$
Then the chain rue tells us $df=\nabla f \cdot d\vec{s} =\frac{\partial f}{\partial x}dx + \frac{\partial f}{\partial y}dy =2xdx + 2ydy . $
And since $f\equiv 0, df\equiv 0. $
$2xdx + 2ydy =0 \implies \frac{dy}{dx}=\frac{-x}{y}$

You can see this is the slope in another way. Parameterize the curve.
Suppose we hae $x^2+y^2-9=0$.
Then we can let $x=3\cos  t . y= 3 \sin t$.
$\frac{dx}{dt}=-3\sin t=-y$
$\frac{dy}{dt}=3\cos t = x$
$\frac{dy}{dx}=\frac{dy/dt}{dx/dt}=\frac{x}{-y}=\frac{-x}{y}$
Here $t$ is just a parameter, you can think of it as time and then $x$ and $y$ give you position with respect to time, but what is the geometric meaning of $dx/dt$? Geometrically, not much, at least not directly, yet the ratio of y and  x velocity gives you the slope of the tangent line, a solidly geometric object.


Maverick Issue : While adding a subview on NSView

Question: I have a NSView(outlet - detailsView) , upon that a NSSplitView (outlet - detailsSpiltView) and there are two subviews in the split view and in those subview there are different scroll view and table view.
<code>NSView(detailsView)
|
NSSplitView(detailsSplitView)
|           |
NSView      NSView
|                 |
NSScrollView      NSScrollView
|                 |
NSTableView       NSTableVIew
</code>
On a certain condition I am adding a an error view on detailsView and on other conditions the table view would be populated:
The code for loading errorView is the following:
<code>[self.errorView setFrame:[self.detailsSplitView frame]];
[self.errorView setBackgroundColor:ERR_BG_COLOR];
[self.errorView setAlphaValue:0.85];
[self.detailsView addSubview:self.errorView];
</code>
Its working perfectly in Mountain Lion but in Maverick the errorView is getting loaded behind the table views.
I even tried to send the table views in back using code
<code>[tableView1 sendToBack];
[tableView2 sendToBack];
[self.detailsView addSubview:self.errorView positioned:NSWindowAbove relativeTo:self.detailsSplitView];
</code>
But still errorview is loading in the back of tableview.
Comment: Did you try my answer?
Answer: I added the following code beneath the addSubView method and it worked:
<code>--------
[self.detailsView addSubview:self.errorView];
[self.errorView setWantsLayer:YES];
</code>


Abusing the word "library"

Question: I see a lot of questions, both here on SO and elsewhere, about "maintaining
common libraries in a VCS".  That is, projects foo and bar both depend on
libbaz, and the questioner is wondering how they should import the source
for libbaz into the VCS for each project.
My question is: WTF?  If libbaz is a library, then foo doesn't need its
source code at all.  There are some libraries that are reasonably designed
to be used in this manner (eg gnulib), but for the most part foo and bar
ought to just link against the library.
I guess my thinking is: if you cut-and-paste source for a library into
your own source tree, then you obviously don't care about future updates
to the library.  If you care about updates, then just link against the
library and trust the library maintainers to maintain a stable API.
If you don't trust the API to remain stable, then you can't blindly
update your own copy of the source anyway, so what is gained?
To summarize the question: why would anyone want to maintain a copy of a
library in the source code for a project rather than just linking against
that library and requiring it as a dependency?
If the only answer is "don't want the dependency", then why not just
distribute a copy of the library along with your app, but keep them
totally separate?
Comment: Could you format this to be more readable?
Comment: Also, make a note that you're talking about languages such as C. In languages like PHP or Ruby it would make a lot of sense to have an external library be part of your project. Also, Git has the concept of "submodule" which helps a lot with this.
Comment: I just formatted the text and got 75%. But it's more readable now.
Comment: Do PHP and Ruby not allow modules to be imported like Perl and Python do?  Surely they have a mechanism for this sort of thing?
Comment: @William, there are possibilities, but all sorts of incompatibilities appear. And your library's users want something that works out of the box. And there are some other cases, when one library depends on "something" more recent, while another cannot work with that recent "something"? What should the user do at that point?
Answer: The use of vendor branches to control 3rd party dependencies is discussed in some depth in the Subversion book. As I understand it, the basic advantages are guaranteeing a stable API and uniformity of libraries for all developers, and the ability to control custom modifications in house in the same versioning system.
Comment: Forking the library means you forgo all future improvements.  Using a vendor branch means you keep your modifications while still getting more recent versions of the vendor code.  This can cause problems, but I don't know of a better way to maintain user mods on top of a changing library.
Comment: You can guarantee a stable API by not installing newer versions of the library.  If you want to do custom modifications, then you should fork the library.  Trying to manage dependencies with a VCS like this is strikes me as a bit insane.
Answer: On the project I'm working on right now, we've got the main code (which is in one Subversion project) and a host of assorted libraries from various places that are in their own Subversion modules.  The Visual Studio solution maintains separate projects for each of them and links them together at the end.  If we were working on Unix or similar OSs, we'd do the same thing.
The only downside I see is that I sometimes forget to update one of the libraries that changes more frequently, and my code doesn't compile until I notice that.  If we had the libraries in the same module, then we wouldn't have that problem.  (Not that I'd ever do it that way.  The gains in flexibility and the ability to use different libraries with different main projects are just too great.)
The API is a red herring here:  either it stays the same or it changes, and if it changed we'd have to update the main code either way.  So is the question of source vs. binary libraries (either we compile them with the main project, or we don't).

Abusing the word "library"


How to integrate Data Hub (POIs, Styles) with Android App using Here Maps SDK

Question: I'm currently using (Here maps freemium plan), integrated Here maps Android SDK (Premium Edition -version 3.18) with Android studio project.

Also created a Data Hub project at (https://studio.here.com/) with a layer that contains POIs data with customized points style.

What I'm trying to do is, integrating data from Data Hub with my Android project, so customized POIs will be visible on the map once it's loaded. I do know that adding a MapContainer can work as a map layer, then can hold multiple MapMarker objects, but I don't think this would be a wise move when working with huge amount of POIs and other Data.

So, it there a method to build a connection between Data Hub and Android project, to automatically sync data and styles?

Is this because of the freemium plan?

And if it's a plan limitation, where's the documentation for building such connection?

Since, the only thing I'm receiving once publishing Data Hub project is a viewer link.
Answer: You can use XYZ API to request your data on HERE Data Hub, download per tile or full data set or even search with location or attributes. You need to defile the caller in your app to call XYZ API, then convert them to MapObject and render them on the map.
Comment: Then the only way to add POIs is by sending API request then create native MapObjects on-top of the map in my Android project. And I can't create a connection between the map on Android and my Data hub data to automatically create ViewObject of type PROXY_OBJECT once the map is loaded. Is that true?
Thanks for your response!
Comment: If your data is point style, you can use MapMarker, instead of Proxy Object. HERE Data Hub provides API to load it by tile or bounding box. But you need to handle the logic of de-duplicating while panning and zooming the map.


(Android studio) How to get item position from strings.xml if I know the string?

Question: I have a list of strings in strings.xml
<resources>
<string name="app_name">XXXXXX MAPS</string>

<string-array name="Field">
    <item>
        AAAAA
    </item>
    <item>
        BBBBB
    </item>
    <item>
        CCCCC
    </item>
    <item>
        DDDDD
    </item>
    <item>
        EEEEE
    </item>
    <item>
        FFFFF
    </item>
    <item>
        GGGGG
    </item>

I have put this list in listview.
When I click the listview I will get the String ( for example String clicked = EEEEE)
How can I find the int position from that strings.xml using the information that I know the string that has been clicked? (for example if String EEEEE where clicked I would like to get Int stringclicked = 5)
I want to stress that I want to some way to get it using that list of strings that are in strings.xml. I cannot use something like
public void onItemClick(AdapterView<?> parent, final View view, int position, long id)

To get int position.
Comment: @Selvin ??? answered so many times where???
Comment: @selvin where? link please
Comment: You couldn't have put it in athe listView without adapter. Use the position you get from adapter. That lead to the position you desire
Comment: i get it know. It was a stupid question. i was just confused because i was using searcview that was filtering the listview and i was getting nowhere.
Comment: Please don't add things like "Answered" to your subject, instead **accept** the answer that was most helpful
Comment: @Mark Rotteveel Did not i accept the answer?? Sorry im new. And I put answered because i did not want more answers because this was not a good question and I cant delete it anymore
Comment: That is not how stack overflow works. People answer, you accept an answer, and other people may still answer (you can even decide to accept a newer, better answer instead). You should not delete questions just because you received an answer (your question and its answers are not just for you, but also for the larger community and future visitors), nor should you add meta-info like "answered".
Comment: @Mark Rotteveel Did I accept answer??? Yeah I know but the question has been answered manytimes so I do not want to people to use their time writing something again :)
Comment: Yes, you accepted, the point I am trying to make is that you should **only** accept, not add things like "answered".
Comment: @Mark Rotteveel I think i accepted the answer many hours ago so I did not get you message. And i thought adding answered would just help. Have a nice day:) bye!
Answer: Answering your question directly, if you have a string and want to obtain the position in the array in resources:
String[] stringArray = getResources().getStringArray(R.array.Field);

Obtain the position in the resources array:
 Arrays.asList(stringArray).indexOf(string)

Answer: If you have list of Strings, what I can see in the question. You can use indexOf method of list for getting position. For example:
    List<String> strings = new ArrayList<>();
    strings.add("aaa");
    strings.add("bbb");
    strings.add("ccc");
    strings.add("ddd");
    strings.add("eee");
    int position = strings.indexOf("ccc");

Answer: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

            try {
                //'position' refers to the 'int position' in the Override method
                Log.e("This is your position", position.toString());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });


Forma correta de checagem de NULL do Scala no Java

Question: Primeiramente, quero falar que sou totalmente leigo em Scala. Não sei quase nada além do básico da linguagem. Sabendo disso, vamos a minha dúvida.
Estou em um projeto onde há bibliotecas desenvolvidas em Scala. Essas bibliotecas foram empacotadas em JAR's e eu importo no projeto Java. Até aí tudo bem. Eu não tenho acesso aos fontes dessas bibliotecas em Scala.
O que acontece é que as vezes eu preciso comparar null. No Java isso é de uma forma e pelo jeito no Scala parece ser de outra forma.
Vamos a um exemplo prático para ilustrar meu problema. Vamos supor que minha lib em escala retorna um objeto Usuario:
Usuario user = usuarioService.getUsuario(usuarioID);
System.out.println(usuario.nome().get());
System.out.println(usuario.email().get());

No exemplo acima estou usando a lib feita em Scala e buscando informações de um Usuario. Tudo é objeto Scala, da lib em Scala.
Agora, eu quero verificar se o atributo nome, por exemplo é nulo ou não. Eu vi duas formas. Uma que acredito ser Java Way e outra Scala Way.
Java Way
final scala.Option<String> None = scala.Option.apply(null);
Usuario user = usuarioService.getUsuario(usuarioID);
if (!user.nome().equals(None)) {
    System.out.println(usuario.nome().get());
}

Scala Way
Usuario user = usuarioService.getUsuario(usuarioID);
if (user.nome().nonEmpty()) {
    System.out.println(usuario.nome().get());
}

Agora a pergunta, qual a melhor forma de fazer isso quando se está desenvolvendo em Java e usando libs feitas em Scala?
Answer: Java 8 traz uma uma nova API para evitar verbosidade e excessivo "checks" a null e por consequência, NPE indesejados através de métodos que indicam a falta de um possível valor de retorno.
Esse é o mesmo proposito do Scala.option.
No java 8 o nome da API é Optional.

Aplicando ao seu código teríamos :

Primeiramente alteramos o retorno de usuarioService.getUsuario.getUsuario adicionando o Optional.
public Optional<Usuario> getUsuario(String usuarioID) {

Agora é so utilizar da API para checar a existencia de um retorno:

Optional <Usuario> user = usuarioService.getUsuario(usuarioID);
if (user.isPresent()) {
    System.out.println(user.get().nome().get());
}

Segue uma visão mais aprofundada no documento da Oracle:
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
Comment: Achei bem interessante o Optional! Fiz algumas experiências aqui e é be legal mesmo. Obrigado pela dica.
Comment: Exato Reginaldo, essa maneira é muito interessante e traz um smell funcional pra linguagem. Interessantemente, Optional em Java tb é um Monad.  http://learnyouahaskell.com/a-fistful-of-monads#monad-laws


Does $\sqrt{n}(Y_n-1)$ converge in distribution?

Question: Let $n\in \mathbb{N}$ and consider, for each $n$, independent real valued stochastic variables $Z_{1n}\ldots Z_{nn}$, such that
$$
    P(Z_{nk}=n)=1-P(Z_{nk}=0)=\frac{1}{n}
$$
for $k=1,\ldots,n$. Thus $Z_{nk}$ takes on almost surely the two values $n$ and $0$. Define
$$
    Y_n=\frac{1}{n}\sum_{i=1}^nZ_{nk}
 $$
see that $\mathbb{E}Z_{nk}=np=n\frac{1}{n}=1$. The we use that the expectations of sums is equal to the sums of expectations, so
$$
    \mathbb{E}Y_n=\mathbb{E} \frac{1}{n}\sum_{k=1}^n Z_{nk}=\frac{1}{n}\sum_{k=1}^n \mathbb{E}Z_{nk}=\frac{1}{n}n=1
$$
We also see that $VZ_{nk}=np(1-p)=1-\frac{1}{n}$. Further. Since all the $Z_{nk}$'s are uncorrelated, we have that the variance of the sum, is equal to the sum of the variances.
$$
    VY_n=V \frac{1}{n}\sum_{k=1}^n Z_{nk}=\frac{1}{n}\sum_{k=1}^n VZ_{nk}=\frac{1}{n}n(1-\frac{1}{n})=\frac{n-1}{n}
$$
Further. From the central limit theorem we know that
$$
P\left(\frac{1}{\sqrt{n}}\sum_{i=1}^n\frac{X_i-\xi}{\sigma} \leq x\right)\rightarrow \Phi(x)
$$

How do I show that the distribution of $\sqrt{n}(Y_n-1)\xrightarrow{D}\mathcal{N}(0,1)$
Comment: Ah-h-h... I smell Billingsley here. I [never liked](http://www.amazon.com/Probability-Theory-Universitext-Alexandr-Borovkov/dp/144715200X) the Lindberg proof, the characteristic functions proof is so much cuter and more compact... shows the beauty of math rather than the tediousness of measure theory. @RudFaden, can you please go back and edit your question to include the full formulation of the CLT as was just proved in your class?
Comment: @RudFaden, this is your educational opportunity, then. Usually, chfs and mgfs are the easiest tool to study convergence in distribution. I would not ask my students to establish convergence in distribution without equipping them these tools. Characteristic functions require complex analysis, and moment generating functions, only calculus.
Comment: @StasK and other curious people. It is a measure theory class. We just proved the CLT (Lindberg proof) and been shown a few examples. I think the solution is just to plus the mean and variance of $Y_n$ into the CLT and then show that it becomes $\sqrt{n}(Y_n-1)$. But I can't really get it to fit though.
Comment: can you derive the characteristic or the moment generating function of $Y_n$?
Comment: Did you mean to define$Y_n$ as $\displaystyle Y_n=\frac 1n \sum_{i=1}^nZ_{nk}$ instead of as $\displaystyle Y_n=\sum_{i=1}^nZ_{nk}$?
Comment: @DilipSarwate Yes. I have corrected that.
Comment: @StasK it is not part of the curriculum. So I am not sure.
Comment: @StasK If the OP hasn't got an introduction to those tools, it is maybe just a basic statistics class. As a result, it may be enough to apply just one of the central limit theorems here.
Comment: @random_guy, may be. But it is still an unbalanced basic stats class if they teach weak convergence. A clarification to the OP, then, stands: what are the tools that they have at their disposal to demonstrate convergence in distribution?
Comment: I would have thought $Y_n=\frac{1}{n}\sum_{i=1}^nZ_{nk}$ had a binomial distribution with parameters $n$ and $p=\frac1n$.  Since $np=1$ is a constant, $Y_n\xrightarrow{D}$ a Poisson distribution with parameter $\lambda=1$.
Comment: There is a convergence in distribution from Poisson distributions to normal distributions: if $X_n$ has a Poisson distribution with parameter $\lambda=n$ then $\frac{X_n-n}{\sqrt{n}} \xrightarrow{D} \mathcal{N}(0,1)$.  But I do not see how that fits here
Answer: Firstly, your indices are overdefined, since you only ever sum $Z_{kn}$ over $k$.  So I'm going to simplify your problem by just referring to these as $Z_k$.  Now, define $X_{k} \sim \text{IID Bern}(1/n)$ and $Z_{k} = n X_{k}$ so that you're now dealing with standard indicator variables.  You then have:
$$Y_n = \frac{1}{n} \sum_{k=1}^n Z_{k} = \sum_{k=1}^n X_{k} \sim \text{Bin}(n,1/n).$$
Your mean and variance formulae follow directly from this known distribution.  The asymptotic mean and variance of $Y_n$ is unity, and from the CLT we have:
$$Y_n \xrightarrow{D} \text{N}(1,1).$$
This is a different asymptotic result from the one you conjectured.


Laravel 7: Automatically add values to a column on first day of every month

Question: I want to add value to specific column for all rows in a table every month.
Users Table:

id
leave_alloc
leave_earn

1
20
0

2
20
1.5

3
20
-3

4
20
4

Controller:
public function earned_leave(){
  $user = User::where('leave_alloc', '!=', null)->get();
  foreach($user as $row){
    $leave_alloc = $row->leave_alloc;
    $earned_leave = $leave_alloc / 12;
    $row->leave_earn += $earned_leave;
    $row->save();
  }
}

Here $earned_leave will be the result of $leave_alloc divided by 12. So, on the first day of every month, I want to add the earned leave amount to the leave_earn column of all users. This column can hold a negative value and decimal value.
How can I make this automation?
Comment: you can create a schedule  with option `monthly()` . document : https://laravel.com/docs/9.x/scheduling#schedule-frequency-options
Answer: Laravel support task scheduling. For your task you may use ->monthlyOn(4, '15:00');
In most simple realization it looks like
$schedule->call(function () {
  $user = User::where('leave_alloc', '!=', null)->get();
  foreach($user as $row){
    $earned_leave = $row->leave_alloc / 12;
    $row->leave_earn += $earned_leave;
    $row->save();
  }
})->monthlyOn(1, '12:00');

Don't forget to add Cron entry
Comment: Thanks, I'm checking. Is my calculation part correct?
Comment: Will it run on the local server?
Comment: @ShanMdShazarulHaque171-15- yes it is. You may write a console command and call it manually.