Java extends programmatically

Question: I am wondering about replacing Java's 'extends' keyword somehow for dynamically extending a class based on a parameter(file, environment variable, db...basically anything). Is this even possible because playing with class loaders or calling constructors does not achieve this. I am not asking "should I use interface or superclass hierarchy" rather what is extending really mean under the hood in JAVA because there aren't any good description about it just the good old inheritance jargon:
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Comment: This sounds like an XY problem of epic proportions. Please state the problem you are trying to solve, and not some intermediate step to solving it. The short answer here is a resounding no. The longer answer is yes, this is possible, but would require extensive and errorprone load time weaving.
Comment: @Zoltan: If you can provide a concrete example of what you're doing and the limitations you're running into (in another question, this question has already sailed), people can provide concrete suggestions for dealing with those limitations. Open-ended "what is `extends`" probably won't help you with those issues.
Comment: And what would you do in the class on the basis of this parameter? Why can't you just have multiple instances of a class for the different parameters? (The short answer is: no, you can't. Inheritance is a property baked into a class at compile time)
Comment: Why do you want to do that? Is this for something like a dynamic proxy?
Comment: @AndyTurner maybe annotating and reflecting?
Comment: Currently I have multiple classes as you said but I want to generalize the solution. My dream is to make a parent class for test classes and there are situations when you need forexample extend AbstractTestNGSpringContextTests or PowerMockTestCase for heavy mocking arsenal (I know that using powermockito is a bit too heavy weapon for mocking but in legacy code you need it sometimes). This could be somehow parameterized in order to dynamically extend the proper test parent class.
Comment: What is the problem that you are solving? It seems to me that your problem can be solved by composition rather than inheritance.
Comment: @Zoltan Use some kind of delegation or strategy pattern instead of inheritance. Extract functionality you want to provide in multiple parent classes into interface and pass specific instance of it to your test class. If you really cannot stand calling 'impl.method' instead of 'method' you could then wrap it in common superclass which will delegate all calls to provided implementation and extend that class yourself, but it is probably not worth for saving few characters.
Answer: The only way to "replace the extends keyword" is to dynamically create classes at runtime, which is entirely possible but non-trivial. Vert.x is a good example of a project that makes extensive use of dynamically-generated classes.
Java wasn't designed as a dynamic language in that sense. There are several dynamic languages out there (some of which can run on the JVM), such as JavaScript.

rather what is extending really mean under the hood...

Without getting into a long treatise on OOP, when you say Derived extends Base, it means that Derived inherits both the public and protected API of Base (which it can then add to) and also the implementation of that API. It means that code expecting to see a Base instance can accept a Derived instance, because Derived "is a" Base. This link is created a compile-time. At runtime, instantiating an instance of Derived involves all of the plumbing that instantiating a Base instance involves, plus then the added plumbing for Derived.
Comment: Thanks for the answers, I will look into this Vert.x project.
Answer: You can't do that with a language like Java. The information about "inheritance" is not only used by the compiler, it is also "hard-baked" into the compiled byte code.
If you really want to such kind of "dynamic" meta programming; you are better of using languages that allow you to do so; instead of "violating" a language that was never intended for such kind of usage.
To use some stupid comparison: just because you happen to know "screws" and "hammer" ... you wouldn't start to use a hammer to get those screws into the wall, would you? Instead, you would be looking for a tool that works better with "screws" than a hammer.
If you still want your code to run within a JVM; you might consider languages like jython or jruby.
Answer: To achieve this you need to maintain various versions of a class based on the condition and you have to customise class loader as well because at a point when you find that you have to load a particular instance, you need to load that class which is not loaded by default class loader on JVM startup.
Its better to maintain multiple versions of the class and let JVM do its job which it does perfectly.

Java extends programmatically


is it correct or no? ROLLEDBACK AND COMMIT

Question: it's about COMMIT statement and ROLLBACK statement in SQL
I know that the ROLLBACK statement is the inverse of COMMIT statement.
what if we said "The COMMIT statement is the inverse of ROLLBACK statement"
Is it correct or no? if it's no explain it please
thank you for help
Comment: No it is not the same.  if you rollback, there is nothing to commit afterwards until you perform some more DML
Comment: Neither is the "inverse" of the other. Once you did a commit, you can not rollback. And once you did a rollback, you can't commit. You can only say one is the opposite of the other
Answer: From SQL Server's perspective the usage of 'inverse' may be misleading with "nested" transaction

COMMIT:
Marks the end of a successful implicit or explicit transaction.
ROLLBACK:
Rolls back an explicit or implicit transaction to the beginning of the transaction, or to a savepoint inside the transaction.

Example:
BEGIN TRAN
BEGIN TRAN
SELECT 'sth';
COMMIT;
SELECT @@TRANCOUNT;
-- 1

vs
BEGIN TRAN
BEGIN TRAN
SELECT 'sth';
ROLLBACK;
SELECT @@TRANCOUNT;
-- 0 (nothing to commit)

db<>fiddle demo


Autowire variable only if it was not set in constructor

Question: I have spring Bean class like this:
 public class A{

    @Autowired
    private B b;

    @Autowired
    private C c;

    @Autowired
    private D d;

    public A(){
     }

    public A(B b){
      this.b = b;
    }

    }

I have some spring xml bean configuration files that initialize B class, but I have also spring java configuration class that initialize A class like this:
@Configuration
public AConfigurator(){

@Bean
public A create(){
   B b = new B();
  A a = new A(b); //I set specific B instance
return a;  //my already set b property will be overried(with the bean B that has already been created in the spring context by another xml configuration) by the spring when autowiring the properties
}
}

My problem is that when create metods return A, the spring will autowired the properties even if the properties has been already setted. It will overried the already setted b property. I want to autowired only the properties that were not set in the constructor. Is it possible to do it in Spring?
Comment: don't use new when you `DI` this is the goal of this pattern to avoid using new
Comment: I completely agree @YCF_L ... either use a DI framework, or you don't. That's like flying a Boeing 737 and having the auto-pilot going while also trying to control the thing yourself. Might not end well ...
Comment: @YCF_L There is nothing wrong with new in spring configuration class. The B is not spring Bean, doesn't have  to be spring intercepted. On the other hand, the A is the spring Bean and its created via the spring configuration class.
Comment: if you only have 1 constructor in a component it is automatically autowired. Perhaps try adding a second constructor to your A class and see if this resolves the problem. Let me know if it does and we can take it from there.
Comment: @Pete I forgot to put there default constructor, when I writed the question. I added the default constructor, but it doesn't solved the problem. My question is if is possible in Spring to autowired only the properties that are null, there has not been setted in constructor.
Comment: @GhostCatsaysReinstateMonica I don't understand what you mean. I use DI framework, the configuration class is part of Sprint init context. In your @_Bean method you can create  new instance of the classes.  For example B can ba inteteger you definitely can do new Integer(10) and is nothing wrong with it, to intercept Integer to be spring bean doesnt make sense.
Answer: I would highly suggest re-considering how you are using autowired and injection to achieve DI. You shouldn't allow class A to know ANYTHING about DI. allow all wiring to be done in your configuration class. You could accomplish this by auto-wiring the dependent classes in the @Configuration class. Then using them in the constructor for A. This ends up looking like
class A:
public class A{
    private B b;
    private C c;
    private D d;

    public A(B b,
            C c,
            D d){
        this.b = b;
        this.c = c;
        this.d = d;
    }
}

Then constructing it in the AConfigurator class like:
@Configuration
class AConfigurator {

    @Autowired
    private B b;

    @Autowired
    private C c;

    @Autowired
    private D d;

    @Bean
    public A create(){
        return new A(b, c, d);
    }
}

Comment: Its Spring 3 application, and A is @Component that is created by Spring when Spring auto-scan for components, so there is nothing wrong with @_Autowired annotation in A class, I can not change that class.  I only trying to find out if is possible in Spring to Autowired the property only if the property has not been set in constructor and is null.


Intuition about the rules of integration?

Question: It makes complete sense to me that if you want to find the area under a curve you can chop it up into rectangles and as the width of the rectangles approach 0 you can sum them and get the correct area with this equation:
$$lim_{{n \to \infty}} \sum_{i=1}^{n} f(x)dx$$
My question is how do the rules of integration give me the area. For example how does the upper bound of the integral give me the entire area under the curve up until that point(just exclude the lower bound for now for simplicity) I can't picture how using these rules of integration for the upper bound give me the super tiny rectangles and sums them to give me the area.
Comment: By "the rules of integration" are you referring to the methods of finding an antiderivative?
Comment: @WW1 Yes I don't understand how adding one to the exponent and dividing by the new when plugging in the upper bound gives me the sum of all rectangles
Comment: just referencing a integration technique for a simple example
Comment: @Stef: That, and how, those areas can be computed by such antiderivatives is nothing less than the [Fundamental Theorem of Calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). That's not a trivial statement you or anyone is expected to see "intuitively" on first or second glance. It took me years to grasp its full meaning.
Answer: The formula you wrote down isn't very meaningful until you have defined what $f(x)\mathrm{d}x$ means. A more precise definition of the integral might resemble: $$\int_a^bf(x)\mathrm{d}x=\lim_{n\to\infty}\sum_{k=1}^nf\left(a+\frac{(b-a)k}n\right)\cdot\frac1n.$$It is easier to gain an intuition from this starting point: $a+\frac{(b-a)k}n$ is the horizontal position of the $k$th rectangle we draw between $a$ and $b$, and $\frac1n$, which tends to zero, is the width of the rectangle we are measuring. As a simple example, $$\int_0^1x\mathrm{d}x=\lim_{n\to\infty}\sum_{k=1}^n\frac{k}n\cdot\frac1n=\lim_{n\to\infty}\frac{\frac12n(n+1)}{n^2}=\lim_{n\to\infty}\frac12+\frac1{2n}=\frac12$$(which is the same result as you would obtain using the power rule and evaluating $\frac{x^2}2$ at $0$ and $1$).


ProxyPassReverse

Question: our IT is trying to configure a new apache/jboss/apj setup. When I browse to  http://domain.com/jboss/test.jsp
and echo out the request.getRequestURL()
I get
http://domain.com/test.jsp
(without jboss) My deployed app encounteres a lot of 404's because of this.
This is what our IT department has the ProxyPassReverse set to.
<Location /jboss>
    ProxyPass balancer://cluster stickysession=JSESSIONID
    ProxyPassReverse https://domain.com/jboss/
</Location>

Shouldn't the directive be set to:
<Location /jboss>
    ProxyPass balancer://cluster stickysession=JSESSIONID
    ProxyPassReverse /jboss https://domain.com/jboss/
</Location>

Edit
The issue arrises when I use
response.sendRedirect
On our old server I used
response.sendRedirect("login.jsp?message=You have successfully logged off.");
to get things to work with the new proxy I have to recode as
response.sendRedirect("/jboss/AppName/login.jsp?message=You have successfully logged off.");
My applications are no longer portable or reuseable with the latter syntax.  That line is in an my framework servlet for logging out and is shared by all of my apps.
The error (in Apache, not jboss) for
response.sendRedirect("login.jsp?message=You have successfully logged off.");
File does not exist: /folder1/folder2/AppNamelogin.jsp`
Note there is no "/" between my appname and login.jsp
The error (in Apache, not jboss) for
response.sendRedirect("/login.jsp?message=You have successfully logged off.");
File does not exist: /folder1/folder2/login.jsp
Note the AppName is missing
Comment: Is the JBoss-server setup with the `/jboss` context?
Comment: I beleive so but I don't have access to directly view the apache configuration.  I'd have to ask IT but they always seem annoyed when developers ask them questions :) I'd like to just tell them here is what ProxyPassReverse should be set to.
Answer: Nope; the first argument is implied when used in a <Location> block.  That usage is correct.
ProxyPassReverse serves only to translate the Location header on a 30x redirection response; it's probably not the issue, given what you've described.
You should clarify exactly what the path should be set to.  If I understand you right, the request should be sent to domain.com/jboss/test.jsp instead of the current domain.com/test.jsp, right?  If that's the case, then just change..
ProxyPass balancer://cluster stickysession=JSESSIONID

..to..
ProxyPass balancer://cluster/jboss stickysession=JSESSIONID

Edit
Leaving the above in place, but the new information presented makes it clear that the problem is indeed with the ProxyPassReverse - the balancer configuration probably has the /jboss path in the BalancerMember configs.
Change..
ProxyPassReverse https://domain.com/jboss/

..to..
ProxyPassReverse https://domain.com/jboss

The slash is being stripped when the Location translation is occurring, sending the client a redirect to /jbossappname instead of /jboss/appname, due to the imbalanced trailing slashes between the <Location /jboss> and the ProxyPassReverse.
Comment: Shane. Correct. I expect the request.getRequestURL() to have jboss in the url. Or in other words what ever URL is typed in the Address bar, request.getRequestURL() should return an exact match. IT has our AS7 apps pointing to https://domain.com/jboss/App1 https://domain.com/jboss/App2
Comment: @jeff Right, but does it actually need to be on the non-`/jboss` path for the actual request to the JBoss server to map to the correct context path for your web application?  If it needs to have the path throughout, then make the change recommended in my answer and all should be well, but I'm confused at how the application code is even handling the request at all if an important part of the URL path is completely missing.
Comment: Not sure how to answer that.  I have edited my question to facilitate.
Comment: @jeff Ahh, then it is indeed an issue with the `ProxyPassReverse`.  See the edit to my answer.
Comment: Shane thanks I really appreciate you helping. But the error in apache never mentions /jboss as in /jbossappname. I was trying to anonymize my path, maybe a bit too much. file not found is more like this /WEB/wwws/appnamelogin.jsp
Comment: so.. I need clarification, do I change both ProxyPassReverse and ProxyPass? Didn't understand what you meant by "Leaving the above in place". Thanks!!!
Comment: @jeff What I meant by that is that I was going to leave the old version of the answer there instead of editing it out completely - but that difference in the path changes things.  Something doesn't add up - none of this config should be capable of removing the slash from that part of the URL string, in addition to having removed the `/jboss` from the path.  Is there any way you can get a more complete picture of the config?  Of particular interest is what's going on in the `` section, as well as any other `ProxyPass` or `ProxyPassReverse` settings.

ProxyPassReverse


Comparing two predictor variables in linear regression, importance of rsquared

Question: I have a linear regression model which goes something like this:
$Revenue=c+x1+x2+x3+.......x15$
What I am interested in is two of these predictor variables, lets say x1 and x2, as I want to see which one of them has the greatest impact on the dependent variable (Revenue).
I have produced a linear regression model in R which is as below:
$Revenue=c+x1+x2$
I get an R-squared value of 0.49. I can see from the coefficients, that x1 has a much larger coefficient (5.2), than x2(3.1).
My question is, is this a valid inference to make from the model with a low R-squared? If I add further variables to the model e.g x3, x4, x5, I get a greater rsquared value and thus the coefficient values change. Would the model with the greater rsquared value be better to make comparisons between the two predictor variables, or will the simpler model which contains only the two variables of interest be better?
Answer: First, R² is a bad statistic if you want to know which model will make the best (out-of-sample) predictions or which model gives you the best inference about predictors. R² will get larger with adding more variables (even if these additional variables are independent and random, having no relation whatsoever with the outcome), but you might just overfit, i.e., fitting noise and sampling variation as if it were informative.
The question which of the predictors is more informative is still underspecified: more important in explaining the data you see (potentially even causally), or most important in making accurate out-of-sample predictions? These are different questions.
I would recommend you first get a valid model which makes sense, judged by a model fit criterion like AIC, WAIC, BIC, or via cross-validation, but also judged by your background knowledge. You will then see whether your model selection procedure retains both variables you are interested in. You can also do explicit comparisons of models with vs. without these variables, for example via likelihood ratio tests or the previously mentioned information criteria.
If your best model contains both variables, then you might want to compare coefficients. Make sure the ones you compare are on the same scale (e.g., normalize them) and take into account their uncertainty (for example via confidence intervals, p-values, credible intervals, ...). But be sure to acknowledge that your conclusions depend on the specified model, which is why this should be the first thing you tackle.
Answer: It is fine to do parameter inference when $R^2$ is low. When you do a two-sample t-test (equal variance), you are doing regression parameter inference, and a quick simulation would show you that you have low $R^2$ in many situations where you would be completely comfortable t-testing.
Whether or not you should add additional predictors will depend on your goals. You might be able to explain some variability in the response by adding more predictors. You also run the risk of muddying the interpretation, particularly if you include predictors that are not independent of the two predictors of interest. Further, adding many predictors runs the risk of overfitting and just memorizing the data instead of modeling the phenomenon.
Finally, be a little cautious about just looking at the parameter estimates. Also consider their scales. Interpretations are quite different if your variable is in kilometers than if it is in nanometers. Look at standard errors of the parameters. If neither  parameter estimate is significantly different from zero, or if their confidence intervals contain one another, you have scant evidence that the values are different. Perhaps the best way to assess which is more impactful would be to do a linear contrast that would give you a confidence interval for the difference between parameters.
EDIT
I like what stefgehrig says about assessing model fit with a metric other than $R^2$. The trouble with other metrics like the AIC mentioned is that it is hard to judge what a good values is. Adjusted $R^2$ or out-of-sample $R^2$ could be easier to interpret. However, do not fret about using a model with an $R^2$ of $0,30$ or even lower. You might be thinking that explain $30\%$ of the variability in the response is a terrible mode since you grew up thinking that a $90\%$ or so was an $A$ and you want to write $A+$ models, but especially for inference, it is fine not to explain a great deal of variability. As I mentioned in my first paragraph, this is routine in vanilla t-testing.


Invalidating Paragraph Cache

Question: I'm working on a paragraph type that will need to display on a very limited number of pages but has some specific functionality where the preprocess function will need to run each time.
In my preprocess function, I've tried various iterations of the following:
$variables['elements']['#cache']['max-age'] = '0';
$variables['elements']['#cache']['contexts'][] = 'url.path';
$variables['elements']['#cache']['contexts'][] = 'url.query_args:r';
$variables['elements']['#cache'] = ['tags' => ['my_paragraph']];
Cache::invalidateTags(['my_paragraph']);
\Drupal::service('page_cache_kill_switch')->trigger();

However, the preprocess function runs once after a cache clear and then doesn't run again.
What am I doing incorrectly here? How can I get this to run each time?
Comment: I'd recommend making a step back and start to explain the `specific functionality where the preprocess function will need to run each time`.
Answer: My understanding is that you're trying to set a cache max-age of 0 (don't cache) for a paragraph. I think your issue here is that the max-age doesn't bubble up to the page level and the page cache still caches your paragraph. This makes it so your paragraph is not processed again.
My understanding is that cache max-age data doesn't bubble up to the page level from subelements. There are a couple open issues on d.o for this.

https://www.drupal.org/project/drupal/issues/2352009
https://www.drupal.org/node/2499321

To me, it looks as though this is something that may not be resolved in core for a while (or maybe ever?). There is a contributed module, Cache Control Override that will bubble up the correct cache data to the page level. From the module's description:

In Drupal 8 core Page Cache max age settings are applied globally to
  all pages, and there is no way to set a different max age per page or
  leverage cache metadata max-age to override Cache-Control max-age
  value. This means that if you're hosting your website behind a reverse
  proxy that honors Cache-Control header, all pages are cached with
  equal TTL. You can either disable cache with response policies, or
  cache it for the same global value.
This module is intended to solve that problem by leveraging
  cacheability metadata bubbled up to the page response level to
  override Cache-Control max-age parameter.

If you install the Cache Control Override module, then set the max-age in your preprocess function, e.g. $variables['elements']['#cache']['max-age'] = '0';, you should see your preprocess run every page load. However this will also ensure your pages with your paragraph never get cached at the page level. This could be a problem.
Depending on your site, it may be more prudent to use an alternative solution and render a placeholder in your paragraph and then use an ajax request to load the dynamic data into the placeholder. This will allow your full pages to stay cached while also allowing you to load dynamic data into your paragraph.
Comment: This approach (installing the Cache Control Override module, then setting max-age to 0) did not work for me in Drupal 9.1.8. I've tried it with and without the subsequent call to \Drupal::service('page_cache_kill_switch')->trigger().
Comment: Actually, I just tried $variables['#cache']['max-age'] = '0' (no "['trigger']"), as shown in Himanshu Sindhwani's answer – and that *does* seem to work.
Answer: You've got a logic error in your PHP. You're doing the following and setting some variables:
$variables['elements']['#cache']['max-age'] = '0';
$variables['elements']['#cache']['contexts'][] = 'url.path';
$variables['elements']['#cache']['contexts'][] = 'url.query_args:r';

But then in the next line you're redeclaring $variables['elements']['#cache'] as a new array of  ['tags' => ['my_paragraph']]; So everything you were doing previously in the
$variables['elements']['#cache'] is now gone
So your max-age declaration doesn't exist now. Try with just these 2 items and that should be all you need. The first to tell drupal not to cache the paragraph. The 2nd to disable anonymous page caching as setting max-age 0 doesnt disable the page cache:
$variables['elements']['#cache']['max-age'] = '0';
\Drupal::service('page_cache_kill_switch')->trigger();

Comment: I've read it as a list of things OP tried. But who knows...
Comment: Ah yes potentially
Answer: function themename_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  if ($paragraph->bundle() === 'your_para_machine_name') {
    $variables['#cache']['max-age'] = 0;
  }
}

after adding this code clear the cache.
Answer: This worked for me. The idea behind is to invalidate both node and paragraph entity caches.
$variables['elements']['#cache']['max-age'] = '0';
Cache::invalidateTags(['paragraph:' . $par->id()]);
Cache::invalidateTags(['node:' . $node->id()]);
\Drupal::service('page_cache_kill_switch')->trigger();

The context is hook_preprocess_paragraph__TYPEID(&$variables)

Invalidating Paragraph Cache


Check if remote mysql query was successful - bash

Question: When using a bash script to execute remote MySQL queries, how can I know if the command was successful or not. Locally it would return an exit code. However, remotely it seems to send the query and  if it is able to connect to the remote MySQL database it takes it as successful. Is there any way to view the output when executing remotely, like when executing locally. Here is the script:
#!/bin/bash

RemoveID=`mysql -u root -proot -h 192.168.1.56 -e "delete from table where ID = '$1'"`

Answer: SELECT statements will return number of rows into your shell variable.
For DELETE statements just append a SELECT ROW_COUNT() after your mysql query, so it would be in your example like:
RemoveID=`mysql -u root -proot -h 192.168.1.56 -e "delete from table where ID = '$1';select row_count()"`

echo $RemoveID
ROW_COUNT() 1
Answer: You could run a follow up query to check for the deleted ID in the script.


Lua with Luabind compilation error c++

Question: I can't get it to work.
Here is my code, I kept it as simple as possible :
<code>#include <iostream>
#include <lua/lua.hpp>
#include <luabind/luabind.hpp>
#include <luabind/class.hpp>

class           MyClass
{
public:
  MyClass() {}
  ~MyClass() {}
  void          myFunc() { std::cout << "Hi !" << std::endl; }
  int           getMyVar2() { return (this->myVar2); }
  int           myVar;
private:
  int           myVar2;
};

int             main()
{
  MyClass       *m = new MyClass();
  lua_State     *L = luaL_newstate();

  luabind::open(L);
  luabind::module(L)
    [
     luabind::class_<MyClass>("MyClass")
     .def("myFunc", &MyClass::myFunc)
     .def("getMyVar2", &MyClass::getMyVar2)
     .def("myVar", &MyClass::myVar)
     ];
  luabind::globals(L)["globalName"] = m;

  if (luaL_dofile(L, "example.lua"))
    fprintf(stderr, "%s\n", lua_tostring(L, -1));
  lua_close(L);
}
</code>
The compiler gives me alot of garbage information, and by redirecting the output, i see first :
<code>/usr/local/include/luabind/class.hpp: In instantiation of 'void luabind::detail::memfun_registration<Class, F, Policies>::register_(lua_State*) const [with Class = MyClass; F = int MyClass::*; Policies = luabind::detail::null_type; lua_State = lua_State]':
exemple_luabind.cpp:48:1:   required from here
/usr/local/include/luabind/class.hpp:311:52: error: no matching function for call to 'deduce_signature(int MyClass::* const&, MyClass*)'
</code>
Line 48 is :
<code>}
</code>
Can anyone help me please ? I'm sure it is a beginner mistake..
Answer: You may not declare attributes with .def since it's only used for functions.
Depending on how you want to access your class members you can use different approaches:
<code>luabind::module(L)
        [
            luabind::class_<MyClass>("MyClass")
            .def("myFunc", &MyClass::myFunc)
            .def("getMyVar2", &MyClass::getMyVar2) // function with MyClass:getMyVar2()
            .property("myVar2", &MyClass::getMyVar2) // MyClass.myVar2 is only readable, same as MyClass:getMyVar2()
            .property("myVar", &MyClass::myVar) // MyClass.myVar is only readable
            // vs
            .def_readwrite("myVarT", &MyClass::myVar) // MyClass.myVarT is read and writable
        ];
    luabind::globals(L)["globalName"] = m;
</code>
Check the doku for a detailed explanation: LuaBind Documentation
Comment: Hi,

Thank you !
I used .def for a variable and that gave me a compilation error.
I didn't know that .property.
Thanks again!

Lua with Luabind compilation error c++


qmp-shell doesn't recognize commands

Question: So, there is a python script that allows to connect to QEMU monitor from a usual shell. I had to download a bunch of files from the QEMU source tree, and add -qmp unix:./qmp-sock,server,nowait to the vm command line. It connects, but I can't get it working.
$ qmp-shell qmp-sock
Welcome to the QMP low-level shell!
Connected to QEMU 1.5.3

(QEMU) help
{u'error': {u'class': u'CommandNotFound', u'desc': u'The command help has not been found'}}
(QEMU) query-
query-balloon               query-fdsets                query-status
query-block                 query-kvm                   query-target
query-block-jobs            query-machines              query-tpm
query-blockstats            query-mice                  query-tpm-models
query-chardev               query-migrate               query-tpm-types
query-command-line-options  query-migrate-cache-size    query-uuid
query-commands              query-migrate-capabilities  query-version
query-cpu-definitions       query-name                  query-vnc
query-cpus                  query-pci
query-events                query-spice
(QEMU) query-kvm
{u'return': {u'enabled': True, u'present': True}}
(QEMU) info block
Error while parsing command line: list index out of range
command format: <command-name>  [arg-name1=arg1] ... [arg-nameN=argN]
(QEMU) info
{u'error': {u'class': u'CommandNotFound', u'desc': u'The command info has not been found'}}
(QEMU) exit
{u'error': {u'class': u'CommandNotFound', u'desc': u'The command exit has not been found'}}
(QEMU)

Answer: Assuming that the qmp-shell works the same way as, say, telneting to QMP socket and sending JSON commands directly, you need to issue the qmp_capabilities command.
None of the other commands in qmp will work until it has been executed, and will result in the 'CommandNotFound' error quoted.
See qemu wiki page regarding QMP for details.
Comment: That was a wrong assumption. qmp-shell does negotiation by itself. Moreover, as you could see above, some commands do work, e.g. `device_add driver=e1000 id=net1` prints `{u'return': {}}` and `quit` closes virtual machine.
Comment: Thanks for that additional information @tijagi about qmp-shell doing the negotiation. The details of the return codes from "device_add" and "quit" commands weren't present in the original post though. It might be worth adding those additional details.
Comment: There's a query-kvm command, that works as well as device_add in this case.

qmp-shell doesn’t recognize commands


Cheaper way to transfer two domain names to Go Daddy

Question: I, like anyone else, am a cheapskate. The thought of paying $20–$25 per domain to the previous owner plus a $7.49 transfer fee on each to Go Daddy makes me cringe a little, because it would be only about $22 to just register the domains from scratch (if they weren't already registered).
Sure, Go Daddy provides a free one-year renewal on each transfer, so there's some value there, but I'm still wondering if there's a way to transfer the domains to my control without paying any transfer fees.
Answer: As long as the whois records haven't changed in the past 60 days, and the previous owner has paid up, there is no reason you can't move the domain to a new domain register. You'll need the EPP key, and he'll have to "unlock" the domain so it can be transferred.
Next, you'll request the transfer and enter the EPP key on your domain register of choice, and when he approves the transfer, it will go through.
Comment: Sure I'll request the transfer, but from whom do I request it and how much will it cost? Can I lower the cost?
Answer: As direct00 said, you have to paid the former registrar, there's no way ot work around this.
They now you have to paid them, so they take advantage of you and charge you as if you were renewing or even more sometimes....
Comment: So I'd have to pay 1&1, not Go Daddy? Now I'm even more confused.


Experimental Design: Number of treatments and replications

Question: I am learning about experimental design. I have been provided the following definitions:

Factors: Variable(s) manipulated by researchers in order to observe response(s)
Levels: Values of factors
Treatments: Combinations of level of factors, applied to experimental units

I am trying to apply this knowledge to the following problem:

To study how different nutrients effect plant growth, 120 seedlings were placed in individual pots. The 120 pots were randomly divided into 3 groups of 40 each and a different plant nutrient (A, B, or C) was applied to the soil in the pots. After 10 days of growth, 10 pots were randomly selected from each group and the plants weighed. The same was done at 20 days, 30 days and 40 days of growth and the weight of each plant measured and recorded.

I am trying to determine the number of factors and treatments. Here is my thinking:

There are 2 factors ("Plant Nutrient" and "Growth Time"). There are 12 Treatments (A10, A20, A30, A40, B10, B20, B30, B40, C10, C20, C30, C40). In this case, there are 10 replications in each treatment.

However, I wonder if instead I should see it this way (because our main goal is to see the differences between the plant nutrient, and we are simply taking into account different times within that):

There is 1 factor ("Plant Nutrient"). There are 3 Treatments (A, B, C). In this case, there are 40 replications in each treatment.

Which of these approaches may be more sound? And if neither, how should I approach it differently?
Answer: You could start by writing down a model, which could be:
$$
  Y_{ijk} = \mu +\alpha_i+\beta_j + (\alpha\beta)_{ij}+\epsilon_{ijk}
$$
where $i=A,B,C$, $j=10,20,30,40$ and $k=1, \dots, 10$.  $(\alpha\beta)$ represents the interaction.
You give two ways to look at this. Both seem reasonable, but, even if the real interest only is in the plant nutrient factor, time obviously also must be modeled, so I would say you should follow your first proposal.
You could also see this as a "growth curve" experiment, look at  https://stats.stackexchange.com/search?q=growth+curve    for some postings about that at this site.
It could well be that interest does not only center on the nutrient, but also in differences in the growth curves, so it could be of interest to parametrize the model differently, with a covariate $x$ measuring days of growth (with values 10, 20, 30, 40) like this:
$$
  y_{ijk} = \mu +\alpha_i +\beta x_{ik} +\epsilon_{ik}
$$
(version without interaction ... ). Here $i=A,B,C$, $k=1,2\dots,40$.
In this version we only assume linear growth, you can augment it with a quadratic term, or replace it with a spline model.


Calculation of Christoffel symbols of Schwarzschild metric using Lagrangian

Question: I know that the Schwarzschild line-element is:
$$ds^2=c^2\left(1-\frac{2\mu}{r}\right)dt^2-\left(1-\frac{2\mu}{r}\right)^{-1}dr^2-r^2d\theta^2-r^2\sin^2\theta d\phi^2$$
Dividing by $d\lambda^2$, where $\lambda$ is an affine parameter, I get:
$$\left(\frac{ds}{d\lambda}\right)^2=c^2\left(1-\frac{2\mu}{r}\right)\dot{t}^2-\left(1-\frac{2\mu}{r}\right)^{-1}\dot{r}^2-r^2\dot{\theta}^2-r^2\sin^2\theta \dot{\phi}^2$$
where $\dot{X}$ is $\frac{dX}{d\lambda}$.
To my understanding, this is the Lagrangian, so Euler-Lagrange equations hold.
So I must have:
$$\frac{d}{d\lambda} \left( \frac{\partial L}{\partial \dot{\phi}} \right)=\frac{\partial L}{\partial \phi}$$
Evaluating LHS: $-2r^2\sin^2\theta\ddot{\phi}$.
RHS: $\frac{\partial L}{\partial \phi} = 0$.
Ie: $\ddot{\phi}=0$
Geodesic equation for $\phi$:
$$\frac{d\phi^2}{d\lambda^2}+\Gamma^{\phi}_{\mu\nu}\frac{dx^\mu}{d\lambda}\frac{dx^nu}{d\lambda}=0$$
So I conclude that $\Gamma^{\phi}_{\mu\nu}$ for any $\mu, \nu$.
This, however, is in conflict with what I find on the internet. Equation 5.4 from here, Wikipedia, disagrees with this result.
What am I doing wrong?
Answer: Perhaps should be moved to physics stackexchange?
Commend you for trying to re-derive the equation of motion directly from the length geodesic for the Schwarzchild metric, but you applied the EL equations incorrectly. The "Lagrangian" in this case is a function of more than just $\phi$. It is also a function of $t$, $r$, and $\theta$, since each of these are functions of $\lambda$, so you would need to set up reciprocal equations of motion for these coordinates.
Comment: Thanks! Maybe will try on Physics, good idea.


O que significa o operador "|="? (com pipeline e não exclamação)

Question: Estava fazendo algumas pesquisas e deparei com o operador em sequencia |=. Vejam:
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;

Existe este operador no JAVA, mas não sei exatamente se segue a mesma sintaxe em outras linguagem e fiquei na dúvida.
O que significa o operador |=?
Answer: Isso aplica o operador bitwise or a mBuilder.getNotification().flags e Notification.FLAG_AUTO_CANCEL e atribui o resultado a mBuilder.getNotification().flags.
É o equivalente a:
mBuilder.getNotification().flags = mBuilder.getNotification().flags | Notification.FLAG_AUTO_CANCEL;

O operador binário OR, ou disjunção binária devolve um bit 1 sempre que pelo menos um dos operandos seja '1'
Exemplo:
int a = 60; //   60 = 0011 1100
int b = 13; //   13 = 0000 1101
int r = (a|b) // 61 = 0011 1101


Display Progress bar while recycler view is clicked

Question: I have an app which displays content of a post while the recycler view is clicked it opens a new activity
<code>        @Override
    public void onClick(View v) {

        int position = getAdapterPosition();
        FeedItem feeditem = this.feeditem.get(position);
        Intent intent = new Intent(this.ctx, ContentActivity.class);
        intent.putExtra("posturl", feeditem.getPostUrl());
        intent.putExtra("Author",feeditem.getAuthorname());
        intent.putExtra("excerpt",feeditem.getExcerpt());
        intent.putExtra("content",feeditem.getContent());
        intent.putExtra("title",feeditem.getTitle());
        intent.putExtra("date",feeditem.getdate());
        intent.putExtra("thumbnail",feeditem.getAttachmentUrl());
        this.ctx.startActivity(intent);

    }
</code>
all i want to acheive is put a progress bar for at least 3 seconds before the other activity is being displayed thanks.
Comment: Looks like you asked the same question before lol: http://stackoverflow.com/questions/41808057/how-to-set-progress-bar-when-recycler-view-is-clicked
Comment: do you have the answer or not?
Answer: <code>Intent intent;  //declare global
ProgressDialog progress; //declare global because before start activity dismiss the dialog
 @Override
    public void onClick(View v) {

        int position = getAdapterPosition();
        FeedItem feeditem = this.feeditem.get(position);
         intent = new Intent(this.ctx, ContentActivity.class);
        intent.putExtra("posturl", feeditem.getPostUrl());
        intent.putExtra("Author",feeditem.getAuthorname());
        intent.putExtra("excerpt",feeditem.getExcerpt());
        intent.putExtra("content",feeditem.getContent());
        intent.putExtra("title",feeditem.getTitle());
        intent.putExtra("date",feeditem.getdate());
        intent.putExtra("thumbnail",feeditem.getAttachmentUrl());

//here start the progress bar

        progress = new ProgressDialog(this);
        progress.setMessage("Loading...");
        progress.setCancelable(false);
        progress.show();

        //set the timer here for 3 second
        Timer t = new Timer();
        t.schedule(new waitingtimer(), 3000);

    }

    //here is the class of timer
    private class waitingtimer extends TimerTask {
            @Override
            public void run() {

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                        progress.dismiss();
                        //here start the activity
                        this.ctx.startActivity(intent);
                    }
                });
            }

  }
</code>
I hope it work for you.
Happy Coding.
Comment: thanks for replying but i was looking forward to a progress bar not a progress dialog. Thanks


Convergence of $\Gamma(p)$ for $0<p\leq 1$ and divergence for $p \leq0$.

Question: Can someone show me a proof or any clear resource about convergence of gamma function for values of $p$ less than zero.
If possible I need proofs using integration by parts.
My problem evaluating convergence is below.
$\displaystyle\int^\infty_0 e^{-x} \hspace{1 mm}x^p \ dx$  and $p<0$
Why does this integral not converge for $p \le -1$, but converge for $-1<
p\le 0$
A proof using series or integrals (like an integral smaller than other convergent integral is convergent) would be appericiated.
Comment: The problem is around the zero, because of the function $x^p$ in $(0,\varepsilon)$ is not integrable for $p\leq -1$.
Answer: The integrand is non-negative, and the problem is only at $0$.
Since $\lim_{x\to 0^+}e^{-x}=1$, we have $3\cdot 2^{-1}\geq e^{-x}\geq 2^{—1}$ for $x\leq x_0$, and so $3\cdot 2^{-1}x^p\geq e^{-x}x^p\geq 2^{-1}x^p\geq 0$.
Since for $p\leq -1$ the integral $\int_0^1 x^pdx$ is divergent, then $\int_0^{+\infty}e^{-x}x^pdx$ is divergent and, if $p>-1$, the integral $\int_0^1 x^pdx$ is convergent and so is $\int_0^{+\infty}e^{-x}x^pdx$.
Answer: Basically, given $p\leq0$
$$\Gamma(p)=\int\limits_0^1 x^{p-1} e^{-x} dx+\int\limits_1^\infty x^{p-1} e^{-x} dx$$
There is no convergence problems for $\displaystyle \int\limits_1^\infty x^{p-1} e^{-x} dx$, however, for $0&lta&lt1$
$$\int\limits_a^1 x^{p-1} e^{-x} dx\geq e^{-1}\int\limits_a^1 \frac {dx} x =-e^{-1} \log a$$
and the limit for $a \to 0^{-}$ does not exist.


Overview Standard Error Correction in Time Series / Panel Literature

Question: In microeconometrics, the time component is usually short (meaning that $T$ is fixed in $t=1,\ldots,T$). Serial correlation is here usually just seen as a negligible issue affecting the standard errors of a standard linear regression model (and not the point estimates) because it can be easily correct via robust standard error (both adjusting for possible heteroscedasticity and serial correlation, a similar approach as to use the Newey-West correction).
A lot of studies have however apparently calculated biased standard error in the difference-and-difference context as demonstrated by Bertrand, Duflo and Mullainathan (2003). They recommend, among others, to use block bootstrap for such an analyses. Yet, their study focuses mainly on the validity of different correction mechanisms with respect to the number of available groups ($n=1,\ldots,N$ in a panel context) but less on the length of the time component $T$.
I have some of questions based on my limited understanding:

Are there other good overviews I should be aware of?
Can you recommend an introduction or a paper about how to assure correct standard error in the time series literature for real-world time series data (not focusing on entirely on theoretical asymptotics but taking into account, for example, time series with multiple seasonalities such as hourly data; or long time series in a slowing but changing world / the effects of a slowly changing data generating process such as climate change). Here is a recent slightly related question which inspired me to raise these questions.
Is there a similar overview available differentiating more between shorter and longer panels?
Are the Bertrand et al. conclusions still considered as current state of the literature after more than 15 years?

An answer to any of these question is welcome!
Answer:
Baltagi, B. H. (2006). Panel Data Econometrics Theoretical Contributions and Empirical Applications. Emerald Group Publishing Limited.
See https://scholar.harvard.edu/files/stock/files/aea_2015_lecture4_har_rev.pdf and the other lectures in the same series (which you can watch online at https://www.aeaweb.org/conference/cont-ed/2019-webcasts (2019 version) or https://www.aeaweb.org/webcasts/2015/continuing-education.php (2015 version); it's a great series).
See (1).
No, more can be said. See Section 8.2 in https://mycourses.aalto.fi/pluginfile.php/203124/mod_resource/content/1/Angrist%20%20Pischke.pdf. There is no consensus yet regarding these issues.
Comment: @mlofton The link in item 4 gives the complete book (the published version just has a different design). There is an online version of the book mentioned in item 1. I provided two links for the publicly available videos corresponding to the lectures in the series on time series econometrics by Stock & Watson.
Comment: The Stack and Watson lecture series sounds amazing, I will go through it thanks! Any further ideas about published papers in the vein of Betrand et al. or a JEL/JEP paper?
Comment: AnonymousIGuess: 1) I have the Angrist book. Thanks. 2) I found the full set of Stock and Watson AEA notes and they look great ( and advanced ). Thanks for that too.
Comment: @AnonymousGuess: Thanks for the nice references. Is the third one a summary of the book or an addendum to the book ?
Comment: Would you mind providing a link to the videos  in 2) if they're available. If I need to join AEA, I'll check that out. Thanks.


GRE Coordinate Geometry Question

Question: Question: In the xy-plane, the point with coordinates (−6,−7) is the center of circle C.
The point with coordinates (−6, 5) lies inside C, and the point with
coordinates (8,−7) lies outside C. If m is the radius of C and m is an
integer, what is the value of m ?
Comment: I'm not sure how knowing what's inside and what's outside the circle allows me to find its radius.
Comment: If you find the distance from the center to each point, you can determine upper and lower bounds on the radius of the circle.
Answer: $m > 12$ and $m < 14$; we also know $m$ is integer. Therefore $m$ is?

GRE Coordinate Geometry Question


A quick Logarithm question

Question: Did I do this problem right?
$\log y= 10 + 2(\log x)$
$y= 10^{10} + x^2$?
Edit: How does $10^{\log (x^2)}= x^2$? I can't seem to find an explanation for this. All the websites that I found already assumes that it equals $x^2$. Sorry for the trouble.

I'm a bit lost :(.
Comment: Definition: $\log_a b=c\iff a^c=b$. Therefore $y=10^{10+2\log x}$.
Comment: It seems your only problem was that you said $10^{10+2\log x}=10^{10}+10^{2\log x}$ instead of $10^{10}\cdot 10^{2\log x}$.
Comment: Ask yourself this question "What is a logarithm?".
Comment: $\log x$ (log base 10 that is) and $10^x$ are inverse functions of each other by definition. That means that $10^{\log x} = x$ for all $x \in (0,\infty)$ and $\log(10^y) = y$ for all $y \in \mathbb R$.
Answer: You had a good idea by raising $10$ to the power of each side.
Note, however, that $a = b+c$ implies that $10^a = 10^{b+c} = 10^b\times 10^c$
So,
$\log_{10} y = 10 + \log_{10}(x^2)$
$10^{\log_{10}y} = 10^{10+\log_{10}(x^2)} = 10^{10}\times 10^{\log_{10}(x^2)}=\dots$
Answer: just remember that $a^{\log_a x}=a$ & $\log_a x=y$ then $a^y=x$. I think you have wrighten wrong, it has to be $y= 10^{10}\times x^2$.
or $\log a-\log b=\log\dfrac{a}{b}$ $$\log y= 10 + 2(\log x)=10+\log x^2$$
$\log y-\log x^2=10$ thus $\log \dfrac{y}{x^2}=10$ then $\dfrac{y}{x^2}= 10^{10}$ hence $y= 10^{10}\times x^2$.
Answer: Here is why $10^{\log \left(x^2\right)}= x^2$. It's almost exactly the definition of logarithm.

Definition of logarithm: $\log_a b=c\iff a^c=b$

In this case: $\log \left(x^2\right)=c\iff 10^c=x^2\ \ \ (1)$
Now remember: $a=b\iff 10^a=10^b$
(it's because $f(x)=10^x$ is a strictly increasing function).
Therefore: $\log\left(x^2\right)=c\iff 10^{\log\left(x^2\right)}=10^c$, which by $(1)$ equals $x^2$.

So to complete the problem:
$\log(y)=10+2\log x\iff 10^{10+2\log x}=y$ (by definition).
$10^{10+2\log x}=10^{10}\cdot 10^{2\log x}$ by exponent property: $a^{b+c}=a^b\cdot a^c$.
$10^{10}\cdot 10^{2\log x}=10^{10}\cdot 10^{\log \left(x^2\right)}$ by logarithm property: $b\log a=\log a^b$.
$10^{10}\cdot 10^{\log \left(x^2\right)}=10^{10}\cdot x^2$ (see beginning of the answer).

A quick Logarithm question


forms of same id in while loop - how to post formdata of user submitted form to php with jQuery AJAX?

Question: I have a while loop which creates forms like:
<?php
$i = 1;
while($i<10){
    ?>
<form id="update">

    <?php echo $i;?>

    <input type="text" maxlength="5" class="input-xs valid" name="plus" value="" />
    <input type="submit" name="submit" class="btn btn-info btn-sm" value="Update" />
    <input class="input-sm slip" name="slip" value="" disabled />

</form>

<?php $i++; }  ?>

I want to post the formdata of user-submitted form with jQuery AJAX.
Comment: Possible duplicate of [jQuery Ajax POST example with PHP](https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php)
Comment: First off, each form needs their own ID. ID's must be unique within the document. Then regarding posting the form using ajax, there are MANY tutorials online. You should really read some and make some attempts before asking.
Answer: your question is not clear but here is the answer
 - if you are generating the forms on the basis of while loop, then you need to pas that $i in every where in the form
<?php
            $i = 1;
        while($i<10){

          ?>
    <form id="update_<?php echo $i ?>">

          <?php echo $i;?>

          <input type="text" maxlength="5" class ="input-xs valid" id="plus_<?php echo $i?>"  name="plus" value="">
          <input type="button" name="submit" class="btn btn-info btn-sm" value="Update" onclick="sub_form(<?php echo $i; ?>)">
          <input class="input-sm slip" id="slip_<?php echo $i?>" name="slip" value="" disabled/>

         </form>
          <?php $i++; }  ?>

AJAX
function sub_form(val){
   var plus = document.getElementById('plus_'+val).value;
   var slip = document.getElementById('slip_'+val).value;
   $.ajax(
                {
                    type:"post",
                    url: "your url here",
                    data:{ plus:plus, slip:slip},
                    success:function(response)
                    {

                    }

                }
            );
}

hope it will work for you
Answer: You should add a class in form HTML node as below:
<form class="anyclass" action="add your action where you want to post form">

And after this, you can submit form as below:
$(".anyclass").submit(function(e) {
e.preventDefault
$.ajax({
       type: "POST",
       url:  $(this).attr('action'),
       data:  $(this).serialize(),
       success: function(data)
       {
               alert('form submitted herer');
       }
});

Hope it helps you.


One of the tuning pegs is at the end of its range on my Floyd-Rose guitar, what can I do?

Question: After getting my Washburn serviced, including having the double-locking floating bridge re-floated with new strings, I'm reaching the point where one string is right at the limit of tightening using the bridge tuning peg. The others have lots of travel and the strings are nowhere near work out, they haven't had lots of use and I play very gently.
Since it's just one string - the D from memory - can I get away with 'cheating' and give myself a bit more space without messing things up? For instance if I:

slacken the neck bolt
slacken the bridge peg
tighten up the head tuning peg a turn
re-lock the neck bolt
re-tune using bridge pegs

In my mind this would work since I'm never drastically reducing tension in any string and only unlocking one. But I've heard how notoriously fickle these setups can be!
Comment: I plead ignorance here: why wouldn't you adjust the machine head so the string's in tune at the midpoint of the bridge adjuster range?
Comment: That's pretty much what I _am_ suggesting. I think that's how it was with new strings but as they've stretched from new I ran out of room so I'm proposing to "reset" this but am nervous in case I unbalance the floating bridge
Comment: (Make sure to do your steps in order. -captain obvious)
Comment: OK, well... :-) I doubt you'll do anything to the bridge just by releasing tension on a single string (and re-threading into the machine head).
Comment: Yeah, but with the bullet points I found myself re-reading the question. I was just being pedantic. I imagined a slightly smaller chance of breaking a string than if you started with step 3. I'm guessing none of this should really mess with the set-up, right? People break strings, I imagine that the guitar should still be fine even at that worse case(broken string). (I'm asking, I guess.)
Comment: I _believe_ you're supposed to be able to change a single string on a floating bridge but I think even then you might have to muck about with all the string tensions...?
Comment: I would hope that if you use precisely the same string size it should not effect your set-up, in principal. The intonation settings and spring tension on the bridge should not change dramatically from normal string activities. I would expect that changing the size and possibly type of string would make a difference though.
Answer: It makes sense for the bridge tuners to be about in the middle of their travel (a couple of turns in from the top is recommended) while the new strings are being tuned using the head machine heads. That way, any subsequent adjustment at the bridge will be available, up or down. Maybe the tech didn't do this, but should have. Yes, your plan should work - and while you're at it, check each bridge adjuster for being in the middle of its travel . Then you've plenty of leeway. Nothing needs taking off, just slackening.When you say neck bolt, hope you don't mean the truss rod!
Comment: @jammypeach - you may find that starting with the bottom strings is slightly more productive as they present more tension, so by the time you're at the top, the guitar has more or less stabilised.
Comment: Neck-bolt == locking nuts at the neck :)
Comment: I have one of these - the best way I've found to get it in tune is what this answer advises. I slacken the locking bolts on the neck, move the fine-tuners to the midrange, then use the machineheads on the head to tune. when in tune, re-lock the nut and tune with the fine tuners. When I'm tuning mine initially, my general rule is tune string 1, then tune 2, then go back and tune 1. then tune 3, and after that, 1 and 2, then 4, 1,2,3, etc. this way you don't get to the high E and realise that the rest of the strings are a half step out now. gradual adjustments.
Comment: @Tim right you are, and I usually do - I realise I've given the impression to start with the bottom strings but I really should have said top or just whatever string you normally start with. I'll edit the comment to make it clearer, thanks. Edit - I can't edit it now but your comment stands :)
Comment: @jammypeach good advice but this isn't a question about restringing and tuning, but tweaking the setup on an already-tuned guitar. I suppose in theory though, slackening all the neck locking bolts shouldn't cause harm in itself as the tensions aren't altered.
Comment: @Mr.Boy thanks, but I disagree - retuning may be required if you unlock the nuts as the tension may be different behind the locked nut, which may affect the other strings - especially as on most locking nuts, it's one lock per two strings. I find that if I have to make this kind of tweak, retuning the other strings is sometimes required, so thought I'd add some supporting info to this answer - my comments aren't intended to be answers on their own. Good luck with your tweaking anyways!
Comment: Oh yeah good point. Normal things aside, I cannot be the only one who accidentally tried tuning a locked FR guitar using the head-tuners before going "oh crap" as I realised why nothing was happening!
Comment: @Mr Boy - ''it happens!
Answer: In my experience it is better to move the bridge tuners close to the top, i.e. the position where you can hardly tune down but you have the maximum range for tuning up. Then you tune the guitar properly using the machine heads, and then you lock the system. The reason is that the strings always get lower (i.e. they relax), you hardly ever need to tune them higher, unless you're experiencing drastic (and lasting) temperature changes.
Comment: Not to mention that overtightening strings is a good way to break them :-(
Comment: One strings have settled/bedded in I tend to find they are quite stable and detune due to temperature, i.e. in both directions. At least that's the case with my acoustic... maybe some would say once they stop stretching they should be replaced but that's not my approach.
Comment: @Mr.Boy: I'm just talking about my experience with the electric guitar. At "normal" rehearsal/gig temperatures I never needed to use the bridge tuners to tune down.


Did something change with Angular 8 to 11 to cause Child to Parent communication to throw ExpressionChangedAfterItHasBeenCheckedError

Question: I figured I should learn my techniques so I was adding to my Angular 11.x application.
Getting this error ( which I did see other stackoverflow questions on and blogs about it but those issues seem to be more complicated things going on).

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Hello from the Child'.

Parent HTML :
 <app-child></app-child>
 Message from child : {{ ParentGettingChildMessage }}

Parent Component code:
import { Component, ViewChild, AfterViewInit} from '@angular/core';
import { ChildComponent } from 'src/app/child/child.component';
@Component({.... })

export class ParentComponent implements AfterViewInit {

   @ViewChild(ChildComponent) child;

   ParentGettingChildMessage: string;

   constructor() { }

   ngAfterViewInit(){
      this.ParentGettingChildMessage = this.child.message;
   }

}

Child Component:
export classs ChildComponent implements OnInit {
    message = "Hello from the Child";
 .....
}

The blog that I found it on seems to be written with Angular 8 in 2020 -  It seems reasonable way to communicate from Child to Parent  for reference > www  .  thirdrocktechkno . com/blog/how-angular-components-communicate/
Why am I getting this error?
Comment: added the message string from the ChildComponent.
Answer: There is a simple fix for this. This only happens when angular is in dev mode. It usually shows this error when angular checks values it has passed to the child component has been changed. This is an elaborative article which tells in depth how it happens, you should look at it.
ngAfterViewInit(){
     setTimeout(() => {
       this.ParentGettingChildMessage = this.child.message;
     })

   }

Comment: I am a bit concerned as I thought for sure some guys at my work job didn't need to do this..   thoughts?


Average precision/recall of multiple classifiers on the same dataset?

Question: If I have some N human classifiers that can only predict in terms of 0 or 1 (not probabilistic, and also disregarding their own uncertainty. They either know or they don't), and each yield different precision/recall metrics for the same dataset, is there anything wrong with saying the average precision is then simply the arithmetic mean?
$$\frac{0.95 + 0.82 + 0.92}{3} = 0.90$$
Or is it "better" to calculate a final score from the majority vote (and why? Doesn't this add extra steps to calculate model uncertainty)?
Comment: You mean, other than the "general" problems with accuracy (and precision)? [Why is accuracy not the best measure for assessing classification models?](https://stats.stackexchange.com/q/312780/1352) More to the point, what is your goal in averaging accuracies? If you have multiple classifiers, you could let them vote (or - much better - combine their probabilistic predictions) and typically get better results.
Comment: Good suggestions. Rephrased problem.
Comment: Hm. Thanks for the edit. I was going to answer that there is nothing wrong with the "average precision" - until I saw your last paragraph. What is "besser" depends on what you want to do. Averaging precisions is not the same as counting votes to classify (and possibly calculating the precision of this ensemble classifier). You can average precisions in the way you propose. But what is your purpose in doing so? Is this just for information?
Comment: The purpose is basically to compare humans to a trained classification model, and also get an estimate of the variability between different humans doing the classification.
Answer: If the 3 classifiers all make the same mistakes, then their joint precision is approximately the mean of their individual precisions.
If the 3 classifiers all make completely different sets of mistakes, then their joint precision may be much higher than the mean.  Imagine the case where each individual mistake is only made once by a single classifier, whereas the other two classifiers don't make that mistake.  In that case, you could argue the joint precision is 100%, depending on how you are defining 'average precision', even though all the classifiers have less than 100% precision.
The difference between the mean of the individual precisions, and the precision of the ensemble should be informative as to the degree of independence between the mistakes made by the different classifiers.


How do I synchronize users and their roles between sites?

Question: I've set up a multi-site Drupal installation. The main site is example.com and we also have a.example.com and b.example.com.
I own example.com, and I rent a.example.com out to Person A, and b.example.com out to Person B. They pay their site rent using the UberCart role-purchase feature on my site. I need a way to set up my site so that Person A and B can log into example.com and pay their site rent, and have the upgraded role transfer over to a.example.com and b.example.com as well, automatically so that after a month if Ubercart downgrades their role I don't have to go in and manually unassign them.
Things I've tried:

Shared users table. This doesn't work because I don't want Person A to be able to see people who have signed up for b.example.com and a shared user site means everyone can see everything.
Domain Access. This works ok but is really shaky, and I'm planning on moving up to z.example.com and onward in the future, so unless there's a way to keep things more separate than I was able to, I don't think this is feasible. For example, if each site has an 'about us' page then I would see 26 "About Us" pages from my uid=1 account. Additionally, I didn't see any way of separating the UberCart module as much as I would like. Ubercart Marketplace is a no-go because I'm not taking any commission like it was designed to do, and UC_Domain hasn't been upgraded to drupal 7 yet.
Account Sync. This seemed like the closest, but the plugin appears broken, I get tons of XML-RPC errors when I try it, and generally it doesn't work as described, and seems to only sync the first account before breaking. Google searching the errors brings back nothing apart from warnings that XMLRPC is potentially dangerous.
Bakery. This seems great but it doesn't share roles across subsites unfortunately. I've been trying to add that in, but before I spent the time I wanted to see if there's some other way that I can go about this

If anybody needs clarification on anything let me know, I really want to get this solved and can't find anything online.
Comment: Easiest way to do it is by exporting roles via features. [Features](https://www.drupal.org/project/features)
Comment: Related: [Bakery doesn't pre-sync accounts](http://drupal.stackexchange.com/q/196530/1908)
Answer: Hope the question is for Drupal 7 or lesser. If it's for Drupal 8, the solution is close to impossible. And for future Drupal versions, as per the current plan for Drupal 9, multi-site option itself shall not be available, which mean sharing user role using Drupal's default options, is clearly impossible.
In Drupal 7 or lower, in the multi-site setup, it's very easily possible to configure each site to use different databases for their contents, and share the same table (from same database) just for users, roles, sessions, etc. If you don't want to share users, but want to share only roles, even that is possible. For this, the settings.php for site A and site B has to be as below:
settings.php for Site A:
<code>/*
 * Database Settings for 'Site A'
 */
$databases['default']['default'] = array (
    'database' => 'site_a_db_name',    // Specify Site A's main database name
    'username' => 'site_a_db_username',
    'password' => 'site_a_db_password',
    'prefix' => array(
        'default' => 'site_a_prefix_',    // Prefix for all tables in Site A's main database (specified above), other than for the tables specified below
        'role' => 'shared_db_name.shared_prefix_',              // Shared database name and prefix for the 'role' table
        'users' => 'shared_db_name.shared_prefix_',             // Shared database name and prefix for the 'users' table
        'authmap' => 'shared_db_name.shared_prefix_',           // Shared database name and prefix for the 'authmap' table
        'sessions' => 'shared_db_name.shared_prefix_',          // Shared database name and prefix for the 'sessions' table
        'profile_fields' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_fields' table
        'profile_values' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_values' table
    ),
    'host' => 'localhost',
    'port' => '3306',
    'driver' => 'mysql',
    'collation' => 'utf8mb4_general_ci',
);
</code>
settings.php for Site B:
<code>/*
 * Database Settings for 'Site B'
 */
$databases['default']['default'] = array (
    'database' => 'site_b_db_name',    // Specify Site B's main database name
    'username' => 'site_b_db_username',
    'password' => 'site_b_db_password',
    'prefix' => array(
        'default' => 'site_b_prefix_',    // Prefix for all tables in Site B's main database (specified above), other than for the tables specified below
        'role' => 'shared_db_name.shared_prefix_',              // Shared database name and prefix for the 'role' table
        'users' => 'shared_db_name.shared_prefix_',             // Shared database name and prefix for the 'users' table
        'authmap' => 'shared_db_name.shared_prefix_',           // Shared database name and prefix for the 'authmap' table
        'sessions' => 'shared_db_name.shared_prefix_',          // Shared database name and prefix for the 'sessions' table
        'profile_fields' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_fields' table
        'profile_values' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_values' table
    ),
    'host' => 'localhost',
    'port' => '3306',
    'driver' => 'mysql',
    'collation' => 'utf8mb4_general_ci',
);
</code>
As shown in the above code, under 'prefix' array, we can specify separate database and prefix for each different table used in the site. Other than those tables exclusively specified in the 'prefix' array, for all other tables, the prefix specified as 'default' shall be used.
In Drupal 8, user/role/session sharing is not as easy as in Drupal 7, because in Drupal 8, many of the informations, including the user roles, are part of a shared table (that shared table is meant for storing many different variable values, and roles are just part of that).
Answer: You could use a secondary database (or a specific table) for all your sites where you manage each site's user roles. You would then need to:

Define a cron job for each site (a-z).example.com which looks up the database and updates the roles of the users on the site
Update the database when people buy on example.com
Trigger cron from example.com after the UberCart transaction is completed

The other way to do that would be to expose a POST (REST) web service endpoint on the sub-sites which will trigger a function to update the roles based on the data submitted. You then call that endpoint after the UberCart transaction.
In both cases, I'm assuming there's a hook you can use to do things after a UberCart transaction (or maybe something like Rules).
Answer: Easiest way if you do not want to develop so much is change a bit about sharing tables:
https://www.drupal.org/node/22267
But if you only want to share roles just sare the roles table.
This is the exaple you can use:
<code>$db_prefix = array(
    "default" => "slave1_", // the prefix for tables that are not shared.
    "role" => "master_",
);
</code>
Answer: Create an additional database. Can be an own drupal instance or a php framework like yii, where you can model the database by your own. There you manage the account data. From there you sync the roles via a cronjob (e.g. a REST call). After you have loaded the account credential data, you use this two Drupal API functions to update the account credentials:

load the user object: https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load/7.x
save it: https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_save/7.x

This approach will do the job, if you are not just looking for a finished module, which does the job for you. Then you get you better a coder, who helps you out.


Is the output of a variational autoencoder meant to be a distribution that can be sampled, or a sample directly?

Question: It is difficult to ask this question succinctly in the title, so let me explain.
From all the examples of VAEs I have seen, there seem to be 2 approaches used to implement them.

In these,  approaches, the output of the decoder is a
distribution. Specifically, a Bernoulli distribution. The loss is
related to the likelihood of the input data with respect to this
distribution. When generating new variables, not only are samples
drawn from the latent space distributions, but also, samples are
drawn from the output distributions. I have a question related to
the parameterization of the output distributions using this
approach, but I will save that for the end.
In these,  approaches, the output of the decoder is the
    actual predicted data points, which are then compared to the input
    to calculate the loss, as mean squared error. The only thing that
    ever gets sampled is the latent space.

These 2 approaches are fundamentally different. I notice that in the first approach, the authors relate the idea to a statistical/probabilistic motivation, and it seems to have a solid theoretical foundation. For this reason I am inclined to adopt the 1st approach.
So my questions are:

Are either of these approaches considered to be superior?
The second question is more of a sense check: Bernoulli distribution
makes sense for grey scale pixels. But for something like stock
returns, we would want some other distribution, such as a
t-distribution. In this case, the output of the encoder would be 3
vectors, 1 for location, 1 for scale, and 1 for degrees of freedom,
right?
Answer: Question 1:
The output of the decoder aims to model the distribution $p(x|t)$, i.e. the distribution of data $x$ given the latent variable $t$. Therefore, in principle, it should always be probabilistic.
However, in some cases, people simply use the mean squared error as the loss and, as you said, the output of the decoder is the actual predicted data points. Note that this approach can also be viewed as probabilistic, in the sense that it is is equivalent to modeling $p(x|t)$ as Gaussian with identity covariance, $p(x|t) = \mathcal{N}(x|\mu(t), I)$. In this case, the output of the decoder is the mean $\mu(t)$ and, therefore, for an example $x_i$, you get the following reconstruction loss:
\begin{align}
-\log(p(x_i | t_i)) &= -\log \left(\frac{1}{\sqrt{(2\pi)^k |I|}} \exp \left(-\frac{1}{2}(x_i-\mu(t_i))^\intercal I (x_i-\mu(t_i))\right)\right) \\
&= \frac{1}{2}||x_i - \mu(t_i)||^2 + \text{const.}
\end{align}
which, as you can see, is proportional to the mean squared error (plus some constant).
Question 2:

Bernoulli distribution makes sense for grey scale pixels.

This is not quite true. The correct statement would be that Bernoulli distribution makes sense for black and white (i.e. binary) images. The Bernoulli distribution is binary, so it assumes that observations may only have two possible outcomes. It is true that people sometimes use it for grayscale images, but this is an abusive interpretation of the VAE. It may work pretty well for datasets that are almost black and white, like MNIST. However, a binarized version of the MNIST dataset exists and, in rigor, this is the version that should be used together with a Bernoulli VAE.

But for something like stock returns, we would want some other distribution, such as a t-distribution. In this case, the output of the encoder would be 3 vectors, 1 for location, 1 for scale, and 1 for degrees of freedom, right?

I would try a Gaussian first, $p(x|t) = \mathcal{N}(x|\mu(t), \sigma^2(t))$, so the decoder would output two values, $\mu(t)$ and $\sigma^2(t)$. But yeah, if you really want a t-distribution, then that is the way to go.
Comment: Could you please explain why Bernoulli distribution makes sense only for black and white images? I understand what Bernoulli distribution does, but we are choosing a distribution for the latent space, not for the data samples space (which is binary), so I don't find it quite evident why it makes sense to select this distribution for the latent space. Also, I have seen in some papers (e.g. $\beta$-VAE) that Bernoulli distribution is used for non-binary datasets.
Comment: In the second case, N(x|mu, sigma^2), the expression for -log(p(x|t)) would include the terms 1/sigma^2 * ||x - mu||^2 + log(sigma). So the loss function would change. But what I don't understand is, how to output sigma from the decoder? Is it similar to how encoder outputs mu_z, sigma_z ? or there is some other technique?
Comment: I meant that a Bernoulli posterior $p(x|t)$ makes sense for black and white images, i.e. those where $x_i \in \{0,1\}$. I was not talking about the posterior distribution on the latent space $p(t|x)$, which I was assuming to be Gaussian (as in "vanilla VAE"), but this need not be the case.
Comment: You could that, but, in that case, the optimization problem is ill-posed (see https://stats.stackexchange.com/questions/373858/is-the-optimization-of-the-gaussian-vae-well-posed). Alternatively, you can simply set the variance to a fixed value, as a hyperparameter.
Comment: [This NeurIPS '19 paper](https://proceedings.neurips.cc/paper/2019/file/f82798ec8909d23e55679ee26bb26437-Paper.pdf) is all about the Bernoulli black/white/grayscale thing and proposes a simple solution: using a ContinuousBernoulli output distribution, which has proper support in [0, 1] (and not just in {0,1} like Bernoulli).


Residuals in linear regression - variance and independence

Question: Let's assume a simple linear regression
$$
y = \beta_0 + \beta_1 x + \varepsilon
$$
where $\varepsilon_i$ are independent and come from $\mathcal{N}(0, \sigma^2)$. We define residuals as
$$
e = y - \hat y
$$
I know that
$$
Var(e_i) = \sigma^2(1-h_{ii})
$$
where
$$
 h_{ii} = (X(X^TX)^{-1}X^T)_{ii}
$$
so residuals are not independent (we know that from the fact $X^T e = 0$ regardless of the presence of the intercept term) and do not have equal variances. Mathematically I understand all the formulas, but my question is: why is that? Why in reality, even for good data like this
<code>x <- rnorm(100, 0, 1)
eps <- rnorm(100, 0, 1)

y <- 1 + 5*x + eps
mod <- lm(y ~ x)

X <- model.matrix(mod)

t(X) %*% solve(t(X) %*% X) %*% t(X)
</code>
variances aren't equal and residuals are dependent? What's the underlying reason for that? From the practical point of view.
EDIT: I am aware of the infulence, but the question is why the estimated errors (i.e. residuals) never have equal variances, regardless of how I specify the model matrix $X$.
Comment: It is instructive to look at intuitive, computationally simple cases.  Consider, for instance, one value of $(0,0)$ and two (or more) values $(1,y_j).$ You don't have to do any arithmetic to know what the residuals are and to see why they have (radically) different variances.
Comment: You might benefit from considering the idea of *influence*. Start first with considering how much a small change to an observation influences its own fitted value in direct terms ($\frac{\partial \widehat{y}_i}{\partial y_i} = h_{ii}$), a sense of how directly a fitted value responds to the "pull" of the observation it approximates. Note that typically these are different for different observations -- values not near the mean in x-space have large $h_{ii}$. There's a somewhat related idea in regression diagnostics, DFFIT, where $\text{DFFIT} = \widehat{y}_i - \widehat{y}_{i(i)}$.
Comment: which is how much the fit changes if you leave out its observation. See also Ye, J. (1998), "On Measuring and Correcting the Effects of Data Mining and Model Selection", *Journal of the American Statistical Association*, 93 (441), 120–131, Eqn 7, and note that this general sense of model d.f. is the sum of these observation influences $\frac{\partial \widehat{y}_i}{\partial y_i}$. Different points "use up" more or less of the model's d.f. in pulling the fit toward them. A point with a strong influence on its own fit (under some model) will tend to have its fitted value pulled more toward it.
Comment: @whuber Thank you. But still, how can we specify variance for a single residual? We only have one point.
Comment: (maybe not following the discussion), but you fix the x's and then generate multiple samples of the noise 'eps' for each x
Answer: Say you start with an iid sequence $\{\varepsilon_i\}$. Now using OLS algebra, we have, uniformly in $i$ under OLS assumptions, that $$e_i-\varepsilon_i=O_p\left(N^{-1/2}\right),$$ implying that for a large sample the difference between $e$ and the model error term vanishes such that $e_i$ inhertis the properties of $\varepsilon$.
Note also that uncorrelatedness as noted in your post, does not imply independence. In fact, OLS chooses the model parameters such that the OLS residuals are orthogal to the explanatory variables; this is by deifinition. Further, the variance of $e_i$  in your post is the conditional variance and not the unconditional one (which is not in general tractable).
Addendum:
\begin{align}
e&=Y-\widehat{Y}\\
&=Y-X\widehat{\beta}\\
&=X\beta+\varepsilon-X\widehat{\beta}\\
&=X\left(\beta-\widehat{\beta}\right)+\varepsilon\\
\end{align}
Now, under OLS assumptions we have $E(\beta-\widehat{\beta})=0$ and that $Var(\beta-\widehat{\beta})\propto \frac1N$, which implies $\beta-\widehat{\beta}=O_p(N^{-1/2})$.
Comment: Thank you. How did you get the formula for $e_i - \varepsilon_i$? And another question: although dependence on sample size seems very rational and intuitive, I don't quite get it. Let's say we have a sample of size $10$, with values $x_1^*, ..., x_{10}^*$ and then "add" $90$ different observations. Why would the corresponding residuals for $x_1^*, ..., x_{10}^*$ change? Is it due to the fact that as there is more data then the impact of each observation averages out?
Comment: Please see the addendum. Note that "equal variance" would only make sense "asymptotically". In small sample you do not necessarily have the same variances.
Answer: Your claim is not true -- there does exist some design matrix $X$ that gives you all equal residual variances.  One example is as follows:
\begin{align*}
X = \begin{bmatrix}
1 & 1 \\
1 & 1 \\
1 & -1 \\
1 & -1
\end{bmatrix}.
\end{align*}
It is easy to verify that the diagonal elements of $H$ are $\{1/2, 1/2, 1/2, 1/2\}$, which means the variance of each residual is $\sigma^2(1 - 1/2) = \sigma^2/2$.
Answer: Not an answer, but reading your post I am puzzled by your conclusion that the estimated $e$ terms are NOT independent, given that the true residuals $\epsilon$ are? Could you explain that please? Thanks.
Comment: Residuals are only the *estimates* of unknown true errors. When you perform OLS, you seek for the linear combination $\hat y = Xb$ of columns of the design matrix $X$ such that the distance from $\hat y$ to your observed vector $y$ is minimized. That happens when the vector $e = \hat y - y$ is orthogonal to the column space of $X$. If the vector is orthogonal to the span of $X$, then it is orthogonal to each of the generators.
Comment: Orthogonality happens when the inner product of two vector is $0$. Recall that for a model with the intercept you have a column of ones (denoted by $\mathbb{1}$) in $X$. Thus $\mathbb{1}e = 0$ what literally means $e_1 + ... + e_n = 0$, so $e_1, ..., e_{n-1} = -e_n$. If e.g. $e_1, ..., e_{n-1}$ are free to vary, then $e_n$ DEPENDS on the values of $e_1, ..., e_{n-1}$.
Comment: OK Thanks, no I see what you meant. But isn't knowing this an answer to you initial question too? I mean, it's perfectly understandable then that/why such dependence exists, just like the different variances of the e residuals are evident.


Guidelines for piano composition and transcription

Question: I'm a classical guitar student but I always loved the piano. Though I never owned one, most of my musical ideas come to me as harmonies on the keyboard so I often have to translate that into something playable on the guitar or the way around (when I compose with music software).
Which would be the main guidelines one should follow when

arranging piano music for the guitar
arranging guitar music for the piano
Answer: I think I see two slightly different questions here.  It seems like you are looking for guidelines for writing parts on piano to play on guitar and also how to arrange a piano part for guitar.  I will assume you are playing guitar in the standard tuning.
The largest difficulty you can encounter will come from the density of the chord voicings.  On a piano, you can have 10 voices, on a guitar you can only have 6 (this is with each finger triggering only one note per on the piano but there are plenty of ways to play more than that).  Beyond that the piano can accommodate clusters of notes, which are several notes within a small range, and a guitar has no such capacity.  Even a simple triad in root position can be uncomfortable to play on guitar.  So if you are trying to write music on the piano to play on the guitar, you should make sure that the chord voicings are playable, paying attention to the density of voicings.  Triads are most easily played in 2nd inversion (5th in the bass) on guitar (and first inversion is more preferable than root position).  It is very easy to write a part on piano that is impossible to play on guitar.
If you are trying to arrange a piano part to play on guitar, then you need to find the most important pieces and hang onto them when it gets translated to guitar.  The most obvious thing here is the melody.  If there is a melody, or even somewhat melodic motion, that must be preserved.  From there you either need a good ear or some good theory.  There will be a lot of time when arranging a piano part for guitar that you won't be able to play all the notes.  In these circumstances you will have to boil down what is there and attempt to maintain the harmony.  First, you can remove any repeated notes within the harmony.  Then the least important voice in a harmony is the 5th, so it would be the first to go of the unique voices.  You will also want to pay attention to the voice leading.  If there is linear motion imbedded in your harmony, you may want to hang on to that.
The idea is that you are trying to find what about the piano part makes it a 'part' in itself.  Why is it a part and not just chord changes?  It is the melody and the motion within the harmony.  You are looking for what makes it specific.  One easy rule about how to translate from one instrument to the other: Sing the part and whatever you sing has to be in the arrangement for the other instrument, as it is definitively the part.
Addendum:
When writing piano parts on a guitar you will want to be mindful of the rhythmic nature of the guitar and the use of muted strings.  Chords played in fast rhythms that are strummed out don't translate well to piano.  One, because the motion is more physically demanding on the piano, and two, because the mechanics of a piano require the key to depress before it can be struck again.  Pianists will often use more than one finger on a single key to play faster rhythms.
Muted notes are also hard to emulate on piano.  There is no effective way to play a muted note on piano.  A lot of guitar parts will include strumming the whole time and muting the strings at times to create a syncopation and playing that note for note on a piano would be impossible.  The best you can do is try to substitute staccato stabs on the piano for the muted guitar notes.  The rhythmic nature of strumming a guitar can bring a lot of groove to the song/piece and this groove is what is hard to translate to piano note for note.  This mostly applies to rock influenced music, including funk/fusion.
Tone is another important thing to consider.  On a guitar most notes can be played on more than one string and there are some notes that can be played on 4 or 5, depending on how many frets you have.  Each string will have a different tone based on the gauge, material (wrapped or not, nylon/steel/etc., round/flatwound), and how far up or down the neck the note is.  The tone will also change based on where and how you pluck the string.  Playing close to the bridge will generate a thinner, sharper tone, while playing toward the neck will tend to be a warmer, more round tone.  As a Classical Guitarist, you may have noticed a slight difference in tone from finger to finger.  Some of this will come from where the finger is plucking the string, as I just mentioned, but the other difference comes from the hardness and width of the fingernail or finger.  These variations in tone can add a lot to the overall texture and feel of the piece.  The primary means of changing tone for a piano is to play another piano... beyond that, you can change the tone most dramatically by playing louder and softer.  Louder notes tend to be brighter and a softer attack will give a softer tone, which is also true for guitar.  The problem here is that this changes the volume of the piano.  If you are using an electric piano, you can adjust the volume but if there is a lot of dynamic variation, then it makes for a difficult performance.  The endless possibilities of tone that you can get from a guitar, even without amps and effects, can make translating the feel of the guitar to the piano difficult.
If you are arranging guitar parts to play on the piano, then what I mentioned previously about getting the melody and finding what makes it a 'part' is the most important thing.  Handling things such as the rhythmic nature of the guitar can be managed through arpeggiation or voice exchange.  By breaking the notes of the strumming up into two or more voices (left hand/right hand for example) or arpeggiating, faster and/or persistent rhythms become more playable (as well as more pianistic).  Depending on the dynamic depth and the amount of timbral variation, you may have to make a lot of sacrifices but you will want to find the middle ground.  Be a little loud for the tone if it is just a short section but don't play loud for tone for the whole piece, as this will affect how the rest of the players will have to play (unless it is a solo piece).
Ultimately when you are arranging a piece to be played on another instrument you want to capture its essence and you want to make it sound like that instrument is supposed to be playing it, such as arpeggiating chords being more pianistic than pounding out each note continuously.  Similarly, on a guitar strumming out the chords that are arpeggiated in a piano part may sound more like an authentic guitar part, depending on the genre.


SQL - Update table1 values from table2

Question: I am trying to update the value of column2 in table1 by getting the values from table 2 column2 with comparing both values of column1 on both tables. I am getting an error ("The multi-part identifier "dbo.PID0147_PEX_LCC.PEX_LCC" could not be bound.") with the query that I made below.
update
BluePrismProcesses.dbo.PID0147_DM
Set
PEX_LCC = dbo.PID0147_PEX_LCC.PEX_LCC
from
dbo.PID0147_DM d, dbo.PID0147_PEX_LCC p
where
d.CtryGrName = p.EWS_Country;

Answer: Its just Alias name makes a difference
Begin Tran
    update
    d
    Set
    PEX_LCC = p.PEX_LCC
    from
    dbo.PID0147_DM d inner join  dbo.PID0147_PEX_LCC p
    on
    d.CtryGrName = p.EWS_Country
    Rollback

;

SQL - Update table1 values from table2


Finding integration factor

Question: Could someone verify if the integrating factor for the differential equation is $e^x$ and whether it makes the DE exact or not.
$$\dfrac {dx}{dt} = \dfrac {(-x + e^t)}{(t - xt + e^t + e^x)}$$
My attempt:
$$Mdx+Ndt=0$$
 I rearranged the DE to get $N(t,x) = x - e^t$ and $M(t,x) = t - xt + e^t + e^x$ and differentiated $N$ wrt $t$ and $M$ wrt $x$. then did $(N' - M')/M$ to get 1 and integrated wrt $x$
Comment: Welcome to MSE. Can you show what you have done so far in the body of your question?
Comment: There is a sign difference so it seems it's not exact
Comment: As im unsure how to format, I rearranged the DE to get N(t,x) = x - e^t and M(t,x) = t - xt + e^t + e^x and differentiated N wrt t and M wrt x. then did (N' - M')/M to get 1 and integrated wrt x
Comment: Are you sure it's not $e^{-x}$ that is needed ?
Comment: The integrating factor should be $e^{-x}$ not $e^x$. I also posted your attempt in your question. Thats what you should always do. Post question and attempt toegether. Otherwise it's deleted or closed.
Answer: You made a little mistake for the integrating factor:
$$Mdx+Ndt=0$$
Differentiate $M$ wrt $t$ and $N$ wrt $x$:
$$\frac 1 {\mu}\frac {d \mu }{ dx}={\color {red}{\frac {M_t-N_x}N}} $$
$$\frac {d \mu }{\mu}=\frac {1-x+e^t-1}{x-e^t} dx$$
$$\frac {d \mu }{\mu}=-dx$$
$$\ln \mu =-x \implies \mu(x)=e^{-x}$$

Finding integration factor


Rename excel sheets with SQL Server Report Builder 2008 2.0

Question: I know you can name excel sheets with Report Builder 2008 2.0 R2 but I was wondering there was a way to do it in Report Builder 2008 2.0? Any work arounds?
Answer: To my knowledge this isn't possible; that feature was introduced in R2 specifically in response to user requests.


Concatenate the values of multiple arrays on VBA for Excel

Question: I am trying to concatenate the elements of multiple arrays in a final array that will store the concatenation. The code will first need to loop and store the values from cells then concatenate the stored values.
From cells:
A 1 V
B 2 W
C 3 X
D 4 Y
E 5 Z

New array being:
A1V
B2V
C3X
D4Y
E5Z

Sample code:
sub Concatenation()
Dim CntCol_updated As Long, CntRow_updated As Long
With Worksheets("Sheet1")

    CntCol_updated = Range(.Cells(1, 1), .Cells(1, 1).End(xlToRight)).Count
    CntRow_updated = Range(.Cells(1, 2), .Cells(1, 2).End(xlDown)).Count

    Dim Largeur() As Variant
    Dim Série() As Variant
    Dim Diamètre() As Variant
    Dim Charge() As Variant
    Dim Concatenated_Array() As Variant

    Largeur = Range(Cells(1, 9), Cells(CntRow_updated, 9))
    Série = Range(Cells(1, 10), Cells(CntRow_updated, 10))
    Diamètre = Range(Cells(1, 11), Cells(CntRow_updated, 11))
    Charge = Range(Cells(1, 12), Cells(CntRow_updated, 12))

    ReDim Concatenated_Array(UBound(Largeur))
    For i = LBound(Largeur) To UBound(Largeur)
          Concatenated_Array = Largeur(i) & Série(i)  & Diamètre(i) & Charge(i)
    Next i

    Range("A28:A53").value = Concatenated_Array

end with
end sub

Comment: And what isn't working with your code?
Comment: Largeur is a 2d array whereas concatenated is 1d. concatenated will also start at 0 whereas your other will start at 1.
Comment: `Concatenated_Array(i) = Largeur(i,1) & Série(i,1)  & Diamètre(i,1) & Charge(i,1)`.
Comment: If you have Excel 2016+, you could just use the `CONCAT` or `TEXTJOIN` function on the worksheet.
Comment: with SJR and T.M. comments, the macro works beautifully!
Comment: "Run-time error '9': subscript out of range" at line "Concatenated_Array = Largeur(i) & Série(i)  & Diamètre(i) & Charge(i)". I can't figure out what is wrong since my knowledge in arrays is kind of limited still.
Comment: … and `Range("A28").Resize(UBound(Concatenated_Array), 1).Value = Application.Transpose(Concatenated_Array)
`
Answer: When you read in ranges to an array you generate a 2d array with base 1. So, Largeur for example is 2d and starts at 1 whereas Concatenated_Array  is 1d and starts at 0.
Instead you could read the different ranges into one array, re-dimension to add another column at end, loop all rows in array and concatenate columns 1-4 and add to column 5. You can then access what you want from last column in array
Dim loopArray()
With ActiveSheet
    loopArray = .Range(.Cells(1, 9), .Cells(CntRow_updated, 12)).Value
End With
ReDim Preserve loopArray(1 To UBound(loopArray, 1), 1 To UBound(loopArray, 2) + 1) 'make space for concatenated column at end

For i = LBound(loopArray, 1) To UBound(loopArray, 1)
    loopArray(i, 5) = loopArray(i, 1) & loopArray(i, 3) & loopArray(i, 3) & loopArray(i, 4)
Next i


.NET Core WebAPI - AWS ElasticBeanstalk Nginx Configuration

Question: I've moved my .NET Core WebAPI to an AWS EB Instance. This works fine, however my file upload has now broken due to the Nginx 'client_max_body_size' configuration.
I've looked up how to override this, however I cannot get this to work. Here is my current set-up:

Within this file I have added:
client_max_body_size 0;

This file has no hidden characters (Notepad++ with show all chars on):

When my EB environment is updated I get the following eb-engine log:
2022/05/17 07:15:57.025994 [ERROR] An error occurred during execution of command [app-deploy] - [FlipProxyForDotNetCore]. Stop running the command. Error: copy proxy conf from staging failed with error validate nginx configuration failed with error Command /bin/sh -c /usr/sbin/nginx -t -c /var/proxy/staging/nginx/nginx.conf failed with error exit status 1. Stderr:nginx: [emerg] unknown directive "client_max_body_size" in /var/proxy/staging/nginx/conf.d/myConf.conf:1
nginx: configuration file /var/proxy/staging/nginx/nginx.conf test failed

My EB instance is running Amazon Linux 2/2.3.1.
What am I doing wrong?
Answer: The error msg
"client_max_body_size"

indicates that you have some non-ASCII characters () in your myConf.conf. Please open the file in a regular text editor and verify that it has only ASCII characters.
Comment: Well that's solved it!
Comment: I have updated my post. This is one thing I had checked, no dodgy characters are there.
Comment: @DuncanPalmer There must be something wrong with the file encoding. The fact that you can't see them, it does not mean they are not there. Maybe recreate the file from scratch.


Defining a Task Type in jBPM6 (in Eclipse)

Question: I use a simple Business Process with just Start->Task->End,
but after executing Test.java, which was successfully generated from my .bpmn file i become an error: "IllegalArgumentException:Cannot add asset...Task node[2] has no task type".
I suppose, i could resolve it by register my own custom task with .wid file. Unfortunately, after creating this file i cannot longer open my .bpmn file in eclipse.
Hope on your help.
Eclipse: Luna,
jbpm 6.3.0.Final,
bpmn-modeler:1.6
jUnitTest.java
<code>package org.jbpm;
import com.sample.ItemHandler;
public class Hello_WorldJUnitTest extends JbpmJUnitTestCase {

@Test
public void test() {
    KieSession ksession = createKnowledgeSession("sample.bpmn");
    ksession.getWorkItemManager().registerWorkItemHandler("Task", new ItemHandler());
    ProcessInstance processInstance = ksession.startProcess("com.sample.bpmn.hello");

}
</code>
ItemHandler.java
<code>    package com.sample;

public class ItemHandler implements WorkItemHandler {

@Override
public void abortWorkItem(WorkItem arg0, WorkItemManager arg1) {
    System.out.println("Work is aborted");
}

@Override
public void executeWorkItem(WorkItem arg0, WorkItemManager arg1) {
    System.out.println("You are welcome!");
    arg1.completeWorkItem(arg0.getId(), param);
}
</code>
Snippet from .bpmn source view
<code>        <bpmn2:task id="Task_1" name="Task">
  <bpmn2:extensionElements>
    <tns:metaData name="elementname">
      <tns:metaValue><![CDATA[Task]]></tns:metaValue>
    </tns:metaData>
    <tns:onEntry-script scriptFormat="http://www.java.com/java">
      <tns:script>import org.drools.core.process.core.datatype.impl.type.StringDataType;
  </tns:script>
    </tns:onEntry-script>
  </bpmn2:extensionElements>
  <bpmn2:incoming>SequenceFlow_1</bpmn2:incoming>
  <bpmn2:outgoing>SequenceFlow_2</bpmn2:outgoing>
  <bpmn2:ioSpecification id="InputOutputSpecification_1">
    <bpmn2:inputSet id="_InputSet_2" name="Input Set 2"/>
    <bpmn2:outputSet id="OutputSet_1" name="Output Set 1"/>
  </bpmn2:ioSpecification>
</bpmn2:task>
</code>
Answer: well it is saying that your task is Not Registered on BPMN file .change the first line of BPMN with .

Copy bpmn source view code into Notepad and modified the BPMN code and save it as sample.bpmn and paste inside resources before that remove existing sample.bpmn file .
<code>  <bpmn2:task id="Task_1" tns:taskName="Task" name="Task">
</code>
i am sure it will work for any doubt ask here