Proof of the trace inequality in PDE

Question: From Evan's Partial Differential Equations in Ch. 5, there is what seems to be a relatively straightforward exercise (5.7) which is a proof of the trace inequality. Here is the statement of the problem:

Assume that $U$ is bounded and there exists a smooth vector field $\alpha$ such that $\alpha\cdot \nu \ge 1$ along $\partial U$, where $\nu$ as usual denotes the outward unit normal. Assume $1\le p <\infty$. Apply the Gauss-Green Theorem to $\int_{\partial U}|u|^{p}\alpha\cdot \nu dS$, to derive a new proof of the trace inequality
$$\int_{\partial U}|u|^{p} dS\leq C\int_{U}|Du|^{p}+|u|^{p}dx$$
for all $u\in C^{1}(\bar{U})$.

I can handle the proof relatively easily up until the end. By assumption, since $\alpha\cdot \nu \geq 1$, we have
$$\int_{\partial U}|u|^{p}\alpha\cdot\nu dS \geq \int_{\partial U}|u|^{p}dS$$
Now applying the Gauss-Green Theorem to the left-side of this inequality we obtain
$$\int_{\partial U}|u|^{p}\alpha\cdot\nu dS=\int_{U}div(|u|^{p}\alpha)dx=\int_{U} div(\alpha)|u|^{p}+D|u|^{p}\cdot \alpha dx$$
I am not entirely sure what to do next with this, how does the smoothness of $\alpha$, for example, fit into this proof? Any suggestions on how to proceed would be incredibly helpful.
Answer: Suppose first $1<p<\infty$ so that $|u|^p$ is in $C^1(\overline{U})$. Smoothness of $\alpha$ (which can be defined on all of $\Bbb{R}^n$) allows you to justify the use of the divergence theorem, and since $\alpha$ is a fixed smooth vector field, you have uniform bounds on it and all its first derivatives. So,
\begin{align}
\int_{\partial U}|u|^p\,dS&\leq\int_{\partial U}|u|^p\alpha\cdot\nu\,dS\\
&=\int_U[\text{div}(\alpha)|u|^p+p|u|^{p-1}\text{sgn}(u)Du\cdot \alpha]\,dV\\
&\leq C(\|\alpha\|_{\infty},\|D\alpha\|_{\infty})\int_U\left(|u|^p+p|u|^{p-1}|Du|\right)\,dV\\
&\leq C(\|\alpha\|_{\infty},\|D\alpha\|_{\infty})\int_{U}\left[|u|^p+p\left(\frac{p-1}{p}|u|^p+\frac{1}{p}|Du|^p\right)\right]\,dV\tag{$*$}\\
&\leq C(\|\alpha\|_{\infty},\|D\alpha\|_{\infty})\int_U\left(p|u|^p+|Du|^p\right)\,dV,
\end{align}
which completes the proof for $1<p<\infty$. If $p=1$, then you can work through the above derivation with the divergence theorem being applied in a weak sense, or you can (why?) simply take the limit $p\to 1^+$ above… this is why I kept the explicit lack of dependence of the constant $C$ on $p$ (why is this important?). Another way of arguing for $p=1$ is to apply the inequality above for $p=1$ with a 'regularized' function $u_{\epsilon}=\sqrt{|u|^2+\epsilon}$, and then taking the limit $\epsilon\to 0^+$. There are several analysis tricks here for dealing with the edge case $p=1$, and you should gain familiarity with as many of them as you can.
For $(*)$, first recall Young's inequality $ab\leq \frac{a^p}{p}+\frac{b^q}{q}$, where $a,b\geq 0$ and $p,q\in (1,\infty)$ are Holder-conjugate exponents (so $\frac{1}{p}+\frac{1}{q}=1$). Now for any $\xi,\eta\in [0,\infty)$, apply this with $a=\eta$ and $b=\xi^{p-1}$ to get
\begin{align}
\xi^{p-1}\eta\leq \frac{\eta^p}{p}+\frac{(\xi^{p-1})^q}{q}=\frac{\eta^p}{p}+\frac{p-1}{p}\xi^p.
\end{align}

Note that if the Young's inequality stuff is confusing, then to keep the gist of the argument in mind, focus on $p=2$, then the inequality simply says $ab\leq \frac{a^2+b^2}{2}$ (which is equivalent to the obviously true inequality $(a-b)^2\geq 0$). This means in the above derivation, we simply use $2|u||Du|\leq |u|^2+|Du|^2$.
Having said that, Young's inequality, and Holder's inequality are basic inequalities fundamental for real analysis, and as such they should always come to mind as suitable things to try (even if it takes you a while to figure out the right constants/exponents).

Proof of the trace inequality in PDE


My boolean is outputing none?

Question: sunny = (input('Is it sunny outside?  '))

def isItSunny(sunny):

if sunny == True:
    return 'Its sunny outside, you may need sunsreen'

elif sunny == False:
    return 'Its cloudy, rain might be forcasted!'

print (str(isItSunny(sunny)))

When I run this short program and enter "True" or "False" I get an output of "none" instead of  return value any ideas? What might I be doing wrong? New to programming so still learning the quote on quote ropes.
Answer: The string 'True' is not equal to the literal True
>>> 'True' == True
False

You should be doing string comparisons
if sunny == 'True':

My boolean is outputing none?


Uncaught TypeError: Cannot read property 'fn' of undefined

Question: This occured after I added the following lines in the hook_init() implementation done from a custom module.
function myid_init() {
  drupal_add_js(drupal_get_path("module", "myid") . "/photobooth-js-gh-pages/photobooth_min.js");
  drupal_add_js(drupal_get_path("module", "myid") . "/photobooth-js-gh-pages/website/js/script.js");
}

It needs jQuery 1.11.2 to work, but Drupal already uses jQuery.
I installed the jQuery Update module and found out that, in the configuration setting, the newer jQuery version I could select is 1.10, but that is not sufficient for jQuery plugin I want to use.
How can I use jQuery 1.11.2 in a Drupal site?
Answer: Check out the drupal.org document on using new versions of jQuery for a few solutions. One good solution is the JQuery Multi module that lets you target multiple versions of jQuery via its hook_jqmulti_libraries() hook (its README explains how).


form auto complete how to restrict results by previous drop down

Question: Hi I have a select field on a form which contains countries. The next field is a text box  which is driven by an autocomplete function. The autocomplete function returns cities from a database table.
I want to restrict the cities that the autocomplete will return based on the country value selected in the dropdown. How do I do this?
if it helps here is my form
 $country_list = _get_country_list();
    $form['country'] = array(
            '#type'=>'select',
            '#title'=>'Select Country',
            '#description'=>'Select the country where you want to collect the car',
            '#options'=>$country_list,
    );
$form['officename'] = array(
    '#type'=>'textfield',
    '#title'=> t('Location'),
    '#default_value'=>$form_state['officename'],
    '#size'=>20,
    '#maxlength' => 50,
    '#description' => t('Select the country where you want to pick up the car'),
    '#attributes' => null,
    '#required' => TRUE,
            '#autocomplete_path'=>'location-autocomplete'
);

$form['submit'] = array(
'#type'=>'submit',
'#value'=>'Search Now',
'#submit'=>array('HolidayAutosXML_carsearch_form_submit'),
);

and here is my autocomplete function. I want to restrict the sql with a where country = {country selected in Drop Down List}
function location_autocomplete($string){
$matches = array();
$result = db_query("select officename from {holidayautos_country_list} where officename like :keyword limit 0, 10", array(':keyword'=>"%" . db_like($string) . "%"));
 foreach($result as $row) {
    $matches[$row->officename] = check_plain($row->officename);
  }
drupal_json_output($matches);
}

Many Thanks
Simon
Comment: You are looking for solution similar to question which is answered [here](http://drupal.stackexchange.com/questions/10112/dynamic-select-list-in-the-form-dependent-dropdown) . You need to use AJAX Form elements. AJAX forms are best explained [here](http://randyfay.com/ajax).
Answer: Using the links suggested from Anil Sagar, I put together this solution using Ajax.
function HolidayAutosXML_carsearch_form($node, &$form_state) {
  $country_list = _get_country_list();
  $form['country'] = array(
    '#type' => 'select',
    '#title' => 'Select Country',
    '#description' => 'Select the country where you want to collect the car',
    '#options' => $country_list,
    '#ajax' => array(
      'callback' => 'update_officename_autocomplete',
      'wrapper' => 'haofficename',
    ),
  );

  $form['officename'] = array(
'#type' => 'textfield',
'#title' => t('Location'),
'#default_value' => $form_state['office name'],
'#size' => 20,
'#maxlength' => 50,
'#description' => t('Select the location where you want to pick up the car'),
'#attributes' => NULL,
'#required' => TRUE,
    '#autocomplete_path' => 'location-autocomplete',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  if (!empty($form_state['values']['country'])) {
    $form['officename']['#autocomplete_path'] = "location-autocomplete/{$form_state['values']['country']}";
  }

  $form['submit'] = array(
    '#type'=>'submit',
    '#value'=>'Search Now',
    '#submit'=>array('HolidayAutosXML_carsearch_form_submit'),
  );

  return $form;
}

I added an Ajax element to the country drop down, telling it to look for a
 with an ID equal to "haofficename" and calling a function named update_officename_autocomplete().
I used a prefix and suffix element in the office name element to wrap it in a
 element with the ID haofficename, which Ajax is going to look for.
update_officename_autocomplete() simply returns the altered office name element of the form. if you look inside the if statement you will see that it is adding to the #autocomplete_path property. So I had to add a second parameter to my autocomplete function. This function now takes $country and $officename.
function location_autocomplete($country,$string){
   $matches = array();
   $result = db_query("select officename from {holidayautos_country_list}        where officename like :keyword and country = :country limit 0, 10",  array(':keyword'=>"%" . db_like($string) . "%",':country'=>$country));
  foreach($result as $row) {
  $matches[$row->officename] = check_plain($row->officename);
  }
  drupal_json_output($matches);
  }

It works like a charm.


Code signing "StreamAlpha.bundle" failed

Question: This Version 9.2 (9C40b) on Mac High Sierra 0.13.2 (17C88) error seems to be new with no search engine results..

Here are the logs: IDEDistribution.standard.log
<code>2018-01-07 05:15:37 +0000  Platform to submission preferences result after merging and ingestion: {
"<DVTPlatform:0x7ffca7d20170:'com.apple.platform.watchos':<DVTFilePath:0x7ffca7d20100:'/Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform'>>" = "<IDEAppSubmissionPreference: 0x7ffc9da32350: storeMC: 3, storeBC: 2, devBC: YES, storeODR: 0>";
"<DVTPlatform:0x7ffca7eb5b40:'com.apple.platform.iphonesimulator':<DVTFilePath:0x7ffca7eb5ac0:'/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform'>>" = "<IDEAppSubmissionPreference: 0x7ffc9c654c40: storeMC: 2, storeBC: 0, devBC: YES, storeODR: 1>";
"<DVTPlatform:0x7ffca7d23d00:'com.apple.platform.macosx':<DVTFilePath:0x7ffca7d23c90:'/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform'>>" = "<IDEAppSubmissionPreference: 0x7ffc9c683560: storeMC: 2, storeBC: 0, devBC: YES, storeODR: 0>";
"<DVTPlatform:0x7ffca7eb25b0:'com.apple.platform.appletvsimulator':<DVTFilePath:0x7ffca7eb2530:'/Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform'>>" = "<IDEAppSubmissionPreference: 0x7ffc9c6b5810: storeMC: 1, storeBC: 0, devBC: YES, storeODR: 1>";
"<DVTPlatform:0x7ffca7c72c90:'com.apple.platform.watchsimulator':<DVTFilePath:0x7ffca7c46bb0:'/Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform'>>" = "<IDEAppSubmissionPreference: 0x7ffc9c78d020: storeMC: 1, storeBC: 0, devBC: YES, storeODR: 1>";
"<DVTPlatform:0x7ffca7d727a0:'com.apple.platform.appletvos':<DVTFilePath:0x7ffca7d72de0:'/Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform'>>" = "<IDEAppSubmissionPreference: 0x7ffc9d718220: storeMC: 3, storeBC: 2, devBC: YES, storeODR: 1>";
"<DVTPlatform:0x7ffca7daa920:'com.apple.platform.iphoneos':<DVTFilePath:0x7ffca7d76140:'/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform'>>" = "<IDEAppSubmissionPreference: 0x7ffc9c649dd0: storeMC: 3, storeBC: 1, devBC: YES, storeODR: 1>";
</code>
snippet shown above, see full one here
https://pastebin.com/tTT3fJKp
IDEDistribution.verbose.log
https://pastebin.com/g5mnDq6L
IDEDistributionPipeline
https://pastebin.com/d0KUSK1R
Answer: From the logs it seems like you have set the distribution provisioning to Automatic. While its not taking it automatically or not fully configured.
Here are some steps which help you to sort out issue :

Firstly download again distribution from developer account & re install it on Xcode by double tapping on it
Now uncheck automatic provisioning & do set up it manually by selecting provisioning
Do the same process in Targets -> Build Settings as well
Clean the project & remove derived data
Change the build no & create new archive file & try upload it

Hope it will help you....


Can't access to HttpContext.Current

Question: I can't access to HttpContext.Current on my project MVC4 with C#4.5
I've added my reference to System.Web in my project and added the using instruction on my controller page...
But I can access currentHandler only...
var context = HttpContext.CurrentHandler; //Current

Is HttpContext.Current deprecated on C#4.5 ?
I've looked this help page : http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx
Comment: you added reference to your project, but have you got a `using System.Web` on top of your file ?
Comment: if anyone find you can't use `HttpContext.Current.Request` or `Request.ApplicationPath`, try `System.Web.HttpContext.Current.Request.ApplicationPath;`
Answer: Have you included the System.Web assembly in the application?
using System.Web;

If not, try specifying the System.Web namespace, for example:
 System.Web.HttpContext.Current

Comment: funny but it only worked for me after adding the full System.Web.HttpContext.Current didn't pick up the using, i wonder why
Comment: @CMS, I think it may have something to do with Extensions.
Comment: @CMS It's pretty old but I think it's because there's some using in the Controller that already implements HttpContext
Answer: This is because you are referring to property of controller named HttpContext. To access the current context use full class name:
System.Web.HttpContext.Current

However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current as being deprecated inside ASP.NET MVC. The correct way to access current context is
this.ControllerContext.HttpContext

or if you are inside a Controller, just use member
this.HttpContext

Comment: Thanks for explain, but i can't access Current, just CurrentHanlder ... so don't resolve my problem...
Answer: Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVC applications.
The answer from Andrei means that you can use HttpContext just as you would use System.Web.HttpContext.Current. For example, if you want to do this:
System.Web.HttpContext.Current.User.Identity.Name

you should instead do this:
HttpContext.User.Identity.Name

Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.
Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.
Comment: That really does clarify Andrei's answer. Thanks for this.

Can't access to HttpContext.Current


Is custom token module sustainable for masive use?

Question: Is the Custom Token module sustainable for massive use or should I create custom module?
Custom Token will be used for generating URL path, "massive use" means hundreds or thousands of nodes created per day.
Comment: Good question, few followups: Is this one simple token across N number of nodes, or dozens of tokens across N? Also, how complex are the tokens you are creating -- simple text replacement or do they invoke other modules, ex. user? Finally, by sustainable, you're just referring to performance issues, correct?
Comment: The token generates the "random part" of Node's URL, so every generated token is uniqe (it should use nid, user name and some php functions (outside drupal). And my question is intended in general - performance, speed, security... Whatever you could help :)
Answer: In general - no, this shouldn't be a performance issue for your use case. The main problem identified with token module and pathauto is in generating the Token UI screen when dealing with a large number of tokens. There are good discussions on this here on stackexchange but I've also found that using the token tweaks module can resolve most of these.
In your use case case, your using just one token to generate the URL path which is then saved to the path alias table, a table optimized and indexed for performance. The only real demand is on token implementation but this is only done once, when saving the article and you're using objects that are already loaded (ex. $user, $node->nid) to generate it so it won't be a performance issue.


Hive installation issue while following Hive apache wiki step by step

Question: After installed Hive by the instruction on Hive apache wiki step by step, I invoked hive shell and typed "CREATE TABLE pokes (foo INT, bar STRING);", then it comes following error, log is also included.
I'm new to Hive, any suggestion or comments? Thanks a lot! I found the questions asked over google the web, but did not find solution.
I use single machine mode for Hadoop on Mac.
hive> CREATE TABLE pokes (foo INT, bar STRING);
FAILED: Error in metadata: javax.jdo.JDOFatalInternalException: Unexpected exception caught.
NestedThrowables:
java.lang.reflect.InvocationTargetException
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask
log file:

Last login: Tue Jun 14 00:27:51 on ttys001
Zhiyong-Xies-MacBook-Pro:~ hadoop$ cat /tmp/*/hive.log
2011-06-14 00:31:54,834 ERROR metastore.HiveMetaStore (HiveMetaStore.java:executeWithRetry(334)) - JDO datastore error. Retrying metastore command after 1000 ms (attempt 1 of 1)
2011-06-14 00:31:56,012 ERROR exec.DDLTask (SessionState.java:printError(374)) - FAILED: Error in metadata: javax.jdo.JDOFatalInternalException: Unexpected exception caught.
NestedThrowables:
java.lang.reflect.InvocationTargetException
org.apache.hadoop.hive.ql.metadata.HiveException: javax.jdo.JDOFatalInternalException: Unexpected exception caught.
NestedThrowables:
java.lang.reflect.InvocationTargetException
     at org.apache.hadoop.hive.ql.metadata.Hive.createTable(Hive.java:491)
     at org.apache.hadoop.hive.ql.exec.DDLTask.createTable(DDLTask.java:3233)
     at org.apache.hadoop.hive.ql.exec.DDLTask.execute(DDLTask.java:221)
     at org.apache.hadoop.hive.ql.exec.Task.executeTask(Task.java:132)
     at org.apache.hadoop.hive.ql.exec.TaskRunner.runSequential(TaskRunner.java:57)
     at org.apache.hadoop.hive.ql.Driver.launchTask(Driver.java:1238)
     at org.apache.hadoop.hive.ql.Driver.execute(Driver.java:1050)
     at org.apache.hadoop.hive.ql.Driver.run(Driver.java:885)
     at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:224)
     at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:358)
     at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:593)
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
     at java.lang.reflect.Method.invoke(Method.java:597)
     at org.apache.hadoop.util.RunJar.main(RunJar.java:156)
Caused by: javax.jdo.JDOFatalInternalException: Unexpected exception caught.
NestedThrowables:
java.lang.reflect.InvocationTargetException
     at javax.jdo.JDOHelper.invokeGetPersistenceManagerFactoryOnImplementation(JDOHelper.java:1186)
     at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:803)
     at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:698)
     at org.apache.hadoop.hive.metastore.ObjectStore.getPMF(ObjectStore.java:237)
     at org.apache.hadoop.hive.metastore.ObjectStore.getPersistenceManager(ObjectStore.java:266)
     at org.apache.hadoop.hive.metastore.ObjectStore.initialize(ObjectStore.java:199)
     at org.apache.hadoop.hive.metastore.ObjectStore.setConf(ObjectStore.java:174)
     at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:62)
     at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:117)
     at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.getMS(HiveMetaStore.java:369)
     at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.executeWithRetry(HiveMetaStore.java:321)
     at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:466)
     at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:240)
     at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.(HiveMetaStore.java:203)
     at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.(HiveMetaStoreClient.java:107)
     at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:2010)
     at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:2020)
     at org.apache.hadoop.hive.ql.metadata.Hive.createTable(Hive.java:485)
     ... 15 more
Caused by: java.lang.reflect.InvocationTargetException
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
     at java.lang.reflect.Method.invoke(Method.java:597)
     at javax.jdo.JDOHelper$16.run(JDOHelper.java:1958)
     at java.security.AccessController.doPrivileged(Native Method)
     at javax.jdo.JDOHelper.invoke(JDOHelper.java:1953)
     at javax.jdo.JDOHelper.invokeGetPersistenceManagerFactoryOnImplementation(JDOHelper.java:1159)
     ... 32 more
Caused by: java.lang.NullPointerException
     at org.datanucleus.plugin.NonManagedPluginRegistry.registerBundle(NonManagedPluginRegistry.java:443)
     at org.datanucleus.plugin.NonManagedPluginRegistry.registerBundle(NonManagedPluginRegistry.java:355)
     at org.datanucleus.plugin.NonManagedPluginRegistry.registerExtensions(NonManagedPluginRegistry.java:215)
     at org.datanucleus.plugin.NonManagedPluginRegistry.registerExtensionPoints(NonManagedPluginRegistry.java:156)
     at org.datanucleus.plugin.PluginManager.registerExtensionPoints(PluginManager.java:82)
     at org.datanucleus.OMFContext.(OMFContext.java:156)
     at org.datanucleus.OMFContext.(OMFContext.java:137)
     at org.datanucleus.ObjectManagerFactoryImpl.initialiseOMFContext(ObjectManagerFactoryImpl.java:132)
     at org.datanucleus.jdo.JDOPersistenceManagerFactory.initialiseProperties(JDOPersistenceManagerFactory.java:363)
     at org.datanucleus.jdo.JDOPersistenceManagerFactory.(JDOPersistenceManagerFactory.java:307)
     at org.datanucleus.jdo.JDOPersistenceManagerFactory.createPersistenceManagerFactory(JDOPersistenceManagerFactory.java:255)
     at org.datanucleus.jdo.JDOPersistenceManagerFactory.getPersistenceManagerFactory(JDOPersistenceManagerFactory.java:182)
     ... 40 more

2011-06-14 00:31:56,014 ERROR ql.Driver (SessionState.java:printError(374)) - FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask
Answer: http://getsatisfaction.com/cloudera/topics/hive_error_error_in_metadata_javax_jdo_jdofatalinternalexception
Removing the $HADOOP_HOME/build directory worked like a charm.
Answer: Removing the directory $HADOOP_HOME/build (actually just renaming it) also works for hive-0.9.0 and hadoop-1.0.4.


PhoneGap offline forms and data storage with JQuery Mobile

Question: I'm trying to create an app which is basically just a long form, which then generates a PDF from the data collected. The app needs to be completely offline.
Is it possible to collect and store the data offline (I was thinking in local storage or using lawnchair) from forms without having to access a server. There will be around 100 seperate pieces of data to record.
Is there a framework or library that I could use for this, or any tutorials I could follow? Is it even possible in Phonegap??
Thanks!
Comment: use websql. it supports 50mb. Don't go for localStorage if it has more data's
Answer: localStorage has a size limitation of 5 MB
So if you think your total data is less than 5 MB you can use it, it's easy to use.
If you need to save more data, I have two database for you. First one is I'm using for almost over a year. Didn't face any issue. Brodysoft SQL wrapper plugin It's use is just like web sql.
<code>function onDeviceReady() {
  var db = window.sqlitePlugin.openDatabase({name: "my.db"});
  // ...
}
</code>
I didn't use the second one but saw the reference in SO. Read that it's very efficient. HTML5SQL
<code>$.get('Setup-Tables.SQL',function(sqlStatements){
    html5sql.process(
        //This is the text data from the SQL file you retrieved
        sqlStatements,
        function(){
            // After all statements are processed this function
            //   will be called.
        },
        function(error){
            // Handle any errors here
        }
    );
});
</code>
Between this two choice has to be yours.


Memory leaks with jQuery in IE 7/8/9 and FF 4

Question: I have been struggling with some memory leaks using jQuery in all major browsers, and am looking for some help.  I've read many articles on memory leaks, references, circular references, closures, etc.  I think I'm doing everything right.  But am still seeing memory increases in IE9 and FF4 and orphans in sIEve that just don't make sense to me.
I've created a test case to showcase the issue.  The test case basically has a large table of 500 rows, and users can click on each row to enter an inline edit mode where  elements are appended using jQuery.  When users exit inline edit mode, the  elements are removed.
The test case has a button to emulate 100 clicks for 100 rows to quickly magnify the issue.
When I run it in sIEve, memory increases 1600KB, in use goes up by 506, and there are 99 orphans.  Interestingly, if I comment out the .remove() on line 123, memory increase 1030KB, in use goes up by 11, and there are 0 orphans.
When I run it in IE9, memory increase 5900KB.  A refresh increases another 1500KB and another run increases anotherr 1K.  Continuing this pattern continues the memory use increase
When I run it in FF4, I get very different behavior if I use "100 clicks slow" and "100 clicks fast".  Emulating slow clicks has a peak increase of 8300KB and it takes a minute for it to settle down to 3300KB.  Emulating fast clicks has a peak increase of 27,700KB, then it takes a minute to settle down to 4700KB. Note this is the exact same code that is executed, just with less delays between executing.  A refresh and another run continues to increase memory at a similar rate.
Sample code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">

 <button id="slow100">100 clicks slow</button>
 <button id="fast100">100 clicks fast</button>

Comment: You do realize most browsers use memory pooling right? I don't know how you're doing your profiling, but if you're just using the "memory used" column in task manager, it's not going to be too accurate. Most browsers will allocate memory which then gets divided up internally. Even if the memory isn't being used it will still be listed as "in use".
Comment: Also the 1KB increase you're seeing may be nothing more than the caching mechanism.
Comment: @Chris: I'm somewhat familiar but far from a guru on how browsers use memory.  I'm learning still, which is part of my question.  I am using the "Working Set" column in the Resource Monitor in Windows 7, which should be the same as the Task Manager's "Memory (Private Working Set)" column plus the sharable memory.

I don't know what would be caching.  The page is not being navagated away from when I click on the rows: it's just dynamically adding input elements and removing them.  Would IE9 or FF4 cache any of this activity within one web page?  That's not my understanding.
Comment: @lschult2: yeah, working set is just the amount reserved for the process. So let's say that your script uses 10MB (just for kicks). It will ask IE for 10MB. IE will check its own memory pool. Let's say for the sake of argument that it doesn't have 10MB available. It might turn around to the OS and ask for, oh say, 50MB. It will then turn around and hand 10MB to your script, and keep the other 40 around for later. Resource manager will show 50MB in use. When your script is done, the 10 will be put back, but IE will still look like it's using 50. It looks like a leak, but isn't.
Comment: And the guess about caching was just a guess. It could be all kinds of things. History, maybe? For all I know you may have discovered a totally legitimate leak.
Comment: @Chris: the problem is that the Working Set just keeps growing and growing.  If I use my app for several hours, I've seen IE9 up to 200MB and FF4 up to 800MB.  I've traced it all to this as the source.  So the problem is it's not putting the 10 back.  It just keeps taking more and more
Comment: Just a guess here: if it's happening in more than one browser (with different javascript engines), it's probably not your code. And firefox is known to be a very bad offender when it comes to memory.
Comment: I also had "memory leaks" using jQuery and saw memory usage go up quickly. Then I discovered that waiting a little time (halting script to prevent new memory usage) the memory would eventually go down to normal levels, cause the browser started to clean the unused memory. Using your code by the way I didn't had any memory leaks or any tipe, used memory floating up and down as normal. It's hard to tell what the cause can be.
Answer: I recent technique I've learnt is to instead of binding events to every object you want clicked, bind one click to the page and look at the event to what object has been clicked.
This is much faster for multiple reasons:

There are way less bind rules for your browser to go through (which older FF and IE are poor at handling, you prob don't notice these issues on Opera or Chrome)
The whole process is much faster.

Example:
$(body).click( function (event) {
    $target = $(event.target);
    if ( $target.hasClass('w') ) {
        var jrow = $target;
        if (!jrow.find('.inedBottle').length) {
        createInlineEdit(jrow);
    }
});

this is off of the top of my head. There is prob a better way than checking the class but I'm a little under the weather.
I hope it helps!
Answer: Maybe 1 problem could be the use of .live. I'm not sure how .live works internally, but it must listen to an event that changes the DOM (every time you update/replace the elements in your td's, and if there is a new  it observes it with the given callback).
If the .live method is not ready checking for another $("td.w") included to the DOM and you start another check, it can cause those memory leaks. I'm just guessing, but try to replace this code:
 $('tr.w').live('click', function(event){
   var jrow = $(this);
   if (!jrow.find('.inedBottle').length) {
    createInlineEdit(jrow);
   }
 });

with this:
 $('tr.w').bind('click', function(event){
   var jrow = $(this);
   if (!jrow.find('.inedBottle').length) {
    createInlineEdit(jrow);
   }
 });

and maybe your memory usage is getting lower, during the heavy DOM operations. Let me know if this helps!
Comment: I actually used .bind before, and found that is more likely to cause memory leaks since a bound event handler can create the circular references. jQuery recommends .live over .bind since .live is supposed to handle that correctly.
[link](http://stackoverflow.com/questions/2411619/browser-memory-increasing-constantly-with-javascript-ajax-calls)
[link](http://stackoverflow.com/questions/2155792/ajax-memory-leak)
Comment: I do not know if that's correct for elements, which are already in the DOM and are not affected by replacements ...


Django "through" model iteration

Question: The answer to this may (and probably) already exists out there but I am having a tough time trying to come up what to look for.
I have three models: Person, Group, and Membership.
class Person(Contact):
    first_name = models.CharField(_('first name'), max_length=200, blank=True)
    last_name = models.CharField(_('last name'), max_length=200, blank=True)

class Organization(Contact):
    title = models.CharField(_('title'), max_length=200)
    members = models.ManyToManyField(Person, blank=True, through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person)
    organization = models.ForeignKey(Organization)
    position = models.CharField(max_length=64, blank=True)

I'd like to get a list of people and have easy access the group that a person belongs to but its not a 1-to-1 relationship between Memberships and Person. It seems like the easiest way would be to create a method get_memberships within Person which would return the memberships, if any, that a person is associated with. Does this make sense and is it a reasonable practice to access this relationship from within the model this way or is there a better way to go about it?
Answer: Yes.
Person.organization_set.all() should return the list of organisations to which the Person in question belongs. For each organisation in that set, you can then return their position, so:
p = Person.objects.get(id=personid)

for o in p.organization_set.all():
    # you have o and p, you should be able to find a unique m.
    m = Membership.objects.get(Person=p, Organization=o)

See the documentation here.

Django "through" model iteration


Erro ao imprimir o valor da propriedade owner.screenname e owner.url (Dailymotion Data API)

Question: Ao executar o GET para os recursos PLAYLIST e VIDEO, tive um problema. Ao executar GET no meu console, a solicitação retorna corretamente os valores dos atributos owner.screenname e owner.url; no entanto, ao fazer a mesma solicitação por AJAX (jQuery), esses valores são apresentados como undefined (console do Google Chrome) . Vocês poderiam me dizer onde estou errando? Estou usando a Dailymotion Data API. Estou fazendo a chamada a partir de http://localhost: 8084 (Apache Tomcat)
Código:
$.ajax({
    type: "GET",
    url: "https://api.dailymotion.com/video/x26ezj5?fields=id,title,owner,owner.screenname,owner.url",
    dataType: "json"
})
.done(function(data){
    console.log(data.id);
    console.log(data.title);
    console.log(data.owner);
    console.log(data.owner.screenname);
    console.log(data.owner.url);
})
.fail(function(jqXHR, textStatus, errorThrown){
    console.log(jqXHR.status + textStatus + errorThrown);
})
.always(function(data) {
    console.log(data);
});

Console do Chrome:
x26ezj5
Greetings
x1fz4ii
undefined
undefined
{id: "x26ezj5", title: "Greetings", owner: "x1fz4ii", owner.screenname: "Dailymotion API", owner.url: "https://www.dailymotion.com/DailymotionAPI"}

Answer: Utilizando o mesmo código, porém em javascript puro, obtive resultado.
Copie e cole este código no console no navegador e verás o resultado.
Acontece que você está dando console.log() em todos as propriedades do objeto data e onde retorna undefined é porque a propriedade não existe no objeto data
var xhr = new XMLHttpRequest();
var uri = "https://api.dailymotion.com/video/x26ezj5?fields=id,title,owner,owner.screenname,owner.url";

xhr.open("GET", uri, true);

//callback
xhr.onreadystatechange = function () {
    if(xhr.status >= 200 && xhr.status < 300) {
         const response = JSON.parse(xhr.response);
         console.log(response)
    } else {
         console.log("offline");
    }
};
xhr.send(null);

Comment: Wagner, obrigado pela contribuição! Consegui solucionar trocando: data.owner.screenname por data["owner.screenname"] e data.owner.url por data["owner.url"].


Backup Strategy: Online Off-site backup like Time Machine

Question: I've a linux VPS hosted in a VPS datacenter.
I need to implement backup on it. I'll order The Planet's Stored Cloud to do this.
http://www.theplanet.com/cloud-storage/
My question is about the Backup Strategy:
Today I have other servers and I use a rsync backup by week. I get a full backup at the beginning of week, and increment this along the week.
In the backup server I've something like it:
200902_week06
200902_week07
200902_week08
....
By week, I'm using rsync --delete. It's working for my proposes until now.
But in this new server, I've a lot of files, and copy and recopy it all weeks will lost bandwidth and storage size.
I this old way, I can rollback files if something goes wrong just by week. In this new case I need to rollback files by day.
I'm thinking something like Time Machine on mac: I send just what is new, like rsync, but I can rollback (and travel to) each committed day.
To do this, I'm thinking to use a VCS, like Bazaar, to manage the commit entries. What do you think about this?
The second question about this strategy is to use a second backup storage: The Backup from Backup. I know data-centers like The Planet have RAID. But what happens if someone get access on my VPS and get the user and password from backup service stored on my CRON's backup script?
In my actually way, I'm doing two backups, and in my public server there isn't mention about the second storage. Again: what do you think about this? There are other ways?
Thank you,
Daniel Koch
Comment: WTF is a "VPS datacenter"?
Comment: I'm using Linode.
Answer: For your first question, I'd recommend taking a look at rsnapshot. It's basically a wrapper around rsync, diff, and a few other tools. It will manage your versioned/incremental backups and, on your backup server, provide a browseable tree for each "snapshot". It uses filesystem hard links to provide a full "view" of each snapshot even though only a few files might have changed.
For your second question - you should be using pull backups, not push backups like you're currently using. From your backup server, generate an ssh keypair, throw the public key on your production server, and then use that account to perform backups via ssh. That way, since only your public is is on the server, no harm can be done to your backups if it gets compromised.
Also, regarding your proposal to use a VCS to manage backups. I'd highly recommend against that. Sure, it would probably work, but performance would likely be very poor. There are much better purpose-built backup tools that you'll be much happier with in the long run.
Comment: This reverse way to do backups is very fine to do this, since I can run rsnapshot inside the storage machine. I think it isn't possible using The Planet's Stored Cloud.  But I can do it using a hidden machine in the same VPS account.

Thank you for reply.
Answer: I've recently stumbled upon a good blog post that shows how easy it is to create a Time Machine scheme while using rsync. Check it out. I've also added it to the rsync wikipedia page for a longer reference.
http://en.wikipedia.org/wiki/Rsync#Examples
http://blog.interlinked.org/tutorials/rsync_time_machine.html


For any sentence A, if M $\models$ A , then M' $\models$ A as well

Question: Exact problem in words:
Let $M$ be an interpretation, and let $M′$ be an extension of $M$. Prove that, for any sentence $A$, if $M$$\models$$A$, then M′ $\models$ $A$.
I'm having trouble here because can't the extension of M' be true while M is false?
For example, taking the sentence $A$: $\exists$$x$(P($x$) $\cap$ R($a$))
So, I make an interpretation $M$ for $A$ where:
$|M|$ = {$1, 2$}
$M^P$ = {$2$}
$M^R$ = {$1$}
$M(a) = 2$
And construct an extension of $M$, $M'$, with the same domain and predicate extensions of $M$, but assigning $a$ a different object from the domain, namely
$M'(a) = 1$
Then, I see that $M$ $\models$$A$. But wouldn't the extension $M'$ be false, because $2$ $\notin$ $M^R$ $?$ Would this not provide proof that the original statement is indeed false? I'm asked to prove this statement for an assignment, so it must be true, so I must not be understanding how extensions of interpretations work, or my definition of $\models$ is wonky. Any insight into what i'm not getting would be greatly appreciated. Thanks in advance!
Answer: In the situation you've described, $M'$ is not an extension of $M$: to be an extension, $M'$ must agree with $M$ on all the symbols in the language of $M$ (in particular here, it can't send $a$ to somewhere other than where $M$ sends $a$).
The idea is that $M'$ adds structure to the existing structure of $M$. For example, the structure $A=(\mathbb{Z}; +,\times)$ is an extension of the structure $B=(\mathbb{Z};+)$: they have the same domain and each interpret the "$+$" symbol in the same way, but $A$ has an additional bit of structure, namely multiplication.

Of course, above I'm being a bit fast and loose with the distinction between a symbol and a function (or relation, or constant). Really it would be more precise to say:

"Let $\oplus,\otimes$ be binary function symbols, let $\Sigma=\{\oplus\}$, and let $\Pi=\{\oplus,\otimes\}$. Let $A$ be the $\Sigma$-structure with domain $\mathbb{Z}$ and which interprets $\oplus$ as $+$, and let $B$ be the $\Pi$-structure with domain $\mathbb{Z}$ which interprets $\oplus$ as $+$ and $\otimes$ as $\times$.  Then $A$ and $B$ have the same domain, the language of $A$ is contained in the language of $B$, and $A$ and $B$ agree on the interpretations of everything in their shared language (namely, just $\oplus$ in this case); so $B$ is an extension of $A$."

But that's a bit long, and I think the way I wrote it above is more intuitive.

Incidentally, if you're familiar with abstract algebra, there's a very general kind of extension you've seen before: a ring is an extension of its underlying group. If you're not familiar with abstract algebra, ignore this bit, but if you are this might help make the notion of extension seem more natural.
Comment: So if i say for $M'$ that it sends $a$ to the set {$1,2$}, then $M'$ would be considered a valid extension?
Comment: @MattyS11 A structure can't send a constant symbol to a set, it has to send it to a *single element*. Again, $M'$ is an extension of $M$ iff the interpretation in $M'$ of each of the symbols in the language of $M$ is **exactly the same as** the interpretation of that symbol in $M$. $M'$ needs to be identical to $M$ except as far as any *new* symbols (= symbols in the language of $M'$ but not in the language of $M$) are concerned.
Comment: right right sorry im dumb lol. So M'(a) would HAVE to map to 2 in this case, but could also send any other constant symbol x to any element of the domain.
Comment: @MattyS11 Yes - as long as such an other constant symbol wasn't in the language of $M$ already.


validate probabilities assigned by a classifier

Question: I've generated a probability of fail for each item(row) in a pandas df using a classifier.
I would like to check that the probabilities are reasonable given the positive class rate.
Say I know that there are 134 fails per year, and I have 1,000,000 rows in my df.
How would I go about this?
Would it be reasonable to estimate the probability that any 134 of the million rows will fail using the probabilities outputted from the model, say by...

calculate # of combos of 134 in 1 million
take sample of 10k combos of size 134 with replacement
calculate prob of each of the 10k combos failing (multiply the 134 individual row probabilities in each combo)
take mean of the 10k probabilities to get mean prob of any combo failing
multiply by number of combos (a) to get total prob

...effectively using N choose K but with unequally likely combinations and using sample?
Probability of fail for an item is independent of other items, and already adjusted to reflect imbalanced set.
Thank you!
Answer: Note that a classifier does not yield probabilities but instead involves a forced binary choice.  You must be talking about a probability estimation method.   Logistic regression will handle the entire range of probabilities, even for rare events.  But with only 134 events you have a very small effective sample size for estimating the contributions of multiple predictors.  Don't consider sampling with replacement to develop the probability model.  You will need to have only a handful of candidate predictive features with 134 events or will need to make heavy use of data reduction that is blinded to the outcome variable (unsupervised learning) as a first step.


I can't run a basic program through the command prompt, but I can run it through an IDE

Question: I cannot run any java programs through the command prompt (Windows 10) but I can run them through the IDE (IntelliJ) I am using. I am currently testing it using a very basic JFrame program which I will provide below. I am able to compile the .java file just fine with the javac command but whenever I try and run it using the java command, I get the error:
"Error: Could not find or load main class JavaTestProgram.java
Caused by: java.lang.ClassNotFoundException: JavaTestProgram.java"
I have tried to fix the PATH variable under system settings and tried using different IDE's and text editors.
import java.awt.FlowLayout;

import javax.swing.*;

public class JavaTestProgram {

    public static void main(String s[]) {

        JFrame frame = new JFrame("JFrame Example");

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        JLabel label = new JLabel("This is a label!");

        JButton button = new JButton();
        button.setText("Press me");

        panel.add(label);
        panel.add(button);

        frame.add(panel);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }

}

Answer: Based on the error message provided, it looks like it's because you're trying to use a class name of JavaTestProgram.java. The class name should be simply JavaTestProgram.


Flask not including/utilising Bootstrap

Question: I'm having trouble getting Bootstrap to do anything via Flask.
Here's a quick test example which should work, however it doesn't seem to be applying the styling (even though bootstrap is available via their CDN in the sources tab).
init.py
from flask import Flask, request, render_template
from flask_bootstrap import Bootstrap

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)

    Bootstrap(app)
    @app.route('/test')
    def test():
        return render_template('test.html')

test.html
    {% extends 'bootstrap/base.html' %}

    {% block content %}

      Active

      Link

      Link

      Disabled

    {% endblock %}

Result:
What it looks like
What it should look like
Both Flask and flask-bootstrap are the latest version from pip.
Answer: Fixed:
It seems flask-bootstrap only uses Bootstrap3, whereas I was trying to use components introduced in Bootstrap4.
Updated base.html (in flask-bootstrap) to utilize the latest Bootstrap4 cdns.

Flask not including/utilising Bootstrap


Find a polar representation for a curve.

Question: I have the following curve:
$(x^2 + y^2)^2 - 4x(x^2 + y^2) = 4y^2$ and I have to find its polar representation.
I don't know how. I'd like to get help .. thanks in advance.
Answer: Just as the Cartesian has two variables, we will have two variables in polar form:
$$x = r\cos \theta,\;\;y = r \sin \theta$$
We can also use the fact that $x^2 + y^2 = (r\cos \theta)^2 + (r\sin\theta)^2 = r^2 \cos^2\theta + r^2\sin^2 \theta = r^2\underbrace{(\sin^2 \theta + \cos^2 \theta)}_{= 1} =r^2$
This gives us $$r^4 - 4r^3\cos \theta - 4r^2 \sin^2\theta = 0 \iff r^2 - 4r\cos\theta - 4\sin^2\theta = 0$$
Comment: You should have $\sin^2 \theta$
Comment: @MarkBennet: thanks for pointing out the typo!!
Comment: It's not the first time you help me. I very appreciate it! thank you very much! now I'll just read around and try to understand.
Comment: It's a matter of substitution: just learn that $x = r \cos \theta, \; y = r\sin\theta$.
Comment: I will. just let me make sure I understood it ..
Comment: Well, it's pretty simple. I thought it's more complex .. well thank you my friend! :)
Comment: You're welcome!
Comment: @amWhy: Very nice feedback! =1
Answer: Replace $x$ by $r\cos\theta$, $y$ by $r\sin\theta$, and simplify. Simplification is in principle not obligatory, but it would be a little strange, for example, not to replace $r^2\cos^2\theta+r^2\sin^2\theta$ by $r^2$.
In some cases, one can express the equation we get in the form $r=f(\theta)$, where $f$ is given by an explicit formula. If it can be done in a fairly simple way, it is generally considered desirable to do so.
Added: Let us do this with your example. Do the substitution mechanically, noting that $x^2+y^2=r^2$. We get $r^4-4r^3\cos\theta=4r^2\sin^2\theta$. This is correct, but we might want to do further processing. Divide through by $r^2$, remembering that this throws away the possibility $r=0$, that is, the origin.
Now replace $\sin^2\theta$ by $1-\cos^2\theta$. We get $r^2-4r\cos\theta=4-4\cos^2\theta$. We could now solve the quadratic either for $r$ or for $\cos\theta$. By completing the square, we get $(r-2\cos\theta)^2=4$. By the way, note that $\theta=0$, $r=0$ satisfies this equation, so we have not thrown away the origin, and need not feel guilty about dividing by $r^2$.
This is simple enough, but if we wish, note that $r-2\cos\theta=\pm 2$, so $r=2\cos\theta\pm 2$. However, for many presentations (but not all) of polar coordinates, we cannot have negative $r$, so $r=2\cos\theta+2$.
Remark: Your particular problem simplified dramatically. But that is because the numbers were carefully chosen. (We could also have started by simplifying the original rectangular coordinates equation.)
Comment: Thank you. but how can I find $\theta$?
Comment: $\theta$ and $r$ are **variables**, just like $x$ and $y$. As $\theta$ travels over the interval $[0,2\pi)$ and $r$ travels over the non-negative reals, the points that satisfy the polar equation travel over the curve.
Comment: Thanks but I still don't get it .. can you show me an example?
Comment: @user1798362:    I have added a simplification for your particular example.


Find the functions satisfying $ \frac { f ( a b ) } { a b } = \frac { f ( a + b ) } { a + b } \cdot \frac { f ( a - b ) } { a - b } $

Question:
Find all the functions $ f : \mathbb R \to\mathbb R $ such that
$$ \frac { f ( a b ) } { a b } = \frac { f ( a + b ) } { a + b } \cdot \frac { f ( a - b ) } { a - b } \text . $$

I think $ f ( x ) = x $, but I don't know how to get it.
Comment: In questions like these, if you test simple functions like $f(x)=x$ or $f(x)=0$ and they work, then you don't need any more argument. Trial and error is a valid method of proof in that respect. The difficult part is to show, once you think you've found all the solutions, that you have actually found all the solutions.
Comment: if $f$ is continuous, then
1. Fixing $b$ and letting $a\to b$ we find that $f'(0)$ exists.
2. Letting $a,b\to0$ we deduce $f'(0)=f'(0)^2$, and, then, $f'(0)\in\{0,1\}$.
3. Fixing $a$ and letting $b\to0$ we obtain $f(a)=\pm\sqrt{f'(0)}a$ and then, by the differentiability of $f$ at $0$ and the continuity of $f$, $f(a)=\sqrt{f'(0)}a$, for all $a$.
Then, $f(x)=0$ or $f(x)=x$. So, you only have to prove continuity
Comment: Unfortunately I need a solution without derivatives.
Answer: First of all, note that you have $ f : \mathbb R \to \mathbb R $, and in particular $ 0 $ is in the domain of $ f $. But the functional equation
$$ \frac { f ( x y ) } { x y } = \frac { f ( x + y ) } { x + y } \cdot \frac { f ( x - y ) } { x - y } \tag 0 \label 0 $$
can only hold when $ x , y \ne 0 $ and $ x \ne \pm y $. That means \eqref{0} doesn't tell you anything about $ f ( 0 ) $, and given any solution $ f $ of \eqref{0}, you can change the value of $ f ( 0 ) $, and still get a solution; i.e. any function $ \tilde f : \mathbb R \to \mathbb R $ with $ \tilde f ( x ) = f ( x ) $ for all $ x \ne 0 $ is a solution. Thus the better question is to ask for all $ f : \mathbb R \setminus \{ 0 \} \to \mathbb R $ satisfying \eqref{0} for all $ x , y \in \mathbb R \setminus \{ 0 \} $ with $ x \ne \pm y $. Then, defining $ g : \mathbb R \setminus \{ 0 \} \to \mathbb R $ with $ g ( x ) = \frac { f ( x ) } x $, \eqref{0} gives
$$ g ( x y ) = g ( x + y ) g ( x - y ) \tag 1 \label 1 $$
for all nonzero $ x $ and $ y $ with $ x \ne \pm y $. Conversely, any $ g : \mathbb R \setminus \{ 0 \} \to \mathbb R $ satisfying \eqref{1} gives rise to an $ f : \mathbb R \setminus \{ 0 \} \to \mathbb R $ defined with $ f ( x ) = x g ( x ) $, which satisfies \eqref{0}. So we will try to solve this equivalent problem. It's straightforward to check that the constant functions $ g ( x ) = 0 $ and $ g ( x ) = 1 $ satisfy \eqref{1} (equivalently, the constant zero function and the identity function both satisfy \eqref{0}). We will show that these are the only solutions.
Setting $ y = 1 $ and then $ y = - 1 $ in \eqref{1} we get
$$ g ( x ) = g ( x + 1 ) g ( x - 1 ) = g ( x - 1 ) g ( x + 1 ) = g ( - x ) $$
for all nonzero $ x $ with $ x \ne \pm 1 $. Similarly, substituting $ \frac x 2 $ for $ x $ in \eqref{1} and once setting $ y = 2 $ and once $ y = - 2 $, we get
$$ g ( x ) = g \left( \frac x 2 + 2 \right) g \left( \frac x 2 - 2 \right) = g \left( \frac x 2 - 2 \right) g \left( \frac x 2 + 2 \right) = g ( - x ) $$
for all nonzero $ x $ with $ x \ne \pm 4 $. Thus we have
$$ g ( - x ) = g ( x ) \tag 2 \label 2 $$
for all nonzero $ x $.
Now, suppose there is a nonzero $ a $ with $ g ( a ) = 0 $. Without loss of generality, we can assume that $ a > 0 $, because if $ a < 0 $, by \eqref{2} we have $ g ( - a ) = 0 $ while at the same time $ - a > 0 $. Letting $ x = y + a $ in \eqref{1} we get $ g \big( y ( y + a ) \big) = 0 $ for all positive $ y $ (note that since $ a > 0 $, thus $ 0 \ne y + a \ne \pm y $). This means that we have $ g ( x ) = 0 $ for all positive $ x $, as when $ x > 0 $ there is a positive $ y $, namely $ y = \frac { - a + \sqrt { a ^ 2 + 4 x } } 2 $, such that $ y ( y + a ) = x $. Using \eqref{2}, this can be generalized for negative $ x $ as well, which means that $ g $ is the constant zero function, one of the mentioned solutions.
Finally, consider the other case where for all nonzero $ x $, $ g ( x ) $ is not equal to $ 0 $. Suppose that $ y $ is negative. Then we have $ 0 \ne \frac y { y - 1 } \ne \pm y $, and we can let $ x = \frac y { y - 1 } $ in \eqref{1}. In that case, we have $ x y = x + y = \frac { y ^ 2 } { y - 1 } $, and by the fact $ g \left( \frac { y ^ 2 } { y - 1 } \right) $ is not equal to $ 0 $, we find out that $ g ( x - y ) = g \left( \frac { y ^ 2 - 2 y } { y - 1 } \right) = 1 $. This means that we have $ g ( x ) = 1 $ for all negative $ x $, since for $ x < 0 $ there is a negative $ y $, namely $ y = \frac { x + 2 - \sqrt { x ^ 2 + 4 } } 2 $, such that $ \frac { y ^ 2 - 2 y } { y - 1 } = x $. By \eqref{2}, that is also true for positive $ x $, and $ g $ is the constant one function, the other mentioned solution.
Answer: just hint
For $b=1,$
put
$$g (n)=\ln (\frac {f (n)}{n}) $$
then
$$g (n+1)-g (n)+g (n-1)=0$$
the characteristic equation is
$$x^2-x+1=0$$
and
$$g (n)=A\cos (n\frac {\pi}{6})+B\sin (n\frac {\pi}{6})$$
Comment: Can we deduce that $ g(x)=0$?
Comment: I didn't know we can write the characteristic equation for any real number. I thought it is possibil only for natural numbers. Was I wrong?
Comment: @Brain123 $(g (n)) $ is a real sequence.
Comment: How is this "hint" going to help anyone with solving the problem?


Tooltip not showing up

Question: I have input group in my form:

            @Html.LabelFor(model => model.EmployeeNo, new { @class = "control-label" })

            @Html.TextBoxFor(model => model.EmployeeNo, new {@class="form-control" })
            @Html.ValidationMessageFor(model => model.EmployeeNo)

and tooltip called by this script:
$(document).ready(function () {
    $('#Contact').tooltip();
});

Jquery and bootstrap included. No warning and errors in browser console.
What I'm doing wrong?
Comment: I think data attributes like data_toggle, data_placement should be data-toggle and etc.. - insted of _
Comment: Have a look at this

[How to use bootstrap tooltip? [closed]][1]

  [1]: http://stackoverflow.com/questions/16461317/how-to-use-bootstrap-tooltip
Answer: I'm not sure why you're using data_content here. However, bootstrap require title attribute for the tooltip, so add it to your div:

    @Html.LabelFor(model => model.EmployeeNo, new { @class = "control-label" })

Answer: The tooltip function displays whatever you have added into the title attribute of your div.
So you should add the tooltip text to your div:

    @Html.LabelFor(model => model.EmployeeNo, new { @class = "control-label" })

Another possibility would be to set the content property of the tooltip when creating it:
$(document).ready(function () {
    $('#Contact').tooltip({ content: "..." });
});

Comment: Thanks It's showing now but now I must find out why it's showing on the top although data_placement is set to left.
Comment: Sounds like a CSS issue to me. Have you the jQuery UI css loaded?
Comment: Try setting the position parameter: http://api.jqueryui.com/tooltip/#option-position

Tooltip not showing up


Drupal 8 Commerce views filter Price

Question: I have a views with products and I want to sow products with price >= 100. I add Relationship 'Product variation'. All of my products are with one variation, so there shouldn't have duplication.
When I add Filter "Price" in popup no configuration options and filter no additional setting like in other numeric fields.
How I can get this filter to set >=?
Answer: My solution for this is in little custom module here,
in short: added new filter "Commerce Product variation Price", of course views should have relationship "Product variation".
Module contain also taxonomy term with depth filter (contextual is not work) for commerce_product, the same thing like on node.

Drupal 8 Commerce views filter Price


Integral $ \int_a^b ((b-x)(x-a))^{n-1}x^{\frac12-n}dx $

Question: How can I prove the integral equality below
$$ \int_a^b ((b-x)(x-a))^{n-1}x^{\frac{1}{2}-n}dx = \frac{2^{2n-1}( (n-1)!)^2}{(2n-1)!}\left(\sqrt b-\sqrt a\right)^{2n-1} $$
I have tried to find a recurrence integrating by parts:
$$I_n:= \int_a^b ((b-x)(x-a))^{n-1}x^{\frac{1}{2}-n}dx\\=\int_a^b \frac{2}{3-2n} ((b-x)(x-a))^{n-1}(x^{\frac{3}{2}-n})'dx\\=\int_a^b \frac{2(n-1)}{2n-3} ((b-x)(x-a))^{n-2}(a+b-2x)x^{\frac{3}{2}-n} dx\\=\frac{2(a+b)(n-1)}{2n-3}I_{n-1}-\frac{4(n-1)}{2n-3} \int_a^b ((b-x)(x-a))^{n-2}x^{\frac{5}{2}-n}dx$$
But, I don't know how to continue.
Maybe it is related to Beta function :
$$B(n,1/2)=\frac{2^{2n-1}}{(2n-1)!}((n-1)!)^2$$
Answer: The trick is to find two equations between I(n+1), I(n) and a third integral J(n) :

a) development of I(n+1)

b) IPP of I(n+1)
Then you just need to eliminate J(n) and come up with a recursion formula :
<code>  I(n+1) = 2n/(2n+1) [(a)^(1/2) - (b)(1/2)]^2 I(n)
</code>

fjaclot
Comment: Maybe it would have been helpful to just add the few steps: By IBP you obtain $$I_{n+1}=\frac{n}{n-1/2} \left\{ (a+b)I_n - 2J_n \right \}$$ and by development $$I_{n+1} = (a+b)I_n - J_n - ab \int_a^b \left[(b-x)(x-a)\right]^{n-1} x^{-n-1/2} \, {\rm d}x \\ \stackrel{x=ab/t}{=} (a+b)I_n - J_n - \sqrt{ab} I_n$$ where $$J_n = \int_a^b \left[(b-x)(x-a)\right]^{n-1} x^{-n+3/2} \, {\rm d}x \, .$$
Answer: Indeed, the integral can be recast into the beta function $B(n,1/2)$ as shown below. Substitute $x=\sqrt{ab}\>t^2$ to reexpress the integral as
\begin{align}
I= & \int_a^b ((b-x)(x-a))^{n-1}x^{\frac12-n}dx \\
=& 2 \sqrt[4]{ab}\int_{\sqrt[4]\frac ab }^{\sqrt[4]\frac ba } \left(b+a-\sqrt{ab}(t^2+\frac1{t^2})\right)^{n-1}dt \\
 \overset{t\to\frac1t}=& \sqrt[4]{ab}\int_{\sqrt[4]\frac ab }^{\sqrt[4]\frac ba } \left(b+a-\sqrt{ab}(t^2+\frac1{t^2})\right)^{n-1}(1+\frac1{t^2})dt \\
=& \sqrt[4]{ab}\int_{\sqrt[4]\frac ab }^{\sqrt[4]\frac ba } \left((\sqrt b-\sqrt a)^2-\sqrt{ab}(t-\frac1{t})^2\right)^{n-1}d(t-\frac1{t})\\
=& \>(\sqrt b-\sqrt a)^{2n-1}\int_{-1}^1 \left(1-y^2\right)^{n-1}dy\\
\end{align}
where the substitute $y= \frac{\sqrt[4]{ab}\>(t-\frac1t)}{\sqrt b-\sqrt a}$ is used in the last step. Note that $B(1,1/2)=2$
\begin{align}
\int_{-1}^1 \left(1-y^2\right)^{n-1}dy
& = \int_{0}^1 \left(1-t\right)^{n-1}\>t^{-\frac12}\>dt\\
&=B\left(n, \frac12\right)
= \frac{2(n-1)}{2n-1} B\left(n-1, \frac12\right)=\cdots\\
&= \frac{2^{2n-1}\> ((n-1)!)^2 }{(2n-1)!}
\end{align}
Thus
\begin{align}
I=\frac{2^{2n-1}\> ((n-1)!)^2 }{(2n-1)!}\left(\sqrt b-\sqrt a\right)^{2n-1}
\end{align}


Pandas Options Broken Again?

Question: Running this canonical example:
from pandas.io.data import  Options

aapl = Options('aapl', 'yahoo')
data = aapl.get_all_data()

gives
RemoteDataError: Data not available

I know this used to be an issue in v0.14 or so, but it was supposedly fixed with v0.15.  I'm on 0.18.1
Answer: It's Yahoo - they've changed their options site, so old parsers aren't working properly
Suggestion: first of all consider using pandas_datareader instead of deprecated pandas.io.data and monitor this issue so you'll know when this issue is fixed

Pandas Options Broken Again?


How do I convert special characters into html in twig

Question: I have some list items in drupal 8 which created by item_list template.I am sending some  tagged data to the item_list template. My idea was to get the output as This is new page.
But it returns the output as
<a href="/this-is-new.html">This is new page</a>
.
I need to print this in a twig template. But with the output I had it renders as a string in the template not as a html anchor tag. I needed to view a link to another page in template. But all I am getting is a string with the This is new page. What should I do?
Answer: NOTE: this should be avoided as it is considered bad practice as mentioned in the comments, leaving here as an example to avoided
Inside your twig template try this
  {{ var|raw }}

where var is the variable being printed.
For more information here
Comment: Using the `|raw` filter should be avoided for security reasons. For a better method to get the raw value see [How do I get the raw field value in a template?](https://drupal.stackexchange.com/questions/228388/how-do-i-get-the-raw-field-value-in-a-template/228393#228393)
Comment: @GiorgosK you cannot trust user input, you need to escape what user's put into fields/forms.  **Using `|raw` turns off Twig's auto escaping mechanism**, while on the answer that I liked to the auto escaping mechanism is still on. [Watch this to see why escaping is crucial](https://www.youtube.com/watch?v=gwUEjgbs02w&feature=youtu.be&t=1h58m37s).
Comment: @NoSssweat yes I understand the reasoning behind escaping but I did not know the inner working of you solution and that it was actually being escaped (thought it was raw) ... thanks for the link very informative
Comment: Sorry for the down vote, but I consider using the `|raw` filter bad practice. You event mentioned it in your comment `{# var won't be escaped #}`. But I don't want you to delete this answer, It's good for others to learn about avoiding this security pitfall.
Comment: @NoSssweat This won't work for me because it only escapes the outer element. As an example with my code it will only escape `` tag but not the string inside. I need to convert the string inside. This output is coming from `item_list` by auto generating the lists from Drupal. Because of that I can't grab the inside string in the `` tag.
Comment: @NoSssweat twig documentation does not mention anywhere that its not secure.
Comment: It's not, inherently, but anything that a user could have provided must be escaped for XSS. That's where security becomes a concern
Comment: so what makes @NoSssweat's solution linked above more secure. I mean they are both raw/non processed inputs ... or am I mistaken ?
Comment: Everything inside `{{ }}` is automatically escaped for xss, unless a filter (like `raw`) is used See https://www.drupal.org/node/2296163 for more info
Answer: Try using convert_encoding('UTF-8', 'HTML-ENTITIES') twig filter. For example {{ item|convert_encoding('UTF-8', 'HTML-ENTITIES')}}.
Comment: Just found out this doesn't work in Drupal 9 as well. What is the alternative?
Comment: This don't work for me :(
Comment: This no longer works in Drupal 9, which throws the warning:
Notice: iconv(): Wrong charset, conversion from `HTML-ENTITIES' to `UTF-8' is not allowed in twig_convert_encoding() (line 1000 of vendor/twig/twig/src/Extension/CoreExtension.php).
Comment: Somebody created a module to replace this functionality in Drupal 9: https://www.drupal.org/project/twig_htmlspecialchars_decode
Answer: To send html markup to a template use a #markup render element
$variables['link'] = [
  '#markup' => 'This is new page',
];

so that the html tags are not escaped when you output the variable in twig:
{{ link }}

The link here is only an example. There are better ways to build links, see How do I create a link?
Answer: There is a module to use the old convert_encoding('UTF-8', 'HTML-ENTITIES') for D9
https://www.drupal.org/project/twig_htmlspecialchars_decode
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/138009)
Answer:
But it returns the output as
<a href="/this-is-new.html">This is new page</a>
.

The reason for this, is because Twig is auto escaping your HTML. List only allows list related HTML tags, like
.

I have some list items in drupal 8
My idea was to get the output as This is new page

Don't use List as your field type, instead use Link and set it to unlimited.

Now when you add a new node:
Answer: You can make use Markup class which defines an object that passes safe strings through the render system.
1.) You first need to create a TwigExtension.php class inside a module and define a function which will actually return a formatted string.
2.) Use that function inside any of your twig files to render formatted strings.
3.) Do Rebuild the cache, using Drush cr.
-> Create a module_name.services.yml file under modules/module_name:
services:
  module_name.twig.TwigExtension:
    class: Drupal\module_name\TwigExtension
    tags:
      - {name: twig.extension}

-> Create a TwigExtension.php under modules/module_name/src/TwigExtension.php :
<?php

namespace Drupal\module_name;

use Drupal\Core\Render\Markup;

/**
 * Class DefaultService.
 *
 * @package Drupal\module_name
 */
class TwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'block_display';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('render_string', array($this, 'render_string'), array('is_safe' => array('html'))),
    );
  }

  /**
   * Function to decode html special chars
   */
  public function render_string($string) {
    $render_string = Markup::create($string);
    return $render_string;
  }

-> **Insert twig function inside your twig file: **
{% set str = render_string('This is new page') %}
....
....
{{ str }}

Hope, this will help you.
Answer: Here is a special case for title field:
{# Template field--node--title--my-node-bundle.html.twig #}

{%
  set classes = [
  'field',
  'field--name-' ~ field_name|clean_class,
  'field--type-' ~ field_type|clean_class,
  'field--label-' ~ label_display,
]
%}

  {%- for item in items -%}
    {# transform title from "inline_template" render element into "markup", to avoid escaping #}
    {% set content = item.content|merge({'#type': 'markup', '#markup': item.content['#context']['value']}) %}
    {{ content }}
  {%- endfor -%}

Answer: You can render links with item_list. Here's an example how to from the book module:
  public function bookRender() {
    $book_list = [];
    foreach ($this->bookManager->getAllBooks() as $book) {
      $book_list[] = Link::fromTextAndUrl($book['title'], $book['url']);
    }
    return [
      '#theme' => 'item_list',
      '#items' => $book_list,
      '#cache' => [
        'tags' => $this->entityTypeManager()->getDefinition('node')->getListCacheTags(),
      ],
    ];
  }

The key is to not pass it as markup, but as a renderable array/object.


Finding subsets of a list in GAP

Question: Is there a command in GAP to find all n-subsets of a list? So the input is a list and the output should be a list, which gives all n-subsets of the list in the input.
Here an example of a list with 3 elements and wanting to find all sublists with 2 elements:
Input:
L:=[ <[ 1, 0 ]>, <[ 1, 1 ]>, <[ 0, 1 ]> ]

Output:
[ [ <[ 1, 0 ]>, <[ 1, 1 ]> ], [ <[ 1, 0 ]>, <[ 0, 1 ]> ],
  [ <[ 1, 1 ]>, <[ 0, 1 ]> ] ]

Here the error I get when using the combinations command:
gap> L;
[ <[ 1, 0 ]>, <[ 1, 1 ]>, <[ 0, 1 ]> ]
gap> Combinations(L,2);
Error, no method found! For debugging hints type ?Recovery from NoMethodFound
Error, no 1st choice method found for `<' on 2 arguments called from
Sort( mset ); at /home/rene/Schreibtisch/gap4r8/lib/combinat.gi:235 called from
<function "Combinations">( <arguments> )
called from read-eval loop at line 157 of *stdin*
you can 'quit;' to quit to outer loop, or
you can 'return;' to continue

Comment: Search in this chapter: https://www.gap-system.org/Manuals/doc/ref/chap16.html. Also note the use of iterators in case the resulting list is very large. Another trick is to use index set i.e. for a set `S` find subsets of `[1..Size(S)]` and then form subsets of `S` one at a time.
Comment: `UnorderedTuples` has repetitions - is that really what you had in mind?
Comment: @AlexanderKonovalov The comment UnorderedTuples looks good. But it doesnt work when applied to my list [ <[ 1, 0 ]>, <[ 1, 1 ]>, <[ 0, 1 ]> ]. All that commands are also for sets instead of lists it seems. Is that a problem?
Comment: @AlexanderKonovalov no sorry, I mean just subsets. Had looked wrong. In all these commands there it seems I cannot input something like [ <[ 1, 0 ]>, <[ 1, 1 ]>, <[ 0, 1 ]> ] but only list of numbers?
Comment: `<[ 1, 0 ]>` is not a valid GAP input. How did you obtain it?
Comment: I use the GAP package qpa. In fact those are modules over quiver algebras, displayed by their dimension vector.
Comment: Here is what I want to do with the subets: https://mathoverflow.net/questions/272984/finding-special-modules
Comment: I presume `[ <[ 1, 0 ]>, <[ 1, 1 ]>, <[ 0, 1 ]> ]` is stored in some GAP variable - you have to access it like I access `s` in my answer, instead of pasting the output. You may also try to print it with `Print` and see if that will be a valid GAP input. But anyway copying and pasting is error-prone, so write the code which avoids that.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/61055/discussion-between-mare-and-alexander-konovalov).
Answer: You can use combinations as documented in this chapter.
For example:
gap> s:=["A","B","C"];
[ "A", "B", "C" ]
gap> Combinations(s,2);
[ [ "A", "B" ], [ "A", "C" ], [ "B", "C" ] ]

Generating the list of all combinations may be expensive, but you can iterate over them instead:
gap> for x in IteratorOfCombinations(s,2) do
> Print(x,"\n");
> od;
[ "A", "B" ]
[ "A", "C" ]
[ "B", "C" ]

Also, you can form combinations of indices instead of combinations of elements of the set itself, for example:
gap> for x in IteratorOfCombinations([1..Size(s)]) do
> Print(s{x},"\n");
> od;
[  ]
[ "A" ]
[ "B" ]
[ "C" ]
[ "A", "B" ]
[ "A", "C" ]
[ "B", "C" ]
[ "A", "B", "C" ]

Comment: Thanks, but that doesnt work when the elements of the list are modules coming from quiver algebras. Is that a bug?
Comment: I need to be able to reproduce the full example before making any further statements. Can you please edit your question and show how did you obtain the ist `L`?
Comment: Apriori my suspicion is that to form a set it requires some way of sorting these modules, which is not defined by QPA. If you know that the list of modules does not have duplicates, you can use the "index set" approach as in the last example in my answer.
Answer: The error message you got:
Error, no 1st choice method found for `<' on 2 arguments called from

indicates that the problem is with comparison. I suspect that qpa simply has no method for this comparison installed.
(The reason for this being a problem is that Combinations first tests for duplicate entries amongst the arguments.)
The easiest way to deal with it is probably to first creates sets of the index positions and then construct subsets. That is:
gap> L:=["A","B","C","D","E"];
[ "A", "B", "C", "D", "E" ]
gap> subsets:=Combinations([1..Length(L)],2);
[ [ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 1, 5 ], [ 2, 3 ], [ 2, 4 ], [ 2, 5 ],
  [ 3, 4 ], [ 3, 5 ], [ 4, 5 ] ]
gap> subsets:=List(subsets,x->L{x});
[ [ "A", "B" ], [ "A", "C" ], [ "A", "D" ], [ "A", "E" ], [ "B", "C" ],
  [ "B", "D" ], [ "B", "E" ], [ "C", "D" ], [ "C", "E" ], [ "D", "E" ] ]

This way you do not need to compare the elements of L themselves.
Comment: Exactly - see https://chat.stackexchange.com/rooms/61055/discussion-between-mare-and-alexander-konovalov

Finding subsets of a list in GAP


MediaWiki setOption() on own PHP page

Question: i have a problem :) I want to use an own PHP file on my server which has the ability to change Options of Users registered in the MediaWiki Installation on same server. For this i have load the webstart and autoload includes. Now, i can read settings of the user logged in at this time without problems. But, if i want to save the edited setting (with setOption()), it appears the following notice:

Notice: Uncommitted DB writes (transaction from DatabaseBase::query (LCStoreDB::get)). in /var/www/wiki/includes/db/Database.php on line 4065 Notice: DB transaction callbacks still pending (from Title::invalidateCache). in /var/www/wiki/includes/db/Database.php on line 4073

and the Option isn't saved to the database :( Have anyone an idea, how to do my task, or how i can solve my problem?
Thanks!
Here is the code:
<code><?php
$IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
    ? getenv( 'MW_INSTALL_PATH' )
    : realpath( __DIR__ . '/' );
require_once "$IP/includes/AutoLoader.php";
require_once( "$IP/includes/WebStart.php" );

$t = new User();
$user = $t->newFromSession();
if(!isset($wgCommandLineMode) && !isset($_COOKIE[session_name()])) {
    wfSetupSession();
}
if ($user->isLoggedIn()) {
    $user->setOption( 'skinname', 'vector' );
    $user->setCookies();
    $user->saveSettings();
}
</code>
?>
Comment: Possibly related to [this known bug](https://bugzilla.wikimedia.org/show_bug.cgi?id=56269)?
Comment: Thanks for that, maybe it's the same bug, i have posted there and will test after a bugfix for that, thx :)
Answer: You need to properly shut down the database connection when using automatic transactions (which is the default when $wgCommandLineMode is true). Add something like this at the end of your file:
<code>$lb = wfGetLBFactory();
$lb->shutdown();
</code>
You'd also probably want to catch any exceptions that might be thrown and do a rollback on all open database connections. As for MediaWiki bug 56269, that's not your issue (although the lack of an ability to do a rollback on all open database connections is probably contributing to that bug).
Comment: Thanks, that's it :) In my code i have a try catch construct, so, if any error occur, the script rollback the changes :) Big thanks for your help!
Answer: Try subclassing the Maintenance class in includes/Maintenance.php and implement the abstract execute function with the desired code.  I encountered the same warnings/no saves as you did with uncommitted transactions.  Following the example in createAndPromote.php, the database transactions were committed.
Comment: Tried, but the same error :/ I have tried also this http://forge.typo3.org/issues/54257 but does not work, too. I think, i will wait, until the bug liked from Patrick Q is fixed, thx nevertheless.

MediaWiki setOption() on own PHP page


Normalizing product quantities to use them as implicit ratings in Product Recommendation

Question: I am running a product recommendation using ALS method on retail transaction data. A simple question struck my mind on the using the methodology in case of implicit ratings. In my case I am using the quantities of different products bought by customer as my implicit rating. My question is if I am normalizing the quantities, should I normalize with respect to each product or each customer.
For example if I am using a normalizing there are the following two cases that I am puzzled with. Which one is ideal in my scenario?
Case a: Rating of Customer 1 on product 1 is = quantity of product 1 bought by customer 1/sum of quantities of all products bought by customer 1
Case b: Rating of Customer 1 on product 1 is = quantity of product 1 bought by customer 1/sum of quantities of product 1 bought by all customers
P.S. I am fairly new to this community and this is my first question. :)
Answer: Without knowing what you refer to as ALS I'd say crafting the two features you answer two different questions:
The first way answers the question: What did that customer think about that product in the past?
The second feature answers the question: What did all customers think about this product in the past?
First of all when you have a choice of which features you should use an easy way of figuring out which ones are the 'good'/right ones and which ones are the bad ones is to craft both of them, let the model run and assess by any means (feature importance / evaluate the model 4 times, once without both features, two times with only one of the two features, one final time with both of them / ...) the model performance depending on those features. This is an 'automatic' way that will guide you towards new questions/insights.
For this particular scenario I would say whether feature number 1 is useful depends on the 'usual' customer behaviour: Does it happen often that a certain customer buys the same product often? In that case feature nr. 1 is particularly useful because it gives a personally tailored estimation of the 'value' of thet product to that particular customer (while features nr. 2 only gives a rough estimate of the average value of that product to all customers but does not express anything about how important that product is for the customer in question).
Does it happen often that customers buy a certain product for the first time? Then you need to go with either feature 2 or a more clever way of crafting that feature. Amazon has demonstrated that by creating 'customers who bought this were also interested in ...' and you could do something like that as well:
Create a vector of the products most bought by the current customer.
Create such a vector for every other customer as well.
Check how much customers liked that product in question that had a 'most similar' past behavioural vector in comparison to the present customer.
Does that help?
Comment: Thanks for your detailed answer. It really does help. By ALS i meant Alternating Least Squares Matrix Factorization algorithm to come up with product recommendations which can give out new products as well as the recommendations for products already bought in past. For now I have used case a and then ranked the products based on scores provided by the algorithm. And was confused on whether i should have done the normalization differently to include more informations.


Is there an Xcode code completion shortcut to jump through noncontiguous function names?

Question: I want to be able to select a table view delegate method with the least amount of characters possible.
Let say I want to implement the
<code>tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
</code>
So I start typing "t". Code completion kicks in and gives me a nice selection.
Is there a way to somehow "jump" to red highlighted character position (I chose "d" but it's about the position..not that particular "d")  after I type "t" and since I want the tableView:heightForRowAtIndexPath: I would type "h" and the method would be selected?
Comment: File an enhancement request.
Answer: Update:
Now Xcode 7 ships with the fuzzy autocompletion by default
Previous answer:
Sadly no. It was hinted that Xcode 7 might implement a fuzzy autocomplete engine, but so far we have to use a third party solution:
Fuzzy autocomplete
I've been using it for a while and works great. You can install it with Alcatraz, if you are familiar with it.
Comment: one and the best answer
Comment: I use AppCode simultaniously with Xcode to get this functionality


About loading spring beans, How to catch the bean that is loaded at first?

Question: I made some logic making db instance and create schema and tables for running.
And those logic is included in the web application file (war).  If I put the war into a specific container and then start the servlet container for loading the web application context, I want to run this logic whenever the instance is not created. How can I achieve this? please give some elaborate explanations..
thanks in advance :)
Answer: Make use of ServletContainerInitializer.onStartUp if you are on Servlet 3.x or use ServletContextListener.contextInitialized if on Servlet 2.x.
Within the implementation of the respective method invoke the custom setup you like to perform before initialization / start of the web app.
For code sample(s) see here.
Comment: Thanks for the hint. But in my case,  I am using gretty gradle plugin for making war file and playing a role as a servlet container. I confirmed that META-INF/services/javax.servlet.ServletContainerInitializer that has implemnation classes in the war. But the servlet container didn't regcognize the ServletContainerInitialzer.


Drupal 8 settings.yml file doesn't reflect changes

Question: So I'm trying to define some additional values in my settings.yml file, but none of my changes are reflected in the code. The config object has the same values in it. I've tried drush cr and other measures to clear the cache, but nothing works.
Answer: yml files are just imported on module install time.
If you need runtime changes, during development, have a look at
https://www.drupal.org/project/config_devel


Input datetime não tem opção de calendário

Question: No input date dá a opção de abrir calendário para seleccionar a data, no datetime não tem essa opção.

<input type="datetime" name="DataInicio" id="DataInicio" >

<input type="date" name="DataReserva" id="DataReserva">

Como posso resolver o problema?
Comment: Uma forma muito simples de resolver isso, é usando jQuery. Segue algumas referências https://xdsoft.net/jqplugins/datetimepicker/ https://eonasdan.github.io/bootstrap-datetimepicker/ Espero que resolva.
Answer: Olá, o correto seria o datatime-local, mesmo assim vai ter limitações que vai depender do seu navegador.
É um recurso do HTML5, onde os Browser que tem que se adaptar, não mais como antes rsrsrs, que as linguagem trabalhavam em cima do navegador, agora é ao contrário, os navegadores que tem que acompanhar as linguagens.
Mas creio que nem o Chrome nem o Firefox não tenha suporte 100% ainda.

<input type="datetime-local" name="DataInicio" id="DataInicio" >
<input type="date" name="DataReserva" id="DataReserva">
Comment: Segundo a [documentação](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local#Browser_compatibility), o Chrome >= 20 já tem suporte a `datetime-local` (mas o Firefox, Safari e IE não tem) - inclusive fiz o teste aqui e só funcionou no Chrome mesmo...
Comment: É... só a parte da Hora que é manual ainda, ele carrega só o calendário.
Answer: Para fazer isto eu costumo usar jQuery-UI.
Segue abaixo exemplo genérico de uso.

$("#DataInicio").on("click", function() {
  $("#DataInicio").datepicker({
    dateFormat: 'dd-mm-yy'
  });
});

$("#DataReserva").on("click", function() {
  $("#DataReserva").datepicker({
    dateFormat: 'dd-mm-yy'
  });
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">

<input type="text" name="DataInicio" id="DataInicio" >

<input type="text" name="DataReserva" id="DataReserva">
Comment: Importante o uso do `placeholder` (do html5) para melhor comunicação com o usuário.


R Arimax Function

Question: I want to make forecast on my data by running an arimax model.
The data is like:
Value1, Flag1, Flag2, ................., FlagN
Value2, Flag1, Flag2, ................., FlagN
Value3, Flag1, Flag2, ................., FlagN
Value4, Flag1, Flag2, ................., FlagN
Value5, Flag1, Flag2, ................., FlagN
....
ValueM, Flag1, Flag2, ................., FlagN

So, when I want to make a new forecast, I will provide flag values to the model, then it can give me the forecast value?
How can I prepare the input data?
What is the proper R function and proper way of calling?
Answer: You want the arima function in base R, or the Arima function in the forecast package.  auto.arima may be useful as well.
type ?arima into R to read the help page, which gives a good overview for fitting such models.  You'll want to split your data into 2 parts: a vector of class ts for "value," and a matrix of your external regressors, which you pass to the xreg argument of the various arima functions.
You can then predict these models using the predict function. You will need to make forecasts of your xregs and pass them to the prediction function in the newxreg argument.  You can also use the forecast function in the forecast package to produce confidence intervals and plots.  ?predict.Arima in base R and ?forecast.Arima in forecast.
Before you do any of this; however, you need to think about your forecasting problem.  Say you want to forecast 1 step ahead (for ValueN).  Will you have the flags for ValueN at time M?  If not, your ARIMAX model will be useless.

R Arimax Function


Higher Order Terms in Stirling's Approximation

Question: Some websites and books give stirling approximation as
$$n! = \sqrt{2 \pi n} \left( \frac{n}{e} \right)^n \left( 1 + O \left(\frac{1}{n} \right)\right)$$
However when I check their derivations most do it analytically up to
$$n! \approx \sqrt{2 \pi n}  \left(\frac{n}{e}\right)^n$$
So I tried proving the $$O\left(\frac {1}{n}\right) $$ term but to no avail.
Here are my steps, hopefully someone can point me in the right direction
First I began by defining
$$n!=\Gamma(n+1) = \int{e^{-x}x^{n} }dx  $$
$$=\int{dxe^{nlnx-x}}$$
The maximum of the integrand is at $$x =n$$
Next, I will expand the powers by a taylor approximation about x=n
$$f(x) = -x+nlnx$$
$$f'(x) = -1 +nx^{-1}$$
$$f''(x) = -nx^{-2}$$
$$f^{3}(x)=2nx^{-3}$$
By letting $$ x = n+\epsilon$$
I get
$$f(n+\epsilon) = -n + nlnn + 0\epsilon + -\frac{1}{n^2}\epsilon^2 + \frac{2}{n^{2}\epsilon^3} $$
Plugging back into the integration
$$\Gamma(n+1) = n! = n^{n}e^{-n}\int{e^{-\frac{\epsilon^2}{2n}+\frac{\epsilon^3}{3n^2}+...}}d\epsilon +...$$
Normally if it were up to the second derivative term of the taylor's expansion, it would be a gaussian integral. But if there are more terms, how would I do it?
Or is there another approach?
Answer: The Euler-MacLaurin summation formula can be used to approximate $n!$ conveniently.
The following is taken from Concrete Mathematics by D.E. Knuth ad R.L. Graham. We find in section 9.5 among other representations this version of the Euler-MacLaurin summation formula for integer values $a\leq b$

\begin{align*}
\sum_{a\leq k < b}f(k)&=\int_a^bf(x)dx-\frac{1}{2}\left.f(x)\right|_a^{b}+\sum_{k=1}^{m}\frac{B_{2k}}{(2k)!}\left.f^{(2k-1)}(x)\right|_a^b\tag{1}\\
&\qquad+
\mathcal{O}\left((2\pi)^{-2m}\right)\int_a^b\left|f^{(2m)}(x)\right|dx
\end{align*}

with $B_k$ the Bernoulli numbers starting with
\begin{align*}
B_0=1,B_1=-\frac{1}{2},B_2=\frac{1}{6},B_4=-\frac{1}{30},B_6=\frac{1}{42},\ldots
\end{align*}
and $B_k=0$ for odd $k$ greater $1$.
It is also shown, that if the function $f$ has the nice property $$f^{2m}(x)\geq 0$$ for $a\leq x \leq b$ then it turns out that the remainder in (1) can be replaced with
\begin{align*}
\Theta_m\frac{B_{2m+2}}{(2m+2)!}\left.f^{(2m+1)}(x)\right|_a^b\qquad\qquad \text{for some }0<\Theta<1
\end{align*}

and we obtain
  \begin{align*}
\sum_{a\leq k < b}f(k)&=\int_a^bf(x)dx-\frac{1}{2}\left.f(x)\right|_a^{b}+\sum_{k=1}^{m}\frac{B_{2k}}{(2k)!}\left. f^{(2k-1)}(x)\right|_a^b\\
&\qquad+\Theta_m\frac{B_{2m+2}}{(2m+2)!}\left.f^{(2m+1)}(x)\right|_a^b\tag{2}
\end{align*}

Example: $f(x)=\ln x$
In order to find the Stirling formula for $n!$ we consider $f(x)=\ln x$ and derive following approximation for $(n-1)!$
\begin{align*}
\sum_{1\leq k < n}\ln k&=n\ln n - n +\sigma-\frac{1}{2}\ln n+\sum_{k=1}^m\frac{B_{2k}}{2k(2k-1)n^{2k-1}}\\
&\qquad+\Theta\frac{B_{2m+1}}{(2m+2)(2m+1)n^{2m+1}}\qquad\qquad 0<\Theta<1
\end{align*}
Another instructive example in section 9.6, namely the asymptotic estimation for $\sum_k\binom{2n}{k}$ provides a formula for $\sigma$
  \begin{align*}
e^\sigma=\sqrt{2\pi}
\end{align*}

Now we have everything we need to estimate $n!$ as precise as we like:

Let's assume we want to approximate $n!$ up to terms of order $n^{-3}$. We put $m=2$ and observe
\begin{align*}
\sum_{1\leq k < n}\ln k=n\ln n-n+\sqrt{2\pi}-\frac{1}{2}\ln n+\frac{1}{12n}-\frac{1}{360n^3}
+\mathcal{O}\left(\frac{1}{n^5}\right)\tag{3}
\end{align*}

Using the generating function of $\exp(x)=\sum_{n\geq 0}\frac{x^n}{n!}$ we obtain from (3)
\begin{align*}
n!&=\exp\left(n\ln n-n+\sqrt{2\pi}+\frac{1}{2}\ln n+\frac{1}{12n}-\frac{1}{360n^3}
+\mathcal{O}\left(\frac{1}{n^5}\right)\right)\tag{4}\\
&=\sqrt{2\pi n}\left(\frac{n}{e}\right)^n
\exp\left(\frac{1}{12n}-\frac{1}{360n^3}+\mathcal{O}\left(\frac{1}{n^5}\right)\right)\\
&=\sqrt{2\pi n}\left(\frac{n}{e}\right)^n
\left(1+\left(\frac{1}{12n}-\frac{1}{360n^3}\right)+\frac{1}{2}\left(\frac{1}{12n}-\frac{1}{360n^3}\right)^2\right.\\
&\qquad\qquad\qquad\qquad\left.+\frac{1}{6}\left(\frac{1}{12n}-\frac{1}{360n^3}\right)^3+\mathcal{O}\left(\frac{1}{n^4}\right)\right)\\
&=\sqrt{2\pi n}\left(\frac{n}{e}\right)^n
\left(1+\left(\frac{1}{12n}-\frac{1}{360n^3}\right)+\frac{1}{2}\left(\frac{1}{144n^2}\right)\right.\\
&\qquad\qquad\qquad\qquad\left.+\frac{1}{6}\left(\frac{1}{1728n^3}\right)+\mathcal{O}\left(\frac{1}{n^4}\right)\right)
\end{align*}
Observe the change from $-\frac{1}{2}\ln n$ to $+\frac{1}{2}\ln n$ from (3) to (4) due to the change from $(n-1)!$ to $n!$.

We finally conclude
  \begin{align*}
n!=\sqrt{2\pi n}\left(\frac{n}{e}\right)^n
\left(1+\frac{1}{12n}+\frac{1}{288n^2}-\frac{139}{51840n^3}+\mathcal{O}\left(\frac{1}{n^4}\right)\right)
\end{align*}
Comment: Very nice answer!
Comment: @OlivierBegassat: Thanks! :-)
Answer: The best way that I'm aware of proving such a result is using a generalization of Laplace's method. The topic is introduced and this paper has an example of using it to obtain the general Stirling expansion:
https://web.cs.elte.hu/blobs/diplomamunkak/msc_mat/2012/nemes_gergo.pdf


Como funciona o retorno undefined?

Question: Quando é declarado uma variável, mas a mesma não possui nenhum valor atribuido a ela, teoricamente ela não possui nenhum dado, mas ela existe na memória e está pronta para ser utilizada:
let myVariable;

Mas ao tentar utilizar está mesma variável como, por exemplo, imprimir o valor dela no console é rotornado o valor undefined:

let myVariable;

console.log(myVariable);

Este valor que foi retornado que é undefined é realmente o valor da variável e no qual a partir daqui o valor desta variável é undefined? ou apenas é um valor para informar que a variável está com o valor indefinido, mas continuar com o valor "nada" na memória do computador?
Isso também acontece, por exemplo, com arrays quando, você utiliza o construtor Array() com um parâmetro númerico inteiro e positivo especificado no qual se for definido, por exemplo, o valor 10 terá 10 posições com valores vazios e no qual se for tentado acessá-lo também retornará undefined:

let myArray  = new Array(10);

console.log(`Posições: ${myArray.length}`);

for (let i = 0; i < myArray.length; i ++) {
    console.log(`Valor da posição ${i}: ${myArray[i]}`);
}

Em uma resposta do bfavaretto ele menciona que:

Note que na verdade a array não está preenchida com undefined; a saída que vemos no console é consequência de como funciona o método toString dela.

Nesta menção ele explica o do porque estar retornando undefined, mas eu não entendi o que ele quis dizer.
Este retorno ele existe apenas para especificar ou confimar que o valor de retorno é undefined?
Answer: undefined é um valor, assim como null também é um valor. O código precisa saber o que é undefined para poder trabalhar com ele.
Uma variável não inicializada é apenas uma região da memória que foi adquirida, mas ainda contém o conteúdo que estava alocado nessa região anteriormente. Não tem como o seu processo saber que esse lixo representa um valor não inicializado, a menos que ele inicialize essa variável com um valor que representa não estar inicializada (isso faz sentido?)
undefined assim como null são ponteiros que apontam para uma região de memória que não deveria ser acessada. Qual região? Geralmente 0x00000000 ou 0x00000001, mas isso é detalhe de implementação, e não cabe a linguagem definir isso.
Quando você declara uma variável mas não a inicializa, o próprio processo irá inicializa-la com o valor undefined. A variável foi de fato inicializada, com um valor que representa não ter sido inicializada pelo programador.
Por outro lado, quando você acessa uma propriedade inválida de um objeto ou de um array, por regra da linguagem JavaScript, você receberá undefined, mas isso não significa que essa região de memória contém o valor undefined, isso é apenas o retorno definido pela regra... o que pode ser um pouco ambíguo.

var arr = new Array(2);
arr[0] = undefined;

console.log(arr[0]);
console.log(arr[1]);

No exemplo acima por exemplo, o array já foi inicializado com a capacidade 2, a propriedade 0 contém o valor undefined, e a propriedade 1 não existe, o que resulta em undefined. Se houver a necessidade de diferenciar um valor undefined e uma propriedade não existente, você precisará recorrer ao operador in:

var arr = new Array(2);
arr[0] = undefined;

for (var i = 0; i < arr.length; i++) {
  if (i in arr) console.log(`A propriedade ${i} existe, e seu valor é ${arr[i]}`);
  else console.log(`A propriedade ${i} não existe, e portanto é retornado ${arr[i]}`);
}
Answer: Antes de mais nada, vale lembrar que Undefined é um dos tipos definidos pela linguagem (assim como String, Number, Boolean, etc). E a especificação diz o seguinte:

The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.

Ou seja, o tipo Undefined possui apenas um valor, que é undefined. E qualquer variável a qual não foi atribuído um valor, tem o valor undefined.
Ou seja, ao fazer apenas let variavel;, a variável possui o valor undefined (e só para deixar mais confuso, ainda existe uma propriedade do objeto global chamada undefined cujo valor é - adivinhe - undefined).

Quanto a arrays, é um pouco mais complicado. Segue explicação baseada nesta resposta do SOen.
O construtor Array(n), quando chamado com apenas um argumento, e este argumento é um número inteiro, retorna um array cujo tamanho (ou seja, cujo valor da propriedade length) é este número.
Mas ao tentar acessar qualquer um dos elementos do mesmo, o retorno é undefined:

let x = Array(2);
console.log(x.length); // 2
console.log(x[0], x[1]); // undefined, undefined
console.log(x);

Obs: na última linha podem haver divergências quanto à saída. Rodando no snippet do site, eu obtive [undefined, undefined], mas próprio console do Chrome, o retorno foi [empty x 2] e no Node foi [ <2 empty items> ].
O que acontece é que, apesar de parecer, Array(2) não é a mesma coisa que [undefined, undefined]. Por exemplo, se mapearmos cada elemento do array para algum valor qualquer, usando map:

console.log([undefined, undefined].map(e => 1));  // [1, 1]
console.log(new Array(2).map(e => 1));

Sobre a última linha, novamente houve a divergência: no snippet do site, a saída foi [undefined, undefined] e no Chrome e Node a saída foi respectivamente [empty x 2] e [ <2 empty items> ].
Enfim, segundo a especificação, o construtor Array(tamanho) só cria um array cujo valor da propriedade length é o tamanho informado, e só. Nenhum elemento de fato foi criado dentro dele.
Por isso ao percorrê-lo com map o resultado continua sendo "2 empty items", pois a especificação diz que map verifica se a propriedade do array (o índice, no caso) existe. Mas o array criado com Array(tamanho) não possui essas propriedades:

function verificarIndices(array) {
    for (let i = 0; i < array.length; i++) {
        console.log(`tem ${i}? ${array.hasOwnProperty(i)}`);
    }
}

console.log('array de undefined');
verificarIndices([undefined, undefined]); // imprime "true" para os índices
console.log('Array(2)');
verificarIndices(Array(2));  // imprime "false" para os índices

console.log(Object.getOwnPropertyNames([undefined, undefined]));  // ['0', '1', 'length']
console.log(Object.getOwnPropertyNames(new Array(2))); // ['length']

O que nos leva a concluir que o array não possui elementos, e undefined é apenas um valor que é retornado quando um elemento não existe. Afinal, é isso que ocorre quando acessamos um índice que não existe:

let x = [1, 2, 3];
console.log(x[999]); // undefined

Por fim, outra forma de ver que o array criado por Array(n) não tem índices (e portanto podemos concluir que não tem os respectivos elementos):

console.log('percorrendo [undefined, undefined]');
for (let i in [undefined, undefined])
    console.log(i); // imprime 0 e 1

console.log('percorrendo Array(2)');
for (let i in Array(2))
    console.log(i); // não imprime nada

console.log('--------');
console.log(Object.keys([undefined, undefined])); // [ '0', '1' ]
console.log(Object.keys(Array(2))); // []

E quanto ao comentário sobre toString, a especificação diz que toString chama internamente o método join sem argumentos. E quando join é chamado sem argumentos, a especificação diz que é usada uma vírgula como separador. O algoritmo também diz que, se o elemento for undefined ou null, é usada a string vazia no lugar. E como já vimos que o acesso aos elementos não existentes de Array(2) retorna undefined, o resultado de toString será um monte de vírgulas (para ser mais preciso, em um array de tamanho N, serão N - 1 vírgulas).
Comment: Então para variáveis o `undefined` existe, mas para arrays só no momento em que o mesmo é acessado?
Comment: @felipecardozo Na verdade acredito que para objetos em geral, ao tentar acessar uma propriedade que não existe, deve ter um "if (não existe) retorna undefined" (e os índices de um array no fundo são propriedades do mesmo). Eu não achei esse trecho da especificação mas tenho quase certeza que deve ter - se eu encontrar, atualizo a resposta
Comment: beleza :), valeu!
Comment: @felipecardozo Não encontrei o trecho da especificação, mas incluí outro exemplo na resposta. Talvez agora fique mais claro que `Array(2)` de fato só seta o tamanho (`length`) mas não cria os elementos
Comment: Valeu, colega! pelo esforço ficou mais claro para mim.

Como funciona o retorno undefined?